pdf.js 206 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483
  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.393';
  23. PDFJS.build = '2282c98';
  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.src = imageUrl;
  1425. }
  1426. /**
  1427. * The maximum allowed image size in total pixels e.g. width * height. Images
  1428. * above this value will not be drawn. Use -1 for no limit.
  1429. * @var {number}
  1430. */
  1431. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1432. -1 : PDFJS.maxImageSize);
  1433. /**
  1434. * The url of where the predefined Adobe CMaps are located. Include trailing
  1435. * slash.
  1436. * @var {string}
  1437. */
  1438. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1439. /**
  1440. * Specifies if CMaps are binary packed.
  1441. * @var {boolean}
  1442. */
  1443. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1444. /*
  1445. * By default fonts are converted to OpenType fonts and loaded via font face
  1446. * rules. If disabled, the font will be rendered using a built in font renderer
  1447. * that constructs the glyphs with primitive path commands.
  1448. * @var {boolean}
  1449. */
  1450. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1451. false : PDFJS.disableFontFace);
  1452. /**
  1453. * Path for image resources, mainly for annotation icons. Include trailing
  1454. * slash.
  1455. * @var {string}
  1456. */
  1457. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1458. '' : PDFJS.imageResourcesPath);
  1459. /**
  1460. * Disable the web worker and run all code on the main thread. This will happen
  1461. * automatically if the browser doesn't support workers or sending typed arrays
  1462. * to workers.
  1463. * @var {boolean}
  1464. */
  1465. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1466. false : PDFJS.disableWorker);
  1467. /**
  1468. * Path and filename of the worker file. Required when the worker is enabled in
  1469. * development mode. If unspecified in the production build, the worker will be
  1470. * loaded based on the location of the pdf.js file.
  1471. * @var {string}
  1472. */
  1473. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1474. /**
  1475. * Disable range request loading of PDF files. When enabled and if the server
  1476. * supports partial content requests then the PDF will be fetched in chunks.
  1477. * Enabled (false) by default.
  1478. * @var {boolean}
  1479. */
  1480. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1481. false : PDFJS.disableRange);
  1482. /**
  1483. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1484. * will automatically keep fetching more data even if it isn't needed to display
  1485. * the current page. This default behavior can be disabled.
  1486. * @var {boolean}
  1487. */
  1488. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1489. false : PDFJS.disableAutoFetch);
  1490. /**
  1491. * Enables special hooks for debugging PDF.js.
  1492. * @var {boolean}
  1493. */
  1494. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1495. /**
  1496. * Enables transfer usage in postMessage for ArrayBuffers.
  1497. * @var {boolean}
  1498. */
  1499. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1500. true : PDFJS.postMessageTransfers);
  1501. /**
  1502. * Disables URL.createObjectURL usage.
  1503. * @var {boolean}
  1504. */
  1505. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1506. false : PDFJS.disableCreateObjectURL);
  1507. /**
  1508. * Disables WebGL usage.
  1509. * @var {boolean}
  1510. */
  1511. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1512. true : PDFJS.disableWebGL);
  1513. /**
  1514. * Enables CSS only zooming.
  1515. * @var {boolean}
  1516. */
  1517. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1518. false : PDFJS.useOnlyCssZoom);
  1519. /**
  1520. * Controls the logging level.
  1521. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1522. * - errors
  1523. * - warnings [default]
  1524. * - infos
  1525. * @var {number}
  1526. */
  1527. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1528. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1529. /**
  1530. * The maximum supported canvas size in total pixels e.g. width * height.
  1531. * The default value is 4096 * 4096. Use -1 for no limit.
  1532. * @var {number}
  1533. */
  1534. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1535. 16777216 : PDFJS.maxCanvasPixels);
  1536. /**
  1537. * Document initialization / loading parameters object.
  1538. *
  1539. * @typedef {Object} DocumentInitParameters
  1540. * @property {string} url - The URL of the PDF.
  1541. * @property {TypedArray} data - A typed array with PDF data.
  1542. * @property {Object} httpHeaders - Basic authentication headers.
  1543. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1544. * Access-Control requests should be made using credentials such as cookies
  1545. * or authorization headers. The default is false.
  1546. * @property {string} password - For decrypting password-protected PDFs.
  1547. * @property {TypedArray} initialData - A typed array with the first portion or
  1548. * all of the pdf data. Used by the extension since some data is already
  1549. * loaded before the switch to range requests.
  1550. */
  1551. /**
  1552. * @typedef {Object} PDFDocumentStats
  1553. * @property {Array} streamTypes - Used stream types in the document (an item
  1554. * is set to true if specific stream ID was used in the document).
  1555. * @property {Array} fontTypes - Used font type in the document (an item is set
  1556. * to true if specific font ID was used in the document).
  1557. */
  1558. /**
  1559. * This is the main entry point for loading a PDF and interacting with it.
  1560. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1561. * is used, which means it must follow the same origin rules that any XHR does
  1562. * e.g. No cross domain requests without CORS.
  1563. *
  1564. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  1565. * where a PDF is located, a typed array (Uint8Array) already populated with
  1566. * data or parameter object.
  1567. *
  1568. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  1569. * to manually serve range requests for data in the PDF. See viewer.js for
  1570. * an example of pdfDataRangeTransport's interface.
  1571. *
  1572. * @param {function} passwordCallback is optional. It is used to request a
  1573. * password if wrong or no password was provided. The callback receives two
  1574. * parameters: function that needs to be called with new password and reason
  1575. * (see {PasswordResponses}).
  1576. *
  1577. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  1578. * object.
  1579. */
  1580. PDFJS.getDocument = function getDocument(source,
  1581. pdfDataRangeTransport,
  1582. passwordCallback,
  1583. progressCallback) {
  1584. var workerInitializedCapability, workerReadyCapability, transport;
  1585. if (typeof source === 'string') {
  1586. source = { url: source };
  1587. } else if (isArrayBuffer(source)) {
  1588. source = { data: source };
  1589. } else if (typeof source !== 'object') {
  1590. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1591. 'string or a parameter object');
  1592. }
  1593. if (!source.url && !source.data) {
  1594. error('Invalid parameter array, need either .data or .url');
  1595. }
  1596. // copy/use all keys as is except 'url' -- full path is required
  1597. var params = {};
  1598. for (var key in source) {
  1599. if (key === 'url' && typeof window !== 'undefined') {
  1600. params[key] = combineUrl(window.location.href, source[key]);
  1601. continue;
  1602. }
  1603. params[key] = source[key];
  1604. }
  1605. workerInitializedCapability = createPromiseCapability();
  1606. workerReadyCapability = createPromiseCapability();
  1607. transport = new WorkerTransport(workerInitializedCapability,
  1608. workerReadyCapability, pdfDataRangeTransport,
  1609. progressCallback);
  1610. workerInitializedCapability.promise.then(function transportInitialized() {
  1611. transport.passwordCallback = passwordCallback;
  1612. transport.fetchDocument(params);
  1613. });
  1614. return workerReadyCapability.promise;
  1615. };
  1616. /**
  1617. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1618. * properties that can be read synchronously.
  1619. * @class
  1620. */
  1621. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1622. function PDFDocumentProxy(pdfInfo, transport) {
  1623. this.pdfInfo = pdfInfo;
  1624. this.transport = transport;
  1625. }
  1626. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1627. /**
  1628. * @return {number} Total number of pages the PDF contains.
  1629. */
  1630. get numPages() {
  1631. return this.pdfInfo.numPages;
  1632. },
  1633. /**
  1634. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1635. * unique.
  1636. */
  1637. get fingerprint() {
  1638. return this.pdfInfo.fingerprint;
  1639. },
  1640. /**
  1641. * @param {number} pageNumber The page number to get. The first page is 1.
  1642. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1643. * object.
  1644. */
  1645. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1646. return this.transport.getPage(pageNumber);
  1647. },
  1648. /**
  1649. * @param {{num: number, gen: number}} ref The page reference. Must have
  1650. * the 'num' and 'gen' properties.
  1651. * @return {Promise} A promise that is resolved with the page index that is
  1652. * associated with the reference.
  1653. */
  1654. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1655. return this.transport.getPageIndex(ref);
  1656. },
  1657. /**
  1658. * @return {Promise} A promise that is resolved with a lookup table for
  1659. * mapping named destinations to reference numbers.
  1660. */
  1661. getDestinations: function PDFDocumentProxy_getDestinations() {
  1662. return this.transport.getDestinations();
  1663. },
  1664. /**
  1665. * @return {Promise} A promise that is resolved with a lookup table for
  1666. * mapping named attachments to their content.
  1667. */
  1668. getAttachments: function PDFDocumentProxy_getAttachments() {
  1669. return this.transport.getAttachments();
  1670. },
  1671. /**
  1672. * @return {Promise} A promise that is resolved with an array of all the
  1673. * JavaScript strings in the name tree.
  1674. */
  1675. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1676. return this.transport.getJavaScript();
  1677. },
  1678. /**
  1679. * @return {Promise} A promise that is resolved with an {Array} that is a
  1680. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1681. * [
  1682. * {
  1683. * title: string,
  1684. * bold: boolean,
  1685. * italic: boolean,
  1686. * color: rgb array,
  1687. * dest: dest obj,
  1688. * items: array of more items like this
  1689. * },
  1690. * ...
  1691. * ].
  1692. */
  1693. getOutline: function PDFDocumentProxy_getOutline() {
  1694. return this.transport.getOutline();
  1695. },
  1696. /**
  1697. * @return {Promise} A promise that is resolved with an {Object} that has
  1698. * info and metadata properties. Info is an {Object} filled with anything
  1699. * available in the information dictionary and similarly metadata is a
  1700. * {Metadata} object with information from the metadata section of the PDF.
  1701. */
  1702. getMetadata: function PDFDocumentProxy_getMetadata() {
  1703. return this.transport.getMetadata();
  1704. },
  1705. /**
  1706. * @return {Promise} A promise that is resolved with a TypedArray that has
  1707. * the raw data from the PDF.
  1708. */
  1709. getData: function PDFDocumentProxy_getData() {
  1710. return this.transport.getData();
  1711. },
  1712. /**
  1713. * @return {Promise} A promise that is resolved when the document's data
  1714. * is loaded. It is resolved with an {Object} that contains the length
  1715. * property that indicates size of the PDF data in bytes.
  1716. */
  1717. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1718. return this.transport.downloadInfoCapability.promise;
  1719. },
  1720. /**
  1721. * @returns {Promise} A promise this is resolved with current stats about
  1722. * document structures (see {@link PDFDocumentStats}).
  1723. */
  1724. getStats: function PDFDocumentProxy_getStats() {
  1725. return this.transport.getStats();
  1726. },
  1727. /**
  1728. * Cleans up resources allocated by the document, e.g. created @font-face.
  1729. */
  1730. cleanup: function PDFDocumentProxy_cleanup() {
  1731. this.transport.startCleanup();
  1732. },
  1733. /**
  1734. * Destroys current document instance and terminates worker.
  1735. */
  1736. destroy: function PDFDocumentProxy_destroy() {
  1737. this.transport.destroy();
  1738. }
  1739. };
  1740. return PDFDocumentProxy;
  1741. })();
  1742. /**
  1743. * Page text content.
  1744. *
  1745. * @typedef {Object} TextContent
  1746. * @property {array} items - array of {@link TextItem}
  1747. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1748. * name.
  1749. */
  1750. /**
  1751. * Page text content part.
  1752. *
  1753. * @typedef {Object} TextItem
  1754. * @property {string} str - text content.
  1755. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1756. * @property {array} transform - transformation matrix.
  1757. * @property {number} width - width in device space.
  1758. * @property {number} height - height in device space.
  1759. * @property {string} fontName - font name used by pdf.js for converted font.
  1760. */
  1761. /**
  1762. * Text style.
  1763. *
  1764. * @typedef {Object} TextStyle
  1765. * @property {number} ascent - font ascent.
  1766. * @property {number} descent - font descent.
  1767. * @property {boolean} vertical - text is in vertical mode.
  1768. * @property {string} fontFamily - possible font family
  1769. */
  1770. /**
  1771. * Page render parameters.
  1772. *
  1773. * @typedef {Object} RenderParameters
  1774. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1775. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1776. * calling of PDFPage.getViewport method.
  1777. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1778. * (default value is 'display').
  1779. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1780. * endLayout and appendImage functions.
  1781. * @property {function} continueCallback - (optional) A function that will be
  1782. * called each time the rendering is paused. To continue
  1783. * rendering call the function that is the first argument
  1784. * to the callback.
  1785. */
  1786. /**
  1787. * PDF page operator list.
  1788. *
  1789. * @typedef {Object} PDFOperatorList
  1790. * @property {Array} fnArray - Array containing the operator functions.
  1791. * @property {Array} argsArray - Array containing the arguments of the
  1792. * functions.
  1793. */
  1794. /**
  1795. * Proxy to a PDFPage in the worker thread.
  1796. * @class
  1797. */
  1798. var PDFPageProxy = (function PDFPageProxyClosure() {
  1799. function PDFPageProxy(pageIndex, pageInfo, transport) {
  1800. this.pageIndex = pageIndex;
  1801. this.pageInfo = pageInfo;
  1802. this.transport = transport;
  1803. this.stats = new StatTimer();
  1804. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  1805. this.commonObjs = transport.commonObjs;
  1806. this.objs = new PDFObjects();
  1807. this.cleanupAfterRender = false;
  1808. this.pendingDestroy = false;
  1809. this.intentStates = {};
  1810. }
  1811. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  1812. /**
  1813. * @return {number} Page number of the page. First page is 1.
  1814. */
  1815. get pageNumber() {
  1816. return this.pageIndex + 1;
  1817. },
  1818. /**
  1819. * @return {number} The number of degrees the page is rotated clockwise.
  1820. */
  1821. get rotate() {
  1822. return this.pageInfo.rotate;
  1823. },
  1824. /**
  1825. * @return {Object} The reference that points to this page. It has 'num' and
  1826. * 'gen' properties.
  1827. */
  1828. get ref() {
  1829. return this.pageInfo.ref;
  1830. },
  1831. /**
  1832. * @return {Array} An array of the visible portion of the PDF page in the
  1833. * user space units - [x1, y1, x2, y2].
  1834. */
  1835. get view() {
  1836. return this.pageInfo.view;
  1837. },
  1838. /**
  1839. * @param {number} scale The desired scale of the viewport.
  1840. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  1841. * defaults to the page rotation.
  1842. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  1843. * along with transforms required for rendering.
  1844. */
  1845. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  1846. if (arguments.length < 2) {
  1847. rotate = this.rotate;
  1848. }
  1849. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  1850. },
  1851. /**
  1852. * @return {Promise} A promise that is resolved with an {Array} of the
  1853. * annotation objects.
  1854. */
  1855. getAnnotations: function PDFPageProxy_getAnnotations() {
  1856. if (this.annotationsPromise) {
  1857. return this.annotationsPromise;
  1858. }
  1859. var promise = this.transport.getAnnotations(this.pageIndex);
  1860. this.annotationsPromise = promise;
  1861. return promise;
  1862. },
  1863. /**
  1864. * Begins the process of rendering a page to the desired context.
  1865. * @param {RenderParameters} params Page render parameters.
  1866. * @return {RenderTask} An object that contains the promise, which
  1867. * is resolved when the page finishes rendering.
  1868. */
  1869. render: function PDFPageProxy_render(params) {
  1870. var stats = this.stats;
  1871. stats.time('Overall');
  1872. // If there was a pending destroy cancel it so no cleanup happens during
  1873. // this call to render.
  1874. this.pendingDestroy = false;
  1875. var renderingIntent = ('intent' in params ?
  1876. (params.intent == 'print' ? 'print' : 'display') : 'display');
  1877. if (!this.intentStates[renderingIntent]) {
  1878. this.intentStates[renderingIntent] = {};
  1879. }
  1880. var intentState = this.intentStates[renderingIntent];
  1881. // If there's no displayReadyCapability yet, then the operatorList
  1882. // was never requested before. Make the request and create the promise.
  1883. if (!intentState.displayReadyCapability) {
  1884. intentState.receivingOperatorList = true;
  1885. intentState.displayReadyCapability = createPromiseCapability();
  1886. intentState.operatorList = {
  1887. fnArray: [],
  1888. argsArray: [],
  1889. lastChunk: false
  1890. };
  1891. this.stats.time('Page Request');
  1892. this.transport.messageHandler.send('RenderPageRequest', {
  1893. pageIndex: this.pageNumber - 1,
  1894. intent: renderingIntent
  1895. });
  1896. }
  1897. var internalRenderTask = new InternalRenderTask(complete, params,
  1898. this.objs,
  1899. this.commonObjs,
  1900. intentState.operatorList,
  1901. this.pageNumber);
  1902. if (!intentState.renderTasks) {
  1903. intentState.renderTasks = [];
  1904. }
  1905. intentState.renderTasks.push(internalRenderTask);
  1906. var renderTask = new RenderTask(internalRenderTask);
  1907. var self = this;
  1908. intentState.displayReadyCapability.promise.then(
  1909. function pageDisplayReadyPromise(transparency) {
  1910. if (self.pendingDestroy) {
  1911. complete();
  1912. return;
  1913. }
  1914. stats.time('Rendering');
  1915. internalRenderTask.initalizeGraphics(transparency);
  1916. internalRenderTask.operatorListChanged();
  1917. },
  1918. function pageDisplayReadPromiseError(reason) {
  1919. complete(reason);
  1920. }
  1921. );
  1922. function complete(error) {
  1923. var i = intentState.renderTasks.indexOf(internalRenderTask);
  1924. if (i >= 0) {
  1925. intentState.renderTasks.splice(i, 1);
  1926. }
  1927. if (self.cleanupAfterRender) {
  1928. self.pendingDestroy = true;
  1929. }
  1930. self._tryDestroy();
  1931. if (error) {
  1932. internalRenderTask.capability.reject(error);
  1933. } else {
  1934. internalRenderTask.capability.resolve();
  1935. }
  1936. stats.timeEnd('Rendering');
  1937. stats.timeEnd('Overall');
  1938. }
  1939. return renderTask;
  1940. },
  1941. /**
  1942. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  1943. * object that represents page's operator list.
  1944. */
  1945. getOperatorList: function PDFPageProxy_getOperatorList() {
  1946. function operatorListChanged() {
  1947. if (intentState.operatorList.lastChunk) {
  1948. intentState.opListReadCapability.resolve(intentState.operatorList);
  1949. }
  1950. }
  1951. var renderingIntent = 'oplist';
  1952. if (!this.intentStates[renderingIntent]) {
  1953. this.intentStates[renderingIntent] = {};
  1954. }
  1955. var intentState = this.intentStates[renderingIntent];
  1956. if (!intentState.opListReadCapability) {
  1957. var opListTask = {};
  1958. opListTask.operatorListChanged = operatorListChanged;
  1959. intentState.receivingOperatorList = true;
  1960. intentState.opListReadCapability = createPromiseCapability();
  1961. intentState.renderTasks = [];
  1962. intentState.renderTasks.push(opListTask);
  1963. intentState.operatorList = {
  1964. fnArray: [],
  1965. argsArray: [],
  1966. lastChunk: false
  1967. };
  1968. this.transport.messageHandler.send('RenderPageRequest', {
  1969. pageIndex: this.pageIndex,
  1970. intent: renderingIntent
  1971. });
  1972. }
  1973. return intentState.opListReadCapability.promise;
  1974. },
  1975. /**
  1976. * @return {Promise} That is resolved a {@link TextContent}
  1977. * object that represent the page text content.
  1978. */
  1979. getTextContent: function PDFPageProxy_getTextContent() {
  1980. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  1981. pageIndex: this.pageNumber - 1
  1982. });
  1983. },
  1984. /**
  1985. * Destroys resources allocated by the page.
  1986. */
  1987. destroy: function PDFPageProxy_destroy() {
  1988. this.pendingDestroy = true;
  1989. this._tryDestroy();
  1990. },
  1991. /**
  1992. * For internal use only. Attempts to clean up if rendering is in a state
  1993. * where that's possible.
  1994. * @ignore
  1995. */
  1996. _tryDestroy: function PDFPageProxy__destroy() {
  1997. if (!this.pendingDestroy ||
  1998. Object.keys(this.intentStates).some(function(intent) {
  1999. var intentState = this.intentStates[intent];
  2000. return (intentState.renderTasks.length !== 0 ||
  2001. intentState.receivingOperatorList);
  2002. }, this)) {
  2003. return;
  2004. }
  2005. Object.keys(this.intentStates).forEach(function(intent) {
  2006. delete this.intentStates[intent];
  2007. }, this);
  2008. this.objs.clear();
  2009. this.annotationsPromise = null;
  2010. this.pendingDestroy = false;
  2011. },
  2012. /**
  2013. * For internal use only.
  2014. * @ignore
  2015. */
  2016. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2017. intent) {
  2018. var intentState = this.intentStates[intent];
  2019. // TODO Refactor RenderPageRequest to separate rendering
  2020. // and operator list logic
  2021. if (intentState.displayReadyCapability) {
  2022. intentState.displayReadyCapability.resolve(transparency);
  2023. }
  2024. },
  2025. /**
  2026. * For internal use only.
  2027. * @ignore
  2028. */
  2029. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2030. intent) {
  2031. var intentState = this.intentStates[intent];
  2032. var i, ii;
  2033. // Add the new chunk to the current operator list.
  2034. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2035. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2036. intentState.operatorList.argsArray.push(
  2037. operatorListChunk.argsArray[i]);
  2038. }
  2039. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2040. // Notify all the rendering tasks there are more operators to be consumed.
  2041. for (i = 0; i < intentState.renderTasks.length; i++) {
  2042. intentState.renderTasks[i].operatorListChanged();
  2043. }
  2044. if (operatorListChunk.lastChunk) {
  2045. intentState.receivingOperatorList = false;
  2046. this._tryDestroy();
  2047. }
  2048. }
  2049. };
  2050. return PDFPageProxy;
  2051. })();
  2052. /**
  2053. * For internal use only.
  2054. * @ignore
  2055. */
  2056. var WorkerTransport = (function WorkerTransportClosure() {
  2057. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  2058. pdfDataRangeTransport, progressCallback) {
  2059. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2060. this.workerInitializedCapability = workerInitializedCapability;
  2061. this.workerReadyCapability = workerReadyCapability;
  2062. this.progressCallback = progressCallback;
  2063. this.commonObjs = new PDFObjects();
  2064. this.pageCache = [];
  2065. this.pagePromises = [];
  2066. this.downloadInfoCapability = createPromiseCapability();
  2067. this.passwordCallback = null;
  2068. // If worker support isn't disabled explicit and the browser has worker
  2069. // support, create a new web worker and test if it/the browser fullfills
  2070. // all requirements to run parts of pdf.js in a web worker.
  2071. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2072. // as it arrives on the worker. Chrome added this with version 15.
  2073. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  2074. var workerSrc = PDFJS.workerSrc;
  2075. if (!workerSrc) {
  2076. error('No PDFJS.workerSrc specified');
  2077. }
  2078. try {
  2079. // Some versions of FF can't create a worker on localhost, see:
  2080. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  2081. var worker = new Worker(workerSrc);
  2082. var messageHandler = new MessageHandler('main', worker);
  2083. this.messageHandler = messageHandler;
  2084. messageHandler.on('test', function transportTest(data) {
  2085. var supportTypedArray = data && data.supportTypedArray;
  2086. if (supportTypedArray) {
  2087. this.worker = worker;
  2088. if (!data.supportTransfers) {
  2089. PDFJS.postMessageTransfers = false;
  2090. }
  2091. this.setupMessageHandler(messageHandler);
  2092. workerInitializedCapability.resolve();
  2093. } else {
  2094. this.setupFakeWorker();
  2095. }
  2096. }.bind(this));
  2097. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  2098. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  2099. // typed array. Also, checking if we can use transfers.
  2100. try {
  2101. messageHandler.send('test', testObj, [testObj.buffer]);
  2102. } catch (ex) {
  2103. info('Cannot use postMessage transfers');
  2104. testObj[0] = 0;
  2105. messageHandler.send('test', testObj);
  2106. }
  2107. return;
  2108. } catch (e) {
  2109. info('The worker has been disabled.');
  2110. }
  2111. }
  2112. // Either workers are disabled, not supported or have thrown an exception.
  2113. // Thus, we fallback to a faked worker.
  2114. this.setupFakeWorker();
  2115. }
  2116. WorkerTransport.prototype = {
  2117. destroy: function WorkerTransport_destroy() {
  2118. this.pageCache = [];
  2119. this.pagePromises = [];
  2120. var self = this;
  2121. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2122. FontLoader.clear();
  2123. if (self.worker) {
  2124. self.worker.terminate();
  2125. }
  2126. });
  2127. },
  2128. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2129. globalScope.PDFJS.disableWorker = true;
  2130. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2131. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2132. // In the developer build load worker_loader which in turn loads all the
  2133. // other files and resolves the promise. In production only the
  2134. // pdf.worker.js file is needed.
  2135. Util.loadScript(PDFJS.workerSrc, function() {
  2136. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2137. });
  2138. }
  2139. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2140. warn('Setting up fake worker.');
  2141. // If we don't use a worker, just post/sendMessage to the main thread.
  2142. var fakeWorker = {
  2143. postMessage: function WorkerTransport_postMessage(obj) {
  2144. fakeWorker.onmessage({data: obj});
  2145. },
  2146. terminate: function WorkerTransport_terminate() {}
  2147. };
  2148. var messageHandler = new MessageHandler('main', fakeWorker);
  2149. this.setupMessageHandler(messageHandler);
  2150. // If the main thread is our worker, setup the handling for the messages
  2151. // the main thread sends to it self.
  2152. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2153. this.workerInitializedCapability.resolve();
  2154. }.bind(this));
  2155. },
  2156. setupMessageHandler:
  2157. function WorkerTransport_setupMessageHandler(messageHandler) {
  2158. this.messageHandler = messageHandler;
  2159. function updatePassword(password) {
  2160. messageHandler.send('UpdatePassword', password);
  2161. }
  2162. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2163. if (pdfDataRangeTransport) {
  2164. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2165. messageHandler.send('OnDataRange', {
  2166. begin: begin,
  2167. chunk: chunk
  2168. });
  2169. });
  2170. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2171. messageHandler.send('OnDataProgress', {
  2172. loaded: loaded
  2173. });
  2174. });
  2175. messageHandler.on('RequestDataRange',
  2176. function transportDataRange(data) {
  2177. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2178. }, this);
  2179. }
  2180. messageHandler.on('GetDoc', function transportDoc(data) {
  2181. var pdfInfo = data.pdfInfo;
  2182. this.numPages = data.pdfInfo.numPages;
  2183. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2184. this.pdfDocument = pdfDocument;
  2185. this.workerReadyCapability.resolve(pdfDocument);
  2186. }, this);
  2187. messageHandler.on('NeedPassword', function transportPassword(data) {
  2188. if (this.passwordCallback) {
  2189. return this.passwordCallback(updatePassword,
  2190. PasswordResponses.NEED_PASSWORD);
  2191. }
  2192. this.workerReadyCapability.reject(data.exception.message,
  2193. data.exception);
  2194. }, this);
  2195. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  2196. if (this.passwordCallback) {
  2197. return this.passwordCallback(updatePassword,
  2198. PasswordResponses.INCORRECT_PASSWORD);
  2199. }
  2200. this.workerReadyCapability.reject(data.exception.message,
  2201. data.exception);
  2202. }, this);
  2203. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  2204. this.workerReadyCapability.reject(data.exception.name, data.exception);
  2205. }, this);
  2206. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  2207. this.workerReadyCapability.reject(data.exception.message,
  2208. data.exception);
  2209. }, this);
  2210. messageHandler.on('UnknownError', function transportUnknownError(data) {
  2211. this.workerReadyCapability.reject(data.exception.message,
  2212. data.exception);
  2213. }, this);
  2214. messageHandler.on('DataLoaded', function transportPage(data) {
  2215. this.downloadInfoCapability.resolve(data);
  2216. }, this);
  2217. messageHandler.on('StartRenderPage', function transportRender(data) {
  2218. var page = this.pageCache[data.pageIndex];
  2219. page.stats.timeEnd('Page Request');
  2220. page._startRenderPage(data.transparency, data.intent);
  2221. }, this);
  2222. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2223. var page = this.pageCache[data.pageIndex];
  2224. page._renderPageChunk(data.operatorList, data.intent);
  2225. }, this);
  2226. messageHandler.on('commonobj', function transportObj(data) {
  2227. var id = data[0];
  2228. var type = data[1];
  2229. if (this.commonObjs.hasData(id)) {
  2230. return;
  2231. }
  2232. switch (type) {
  2233. case 'Font':
  2234. var exportedData = data[2];
  2235. var font;
  2236. if ('error' in exportedData) {
  2237. var error = exportedData.error;
  2238. warn('Error during font loading: ' + error);
  2239. this.commonObjs.resolve(id, error);
  2240. break;
  2241. } else {
  2242. font = new FontFace(exportedData);
  2243. }
  2244. FontLoader.bind(
  2245. [font],
  2246. function fontReady(fontObjs) {
  2247. this.commonObjs.resolve(id, font);
  2248. }.bind(this)
  2249. );
  2250. break;
  2251. case 'FontPath':
  2252. this.commonObjs.resolve(id, data[2]);
  2253. break;
  2254. default:
  2255. error('Got unknown common object type ' + type);
  2256. }
  2257. }, this);
  2258. messageHandler.on('obj', function transportObj(data) {
  2259. var id = data[0];
  2260. var pageIndex = data[1];
  2261. var type = data[2];
  2262. var pageProxy = this.pageCache[pageIndex];
  2263. var imageData;
  2264. if (pageProxy.objs.hasData(id)) {
  2265. return;
  2266. }
  2267. switch (type) {
  2268. case 'JpegStream':
  2269. imageData = data[3];
  2270. loadJpegStream(id, imageData, pageProxy.objs);
  2271. break;
  2272. case 'Image':
  2273. imageData = data[3];
  2274. pageProxy.objs.resolve(id, imageData);
  2275. // heuristics that will allow not to store large data
  2276. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2277. if (imageData && 'data' in imageData &&
  2278. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2279. pageProxy.cleanupAfterRender = true;
  2280. }
  2281. break;
  2282. default:
  2283. error('Got unknown object type ' + type);
  2284. }
  2285. }, this);
  2286. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2287. if (this.progressCallback) {
  2288. this.progressCallback({
  2289. loaded: data.loaded,
  2290. total: data.total
  2291. });
  2292. }
  2293. }, this);
  2294. messageHandler.on('DocError', function transportDocError(data) {
  2295. this.workerReadyCapability.reject(data);
  2296. }, this);
  2297. messageHandler.on('PageError', function transportError(data) {
  2298. var page = this.pageCache[data.pageNum - 1];
  2299. var intentState = page.intentStates[data.intent];
  2300. if (intentState.displayReadyCapability.promise) {
  2301. intentState.displayReadyCapability.reject(data.error);
  2302. } else {
  2303. error(data.error);
  2304. }
  2305. }, this);
  2306. messageHandler.on('JpegDecode', function(data) {
  2307. var imageUrl = data[0];
  2308. var components = data[1];
  2309. if (components != 3 && components != 1) {
  2310. return Promise.reject(
  2311. new Error('Only 3 components or 1 component can be returned'));
  2312. }
  2313. return new Promise(function (resolve, reject) {
  2314. var img = new Image();
  2315. img.onload = function () {
  2316. var width = img.width;
  2317. var height = img.height;
  2318. var size = width * height;
  2319. var rgbaLength = size * 4;
  2320. var buf = new Uint8Array(size * components);
  2321. var tmpCanvas = createScratchCanvas(width, height);
  2322. var tmpCtx = tmpCanvas.getContext('2d');
  2323. tmpCtx.drawImage(img, 0, 0);
  2324. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2325. var i, j;
  2326. if (components == 3) {
  2327. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2328. buf[j] = data[i];
  2329. buf[j + 1] = data[i + 1];
  2330. buf[j + 2] = data[i + 2];
  2331. }
  2332. } else if (components == 1) {
  2333. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2334. buf[j] = data[i];
  2335. }
  2336. }
  2337. resolve({ data: buf, width: width, height: height});
  2338. };
  2339. img.onerror = function () {
  2340. reject(new Error('JpegDecode failed to load image'));
  2341. };
  2342. img.src = imageUrl;
  2343. });
  2344. });
  2345. },
  2346. fetchDocument: function WorkerTransport_fetchDocument(source) {
  2347. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2348. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2349. this.messageHandler.send('GetDocRequest', {
  2350. source: source,
  2351. disableRange: PDFJS.disableRange,
  2352. maxImageSize: PDFJS.maxImageSize,
  2353. cMapUrl: PDFJS.cMapUrl,
  2354. cMapPacked: PDFJS.cMapPacked,
  2355. disableFontFace: PDFJS.disableFontFace,
  2356. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2357. verbosity: PDFJS.verbosity
  2358. });
  2359. },
  2360. getData: function WorkerTransport_getData() {
  2361. return this.messageHandler.sendWithPromise('GetData', null);
  2362. },
  2363. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2364. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2365. (pageNumber|0) !== pageNumber) {
  2366. return Promise.reject(new Error('Invalid page request'));
  2367. }
  2368. var pageIndex = pageNumber - 1;
  2369. if (pageIndex in this.pagePromises) {
  2370. return this.pagePromises[pageIndex];
  2371. }
  2372. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2373. pageIndex: pageIndex
  2374. }).then(function (pageInfo) {
  2375. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2376. this.pageCache[pageIndex] = page;
  2377. return page;
  2378. }.bind(this));
  2379. this.pagePromises[pageIndex] = promise;
  2380. return promise;
  2381. },
  2382. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2383. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2384. },
  2385. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2386. return this.messageHandler.sendWithPromise('GetAnnotations',
  2387. { pageIndex: pageIndex });
  2388. },
  2389. getDestinations: function WorkerTransport_getDestinations() {
  2390. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2391. },
  2392. getAttachments: function WorkerTransport_getAttachments() {
  2393. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2394. },
  2395. getJavaScript: function WorkerTransport_getJavaScript() {
  2396. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2397. },
  2398. getOutline: function WorkerTransport_getOutline() {
  2399. return this.messageHandler.sendWithPromise('GetOutline', null);
  2400. },
  2401. getMetadata: function WorkerTransport_getMetadata() {
  2402. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2403. then(function transportMetadata(results) {
  2404. return {
  2405. info: results[0],
  2406. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2407. };
  2408. });
  2409. },
  2410. getStats: function WorkerTransport_getStats() {
  2411. return this.messageHandler.sendWithPromise('GetStats', null);
  2412. },
  2413. startCleanup: function WorkerTransport_startCleanup() {
  2414. this.messageHandler.sendWithPromise('Cleanup', null).
  2415. then(function endCleanup() {
  2416. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2417. var page = this.pageCache[i];
  2418. if (page) {
  2419. page.destroy();
  2420. }
  2421. }
  2422. this.commonObjs.clear();
  2423. FontLoader.clear();
  2424. }.bind(this));
  2425. }
  2426. };
  2427. return WorkerTransport;
  2428. })();
  2429. /**
  2430. * A PDF document and page is built of many objects. E.g. there are objects
  2431. * for fonts, images, rendering code and such. These objects might get processed
  2432. * inside of a worker. The `PDFObjects` implements some basic functions to
  2433. * manage these objects.
  2434. * @ignore
  2435. */
  2436. var PDFObjects = (function PDFObjectsClosure() {
  2437. function PDFObjects() {
  2438. this.objs = {};
  2439. }
  2440. PDFObjects.prototype = {
  2441. /**
  2442. * Internal function.
  2443. * Ensures there is an object defined for `objId`.
  2444. */
  2445. ensureObj: function PDFObjects_ensureObj(objId) {
  2446. if (this.objs[objId]) {
  2447. return this.objs[objId];
  2448. }
  2449. var obj = {
  2450. capability: createPromiseCapability(),
  2451. data: null,
  2452. resolved: false
  2453. };
  2454. this.objs[objId] = obj;
  2455. return obj;
  2456. },
  2457. /**
  2458. * If called *without* callback, this returns the data of `objId` but the
  2459. * object needs to be resolved. If it isn't, this function throws.
  2460. *
  2461. * If called *with* a callback, the callback is called with the data of the
  2462. * object once the object is resolved. That means, if you call this
  2463. * function and the object is already resolved, the callback gets called
  2464. * right away.
  2465. */
  2466. get: function PDFObjects_get(objId, callback) {
  2467. // If there is a callback, then the get can be async and the object is
  2468. // not required to be resolved right now
  2469. if (callback) {
  2470. this.ensureObj(objId).capability.promise.then(callback);
  2471. return null;
  2472. }
  2473. // If there isn't a callback, the user expects to get the resolved data
  2474. // directly.
  2475. var obj = this.objs[objId];
  2476. // If there isn't an object yet or the object isn't resolved, then the
  2477. // data isn't ready yet!
  2478. if (!obj || !obj.resolved) {
  2479. error('Requesting object that isn\'t resolved yet ' + objId);
  2480. }
  2481. return obj.data;
  2482. },
  2483. /**
  2484. * Resolves the object `objId` with optional `data`.
  2485. */
  2486. resolve: function PDFObjects_resolve(objId, data) {
  2487. var obj = this.ensureObj(objId);
  2488. obj.resolved = true;
  2489. obj.data = data;
  2490. obj.capability.resolve(data);
  2491. },
  2492. isResolved: function PDFObjects_isResolved(objId) {
  2493. var objs = this.objs;
  2494. if (!objs[objId]) {
  2495. return false;
  2496. } else {
  2497. return objs[objId].resolved;
  2498. }
  2499. },
  2500. hasData: function PDFObjects_hasData(objId) {
  2501. return this.isResolved(objId);
  2502. },
  2503. /**
  2504. * Returns the data of `objId` if object exists, null otherwise.
  2505. */
  2506. getData: function PDFObjects_getData(objId) {
  2507. var objs = this.objs;
  2508. if (!objs[objId] || !objs[objId].resolved) {
  2509. return null;
  2510. } else {
  2511. return objs[objId].data;
  2512. }
  2513. },
  2514. clear: function PDFObjects_clear() {
  2515. this.objs = {};
  2516. }
  2517. };
  2518. return PDFObjects;
  2519. })();
  2520. /**
  2521. * Allows controlling of the rendering tasks.
  2522. * @class
  2523. */
  2524. var RenderTask = (function RenderTaskClosure() {
  2525. function RenderTask(internalRenderTask) {
  2526. this.internalRenderTask = internalRenderTask;
  2527. /**
  2528. * Promise for rendering task completion.
  2529. * @type {Promise}
  2530. */
  2531. this.promise = this.internalRenderTask.capability.promise;
  2532. }
  2533. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2534. /**
  2535. * Cancels the rendering task. If the task is currently rendering it will
  2536. * not be cancelled until graphics pauses with a timeout. The promise that
  2537. * this object extends will resolved when cancelled.
  2538. */
  2539. cancel: function RenderTask_cancel() {
  2540. this.internalRenderTask.cancel();
  2541. },
  2542. /**
  2543. * Registers callback to indicate the rendering task completion.
  2544. *
  2545. * @param {function} onFulfilled The callback for the rendering completion.
  2546. * @param {function} onRejected The callback for the rendering failure.
  2547. * @return {Promise} A promise that is resolved after the onFulfilled or
  2548. * onRejected callback.
  2549. */
  2550. then: function RenderTask_then(onFulfilled, onRejected) {
  2551. return this.promise.then(onFulfilled, onRejected);
  2552. }
  2553. };
  2554. return RenderTask;
  2555. })();
  2556. /**
  2557. * For internal use only.
  2558. * @ignore
  2559. */
  2560. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2561. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2562. pageNumber) {
  2563. this.callback = callback;
  2564. this.params = params;
  2565. this.objs = objs;
  2566. this.commonObjs = commonObjs;
  2567. this.operatorListIdx = null;
  2568. this.operatorList = operatorList;
  2569. this.pageNumber = pageNumber;
  2570. this.running = false;
  2571. this.graphicsReadyCallback = null;
  2572. this.graphicsReady = false;
  2573. this.cancelled = false;
  2574. this.capability = createPromiseCapability();
  2575. // caching this-bound methods
  2576. this._continueBound = this._continue.bind(this);
  2577. this._scheduleNextBound = this._scheduleNext.bind(this);
  2578. this._nextBound = this._next.bind(this);
  2579. }
  2580. InternalRenderTask.prototype = {
  2581. initalizeGraphics:
  2582. function InternalRenderTask_initalizeGraphics(transparency) {
  2583. if (this.cancelled) {
  2584. return;
  2585. }
  2586. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2587. globalScope.StepperManager.enabled) {
  2588. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2589. this.stepper.init(this.operatorList);
  2590. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2591. }
  2592. var params = this.params;
  2593. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2594. this.objs, params.imageLayer);
  2595. this.gfx.beginDrawing(params.viewport, transparency);
  2596. this.operatorListIdx = 0;
  2597. this.graphicsReady = true;
  2598. if (this.graphicsReadyCallback) {
  2599. this.graphicsReadyCallback();
  2600. }
  2601. },
  2602. cancel: function InternalRenderTask_cancel() {
  2603. this.running = false;
  2604. this.cancelled = true;
  2605. this.callback('cancelled');
  2606. },
  2607. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2608. if (!this.graphicsReady) {
  2609. if (!this.graphicsReadyCallback) {
  2610. this.graphicsReadyCallback = this._continueBound;
  2611. }
  2612. return;
  2613. }
  2614. if (this.stepper) {
  2615. this.stepper.updateOperatorList(this.operatorList);
  2616. }
  2617. if (this.running) {
  2618. return;
  2619. }
  2620. this._continue();
  2621. },
  2622. _continue: function InternalRenderTask__continue() {
  2623. this.running = true;
  2624. if (this.cancelled) {
  2625. return;
  2626. }
  2627. if (this.params.continueCallback) {
  2628. this.params.continueCallback(this._scheduleNextBound);
  2629. } else {
  2630. this._scheduleNext();
  2631. }
  2632. },
  2633. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2634. window.requestAnimationFrame(this._nextBound);
  2635. },
  2636. _next: function InternalRenderTask__next() {
  2637. if (this.cancelled) {
  2638. return;
  2639. }
  2640. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2641. this.operatorListIdx,
  2642. this._continueBound,
  2643. this.stepper);
  2644. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2645. this.running = false;
  2646. if (this.operatorList.lastChunk) {
  2647. this.gfx.endDrawing();
  2648. this.callback();
  2649. }
  2650. }
  2651. }
  2652. };
  2653. return InternalRenderTask;
  2654. })();
  2655. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2656. function fixMetadata(meta) {
  2657. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2658. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2659. function(code, d1, d2, d3) {
  2660. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2661. });
  2662. var chars = '';
  2663. for (var i = 0; i < bytes.length; i += 2) {
  2664. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2665. chars += code >= 32 && code < 127 && code != 60 && code != 62 &&
  2666. code != 38 && false ? String.fromCharCode(code) :
  2667. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2668. }
  2669. return '>' + chars;
  2670. });
  2671. }
  2672. function Metadata(meta) {
  2673. if (typeof meta === 'string') {
  2674. // Ghostscript produces invalid metadata
  2675. meta = fixMetadata(meta);
  2676. var parser = new DOMParser();
  2677. meta = parser.parseFromString(meta, 'application/xml');
  2678. } else if (!(meta instanceof Document)) {
  2679. error('Metadata: Invalid metadata object');
  2680. }
  2681. this.metaDocument = meta;
  2682. this.metadata = {};
  2683. this.parse();
  2684. }
  2685. Metadata.prototype = {
  2686. parse: function Metadata_parse() {
  2687. var doc = this.metaDocument;
  2688. var rdf = doc.documentElement;
  2689. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2690. rdf = rdf.firstChild;
  2691. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2692. rdf = rdf.nextSibling;
  2693. }
  2694. }
  2695. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2696. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2697. return;
  2698. }
  2699. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2700. for (i = 0, length = children.length; i < length; i++) {
  2701. desc = children[i];
  2702. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2703. continue;
  2704. }
  2705. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2706. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2707. entry = desc.childNodes[ii];
  2708. name = entry.nodeName.toLowerCase();
  2709. this.metadata[name] = entry.textContent.trim();
  2710. }
  2711. }
  2712. }
  2713. },
  2714. get: function Metadata_get(name) {
  2715. return this.metadata[name] || null;
  2716. },
  2717. has: function Metadata_has(name) {
  2718. return typeof this.metadata[name] !== 'undefined';
  2719. }
  2720. };
  2721. return Metadata;
  2722. })();
  2723. // <canvas> contexts store most of the state we need natively.
  2724. // However, PDF needs a bit more state, which we store here.
  2725. // Minimal font size that would be used during canvas fillText operations.
  2726. var MIN_FONT_SIZE = 16;
  2727. var MAX_GROUP_SIZE = 4096;
  2728. var COMPILE_TYPE3_GLYPHS = true;
  2729. function createScratchCanvas(width, height) {
  2730. var canvas = document.createElement('canvas');
  2731. canvas.width = width;
  2732. canvas.height = height;
  2733. return canvas;
  2734. }
  2735. function addContextCurrentTransform(ctx) {
  2736. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  2737. if (!ctx.mozCurrentTransform) {
  2738. // Store the original context
  2739. ctx._scaleX = ctx._scaleX || 1.0;
  2740. ctx._scaleY = ctx._scaleY || 1.0;
  2741. ctx._originalSave = ctx.save;
  2742. ctx._originalRestore = ctx.restore;
  2743. ctx._originalRotate = ctx.rotate;
  2744. ctx._originalScale = ctx.scale;
  2745. ctx._originalTranslate = ctx.translate;
  2746. ctx._originalTransform = ctx.transform;
  2747. ctx._originalSetTransform = ctx.setTransform;
  2748. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  2749. ctx._transformStack = [];
  2750. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2751. get: function getCurrentTransform() {
  2752. return this._transformMatrix;
  2753. }
  2754. });
  2755. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  2756. get: function getCurrentTransformInverse() {
  2757. // Calculation done using WolframAlpha:
  2758. // http://www.wolframalpha.com/input/?
  2759. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  2760. var m = this._transformMatrix;
  2761. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  2762. var ad_bc = a * d - b * c;
  2763. var bc_ad = b * c - a * d;
  2764. return [
  2765. d / ad_bc,
  2766. b / bc_ad,
  2767. c / bc_ad,
  2768. a / ad_bc,
  2769. (d * e - c * f) / bc_ad,
  2770. (b * e - a * f) / ad_bc
  2771. ];
  2772. }
  2773. });
  2774. ctx.save = function ctxSave() {
  2775. var old = this._transformMatrix;
  2776. this._transformStack.push(old);
  2777. this._transformMatrix = old.slice(0, 6);
  2778. this._originalSave();
  2779. };
  2780. ctx.restore = function ctxRestore() {
  2781. var prev = this._transformStack.pop();
  2782. if (prev) {
  2783. this._transformMatrix = prev;
  2784. this._originalRestore();
  2785. }
  2786. };
  2787. ctx.translate = function ctxTranslate(x, y) {
  2788. var m = this._transformMatrix;
  2789. m[4] = m[0] * x + m[2] * y + m[4];
  2790. m[5] = m[1] * x + m[3] * y + m[5];
  2791. this._originalTranslate(x, y);
  2792. };
  2793. ctx.scale = function ctxScale(x, y) {
  2794. var m = this._transformMatrix;
  2795. m[0] = m[0] * x;
  2796. m[1] = m[1] * x;
  2797. m[2] = m[2] * y;
  2798. m[3] = m[3] * y;
  2799. this._originalScale(x, y);
  2800. };
  2801. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  2802. var m = this._transformMatrix;
  2803. this._transformMatrix = [
  2804. m[0] * a + m[2] * b,
  2805. m[1] * a + m[3] * b,
  2806. m[0] * c + m[2] * d,
  2807. m[1] * c + m[3] * d,
  2808. m[0] * e + m[2] * f + m[4],
  2809. m[1] * e + m[3] * f + m[5]
  2810. ];
  2811. ctx._originalTransform(a, b, c, d, e, f);
  2812. };
  2813. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  2814. this._transformMatrix = [a, b, c, d, e, f];
  2815. ctx._originalSetTransform(a, b, c, d, e, f);
  2816. };
  2817. ctx.rotate = function ctxRotate(angle) {
  2818. var cosValue = Math.cos(angle);
  2819. var sinValue = Math.sin(angle);
  2820. var m = this._transformMatrix;
  2821. this._transformMatrix = [
  2822. m[0] * cosValue + m[2] * sinValue,
  2823. m[1] * cosValue + m[3] * sinValue,
  2824. m[0] * (-sinValue) + m[2] * cosValue,
  2825. m[1] * (-sinValue) + m[3] * cosValue,
  2826. m[4],
  2827. m[5]
  2828. ];
  2829. this._originalRotate(angle);
  2830. };
  2831. }
  2832. }
  2833. var CachedCanvases = (function CachedCanvasesClosure() {
  2834. var cache = {};
  2835. return {
  2836. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  2837. trackTransform) {
  2838. var canvasEntry;
  2839. if (id in cache) {
  2840. canvasEntry = cache[id];
  2841. canvasEntry.canvas.width = width;
  2842. canvasEntry.canvas.height = height;
  2843. // reset canvas transform for emulated mozCurrentTransform, if needed
  2844. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  2845. } else {
  2846. var canvas = createScratchCanvas(width, height);
  2847. var ctx = canvas.getContext('2d');
  2848. if (trackTransform) {
  2849. addContextCurrentTransform(ctx);
  2850. }
  2851. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  2852. }
  2853. return canvasEntry;
  2854. },
  2855. clear: function () {
  2856. for (var id in cache) {
  2857. var canvasEntry = cache[id];
  2858. // Zeroing the width and height causes Firefox to release graphics
  2859. // resources immediately, which can greatly reduce memory consumption.
  2860. canvasEntry.canvas.width = 0;
  2861. canvasEntry.canvas.height = 0;
  2862. delete cache[id];
  2863. }
  2864. }
  2865. };
  2866. })();
  2867. function compileType3Glyph(imgData) {
  2868. var POINT_TO_PROCESS_LIMIT = 1000;
  2869. var width = imgData.width, height = imgData.height;
  2870. var i, j, j0, width1 = width + 1;
  2871. var points = new Uint8Array(width1 * (height + 1));
  2872. var POINT_TYPES =
  2873. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  2874. // decodes bit-packed mask data
  2875. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  2876. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  2877. for (i = 0, ii = data0.length; i < ii; i++) {
  2878. var mask = 128, elem = data0[i];
  2879. while (mask > 0) {
  2880. data[pos++] = (elem & mask) ? 0 : 255;
  2881. mask >>= 1;
  2882. }
  2883. }
  2884. // finding iteresting points: every point is located between mask pixels,
  2885. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  2886. // will have flags assigned based on neighboring mask pixels:
  2887. // 4 | 8
  2888. // --P--
  2889. // 2 | 1
  2890. // We are interested only in points with the flags:
  2891. // - outside corners: 1, 2, 4, 8;
  2892. // - inside corners: 7, 11, 13, 14;
  2893. // - and, intersections: 5, 10.
  2894. var count = 0;
  2895. pos = 0;
  2896. if (data[pos] !== 0) {
  2897. points[0] = 1;
  2898. ++count;
  2899. }
  2900. for (j = 1; j < width; j++) {
  2901. if (data[pos] !== data[pos + 1]) {
  2902. points[j] = data[pos] ? 2 : 1;
  2903. ++count;
  2904. }
  2905. pos++;
  2906. }
  2907. if (data[pos] !== 0) {
  2908. points[j] = 2;
  2909. ++count;
  2910. }
  2911. for (i = 1; i < height; i++) {
  2912. pos = i * lineSize;
  2913. j0 = i * width1;
  2914. if (data[pos - lineSize] !== data[pos]) {
  2915. points[j0] = data[pos] ? 1 : 8;
  2916. ++count;
  2917. }
  2918. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  2919. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  2920. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  2921. for (j = 1; j < width; j++) {
  2922. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  2923. (data[pos - lineSize + 1] ? 8 : 0);
  2924. if (POINT_TYPES[sum]) {
  2925. points[j0 + j] = POINT_TYPES[sum];
  2926. ++count;
  2927. }
  2928. pos++;
  2929. }
  2930. if (data[pos - lineSize] !== data[pos]) {
  2931. points[j0 + j] = data[pos] ? 2 : 4;
  2932. ++count;
  2933. }
  2934. if (count > POINT_TO_PROCESS_LIMIT) {
  2935. return null;
  2936. }
  2937. }
  2938. pos = lineSize * (height - 1);
  2939. j0 = i * width1;
  2940. if (data[pos] !== 0) {
  2941. points[j0] = 8;
  2942. ++count;
  2943. }
  2944. for (j = 1; j < width; j++) {
  2945. if (data[pos] !== data[pos + 1]) {
  2946. points[j0 + j] = data[pos] ? 4 : 8;
  2947. ++count;
  2948. }
  2949. pos++;
  2950. }
  2951. if (data[pos] !== 0) {
  2952. points[j0 + j] = 4;
  2953. ++count;
  2954. }
  2955. if (count > POINT_TO_PROCESS_LIMIT) {
  2956. return null;
  2957. }
  2958. // building outlines
  2959. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  2960. var outlines = [];
  2961. for (i = 0; count && i <= height; i++) {
  2962. var p = i * width1;
  2963. var end = p + width;
  2964. while (p < end && !points[p]) {
  2965. p++;
  2966. }
  2967. if (p === end) {
  2968. continue;
  2969. }
  2970. var coords = [p % width1, i];
  2971. var type = points[p], p0 = p, pp;
  2972. do {
  2973. var step = steps[type];
  2974. do {
  2975. p += step;
  2976. } while (!points[p]);
  2977. pp = points[p];
  2978. if (pp !== 5 && pp !== 10) {
  2979. // set new direction
  2980. type = pp;
  2981. // delete mark
  2982. points[p] = 0;
  2983. } else { // type is 5 or 10, ie, a crossing
  2984. // set new direction
  2985. type = pp & ((0x33 * type) >> 4);
  2986. // set new type for "future hit"
  2987. points[p] &= (type >> 2 | type << 2);
  2988. }
  2989. coords.push(p % width1);
  2990. coords.push((p / width1) | 0);
  2991. --count;
  2992. } while (p0 !== p);
  2993. outlines.push(coords);
  2994. --i;
  2995. }
  2996. var drawOutline = function(c) {
  2997. c.save();
  2998. // the path shall be painted in [0..1]x[0..1] space
  2999. c.scale(1 / width, -1 / height);
  3000. c.translate(0, -height);
  3001. c.beginPath();
  3002. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3003. var o = outlines[i];
  3004. c.moveTo(o[0], o[1]);
  3005. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3006. c.lineTo(o[j], o[j+1]);
  3007. }
  3008. }
  3009. c.fill();
  3010. c.beginPath();
  3011. c.restore();
  3012. };
  3013. return drawOutline;
  3014. }
  3015. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3016. function CanvasExtraState(old) {
  3017. // Are soft masks and alpha values shapes or opacities?
  3018. this.alphaIsShape = false;
  3019. this.fontSize = 0;
  3020. this.fontSizeScale = 1;
  3021. this.textMatrix = IDENTITY_MATRIX;
  3022. this.textMatrixScale = 1;
  3023. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3024. this.leading = 0;
  3025. // Current point (in user coordinates)
  3026. this.x = 0;
  3027. this.y = 0;
  3028. // Start of text line (in text coordinates)
  3029. this.lineX = 0;
  3030. this.lineY = 0;
  3031. // Character and word spacing
  3032. this.charSpacing = 0;
  3033. this.wordSpacing = 0;
  3034. this.textHScale = 1;
  3035. this.textRenderingMode = TextRenderingMode.FILL;
  3036. this.textRise = 0;
  3037. // Default fore and background colors
  3038. this.fillColor = '#000000';
  3039. this.strokeColor = '#000000';
  3040. // Note: fill alpha applies to all non-stroking operations
  3041. this.fillAlpha = 1;
  3042. this.strokeAlpha = 1;
  3043. this.lineWidth = 1;
  3044. this.activeSMask = null; // nonclonable field (see the save method below)
  3045. this.old = old;
  3046. }
  3047. CanvasExtraState.prototype = {
  3048. clone: function CanvasExtraState_clone() {
  3049. return Object.create(this);
  3050. },
  3051. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3052. this.x = x;
  3053. this.y = y;
  3054. }
  3055. };
  3056. return CanvasExtraState;
  3057. })();
  3058. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3059. // Defines the time the executeOperatorList is going to be executing
  3060. // before it stops and shedules a continue of execution.
  3061. var EXECUTION_TIME = 15;
  3062. // Defines the number of steps before checking the execution time
  3063. var EXECUTION_STEPS = 10;
  3064. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3065. this.ctx = canvasCtx;
  3066. this.current = new CanvasExtraState();
  3067. this.stateStack = [];
  3068. this.pendingClip = null;
  3069. this.pendingEOFill = false;
  3070. this.res = null;
  3071. this.xobjs = null;
  3072. this.commonObjs = commonObjs;
  3073. this.objs = objs;
  3074. this.imageLayer = imageLayer;
  3075. this.groupStack = [];
  3076. this.processingType3 = null;
  3077. // Patterns are painted relative to the initial page/form transform, see pdf
  3078. // spec 8.7.2 NOTE 1.
  3079. this.baseTransform = null;
  3080. this.baseTransformStack = [];
  3081. this.groupLevel = 0;
  3082. this.smaskStack = [];
  3083. this.smaskCounter = 0;
  3084. this.tempSMask = null;
  3085. if (canvasCtx) {
  3086. addContextCurrentTransform(canvasCtx);
  3087. }
  3088. }
  3089. function putBinaryImageData(ctx, imgData) {
  3090. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3091. ctx.putImageData(imgData, 0, 0);
  3092. return;
  3093. }
  3094. // Put the image data to the canvas in chunks, rather than putting the
  3095. // whole image at once. This saves JS memory, because the ImageData object
  3096. // is smaller. It also possibly saves C++ memory within the implementation
  3097. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3098. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3099. // because too many putImageData() calls will slow things down.
  3100. //
  3101. // Note: as written, if the last chunk is partial, the putImageData() call
  3102. // will (conceptually) put pixels past the bounds of the canvas. But
  3103. // that's ok; any such pixels are ignored.
  3104. var height = imgData.height, width = imgData.width;
  3105. var fullChunkHeight = 16;
  3106. var fracChunks = height / fullChunkHeight;
  3107. var fullChunks = Math.floor(fracChunks);
  3108. var totalChunks = Math.ceil(fracChunks);
  3109. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3110. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3111. var srcPos = 0, destPos;
  3112. var src = imgData.data;
  3113. var dest = chunkImgData.data;
  3114. var i, j, thisChunkHeight, elemsInThisChunk;
  3115. // There are multiple forms in which the pixel data can be passed, and
  3116. // imgData.kind tells us which one this is.
  3117. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3118. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3119. var srcLength = src.byteLength;
  3120. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3121. new Uint32ArrayView(dest);
  3122. var dest32DataLength = dest32.length;
  3123. var fullSrcDiff = (width + 7) >> 3;
  3124. var white = 0xFFFFFFFF;
  3125. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3126. 0xFF000000 : 0x000000FF;
  3127. for (i = 0; i < totalChunks; i++) {
  3128. thisChunkHeight =
  3129. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3130. destPos = 0;
  3131. for (j = 0; j < thisChunkHeight; j++) {
  3132. var srcDiff = srcLength - srcPos;
  3133. var k = 0;
  3134. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3135. var kEndUnrolled = kEnd & ~7;
  3136. var mask = 0;
  3137. var srcByte = 0;
  3138. for (; k < kEndUnrolled; k += 8) {
  3139. srcByte = src[srcPos++];
  3140. dest32[destPos++] = (srcByte & 128) ? white : black;
  3141. dest32[destPos++] = (srcByte & 64) ? white : black;
  3142. dest32[destPos++] = (srcByte & 32) ? white : black;
  3143. dest32[destPos++] = (srcByte & 16) ? white : black;
  3144. dest32[destPos++] = (srcByte & 8) ? white : black;
  3145. dest32[destPos++] = (srcByte & 4) ? white : black;
  3146. dest32[destPos++] = (srcByte & 2) ? white : black;
  3147. dest32[destPos++] = (srcByte & 1) ? white : black;
  3148. }
  3149. for (; k < kEnd; k++) {
  3150. if (mask === 0) {
  3151. srcByte = src[srcPos++];
  3152. mask = 128;
  3153. }
  3154. dest32[destPos++] = (srcByte & mask) ? white : black;
  3155. mask >>= 1;
  3156. }
  3157. }
  3158. // We ran out of input. Make all remaining pixels transparent.
  3159. while (destPos < dest32DataLength) {
  3160. dest32[destPos++] = 0;
  3161. }
  3162. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3163. }
  3164. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3165. // RGBA, 32-bits per pixel.
  3166. j = 0;
  3167. elemsInThisChunk = width * fullChunkHeight * 4;
  3168. for (i = 0; i < fullChunks; i++) {
  3169. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3170. srcPos += elemsInThisChunk;
  3171. ctx.putImageData(chunkImgData, 0, j);
  3172. j += fullChunkHeight;
  3173. }
  3174. if (i < totalChunks) {
  3175. elemsInThisChunk = width * partialChunkHeight * 4;
  3176. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3177. ctx.putImageData(chunkImgData, 0, j);
  3178. }
  3179. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3180. // RGB, 24-bits per pixel.
  3181. thisChunkHeight = fullChunkHeight;
  3182. elemsInThisChunk = width * thisChunkHeight;
  3183. for (i = 0; i < totalChunks; i++) {
  3184. if (i >= fullChunks) {
  3185. thisChunkHeight =partialChunkHeight;
  3186. elemsInThisChunk = width * thisChunkHeight;
  3187. }
  3188. destPos = 0;
  3189. for (j = elemsInThisChunk; j--;) {
  3190. dest[destPos++] = src[srcPos++];
  3191. dest[destPos++] = src[srcPos++];
  3192. dest[destPos++] = src[srcPos++];
  3193. dest[destPos++] = 255;
  3194. }
  3195. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3196. }
  3197. } else {
  3198. error('bad image kind: ' + imgData.kind);
  3199. }
  3200. }
  3201. function putBinaryImageMask(ctx, imgData) {
  3202. var height = imgData.height, width = imgData.width;
  3203. var fullChunkHeight = 16;
  3204. var fracChunks = height / fullChunkHeight;
  3205. var fullChunks = Math.floor(fracChunks);
  3206. var totalChunks = Math.ceil(fracChunks);
  3207. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3208. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3209. var srcPos = 0;
  3210. var src = imgData.data;
  3211. var dest = chunkImgData.data;
  3212. for (var i = 0; i < totalChunks; i++) {
  3213. var thisChunkHeight =
  3214. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3215. // Expand the mask so it can be used by the canvas. Any required
  3216. // inversion has already been handled.
  3217. var destPos = 3; // alpha component offset
  3218. for (var j = 0; j < thisChunkHeight; j++) {
  3219. var mask = 0;
  3220. for (var k = 0; k < width; k++) {
  3221. if (!mask) {
  3222. var elem = src[srcPos++];
  3223. mask = 128;
  3224. }
  3225. dest[destPos] = (elem & mask) ? 0 : 255;
  3226. destPos += 4;
  3227. mask >>= 1;
  3228. }
  3229. }
  3230. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3231. }
  3232. }
  3233. function copyCtxState(sourceCtx, destCtx) {
  3234. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3235. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3236. 'globalCompositeOperation', 'font'];
  3237. for (var i = 0, ii = properties.length; i < ii; i++) {
  3238. var property = properties[i];
  3239. if (property in sourceCtx) {
  3240. destCtx[property] = sourceCtx[property];
  3241. }
  3242. }
  3243. if ('setLineDash' in sourceCtx) {
  3244. destCtx.setLineDash(sourceCtx.getLineDash());
  3245. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3246. } else if ('mozDash' in sourceCtx) {
  3247. destCtx.mozDash = sourceCtx.mozDash;
  3248. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3249. }
  3250. }
  3251. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3252. var length = bytes.length;
  3253. for (var i = 3; i < length; i += 4) {
  3254. var alpha = bytes[i];
  3255. if (alpha === 0) {
  3256. bytes[i - 3] = r0;
  3257. bytes[i - 2] = g0;
  3258. bytes[i - 1] = b0;
  3259. } else if (alpha < 255) {
  3260. var alpha_ = 255 - alpha;
  3261. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3262. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3263. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3264. }
  3265. }
  3266. }
  3267. function composeSMaskAlpha(maskData, layerData) {
  3268. var length = maskData.length;
  3269. var scale = 1 / 255;
  3270. for (var i = 3; i < length; i += 4) {
  3271. var alpha = maskData[i];
  3272. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3273. }
  3274. }
  3275. function composeSMaskLuminosity(maskData, layerData) {
  3276. var length = maskData.length;
  3277. for (var i = 3; i < length; i += 4) {
  3278. var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3279. (maskData[i - 2] * 152) + // * 0.59 ....
  3280. (maskData[i - 1] * 28)) | 0; // * 0.11 ....
  3281. layerData[i] = (layerData[i] * y) >> 16;
  3282. }
  3283. }
  3284. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3285. subtype, backdrop) {
  3286. var hasBackdrop = !!backdrop;
  3287. var r0 = hasBackdrop ? backdrop[0] : 0;
  3288. var g0 = hasBackdrop ? backdrop[1] : 0;
  3289. var b0 = hasBackdrop ? backdrop[2] : 0;
  3290. var composeFn;
  3291. if (subtype === 'Luminosity') {
  3292. composeFn = composeSMaskLuminosity;
  3293. } else {
  3294. composeFn = composeSMaskAlpha;
  3295. }
  3296. // processing image in chunks to save memory
  3297. var PIXELS_TO_PROCESS = 65536;
  3298. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3299. for (var row = 0; row < height; row += chunkSize) {
  3300. var chunkHeight = Math.min(chunkSize, height - row);
  3301. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3302. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3303. if (hasBackdrop) {
  3304. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3305. }
  3306. composeFn(maskData.data, layerData.data);
  3307. maskCtx.putImageData(layerData, 0, row);
  3308. }
  3309. }
  3310. function composeSMask(ctx, smask, layerCtx) {
  3311. var mask = smask.canvas;
  3312. var maskCtx = smask.context;
  3313. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3314. smask.offsetX, smask.offsetY);
  3315. var backdrop = smask.backdrop || null;
  3316. if (WebGLUtils.isEnabled) {
  3317. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3318. {subtype: smask.subtype, backdrop: backdrop});
  3319. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3320. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3321. return;
  3322. }
  3323. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3324. smask.subtype, backdrop);
  3325. ctx.drawImage(mask, 0, 0);
  3326. }
  3327. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3328. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3329. var NORMAL_CLIP = {};
  3330. var EO_CLIP = {};
  3331. CanvasGraphics.prototype = {
  3332. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3333. // For pdfs that use blend modes we have to clear the canvas else certain
  3334. // blend modes can look wrong since we'd be blending with a white
  3335. // backdrop. The problem with a transparent backdrop though is we then
  3336. // don't get sub pixel anti aliasing on text, so we fill with white if
  3337. // we can.
  3338. var width = this.ctx.canvas.width;
  3339. var height = this.ctx.canvas.height;
  3340. if (transparency) {
  3341. this.ctx.clearRect(0, 0, width, height);
  3342. } else {
  3343. this.ctx.mozOpaque = true;
  3344. this.ctx.save();
  3345. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3346. this.ctx.fillRect(0, 0, width, height);
  3347. this.ctx.restore();
  3348. }
  3349. var transform = viewport.transform;
  3350. this.ctx.save();
  3351. this.ctx.transform.apply(this.ctx, transform);
  3352. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3353. if (this.imageLayer) {
  3354. this.imageLayer.beginLayout();
  3355. }
  3356. },
  3357. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3358. operatorList,
  3359. executionStartIdx, continueCallback,
  3360. stepper) {
  3361. var argsArray = operatorList.argsArray;
  3362. var fnArray = operatorList.fnArray;
  3363. var i = executionStartIdx || 0;
  3364. var argsArrayLen = argsArray.length;
  3365. // Sometimes the OperatorList to execute is empty.
  3366. if (argsArrayLen === i) {
  3367. return i;
  3368. }
  3369. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3370. typeof continueCallback === 'function');
  3371. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3372. var steps = 0;
  3373. var commonObjs = this.commonObjs;
  3374. var objs = this.objs;
  3375. var fnId;
  3376. while (true) {
  3377. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3378. stepper.breakIt(i, continueCallback);
  3379. return i;
  3380. }
  3381. fnId = fnArray[i];
  3382. if (fnId !== OPS.dependency) {
  3383. this[fnId].apply(this, argsArray[i]);
  3384. } else {
  3385. var deps = argsArray[i];
  3386. for (var n = 0, nn = deps.length; n < nn; n++) {
  3387. var depObjId = deps[n];
  3388. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3389. var objsPool = common ? commonObjs : objs;
  3390. // If the promise isn't resolved yet, add the continueCallback
  3391. // to the promise and bail out.
  3392. if (!objsPool.isResolved(depObjId)) {
  3393. objsPool.get(depObjId, continueCallback);
  3394. return i;
  3395. }
  3396. }
  3397. }
  3398. i++;
  3399. // If the entire operatorList was executed, stop as were done.
  3400. if (i === argsArrayLen) {
  3401. return i;
  3402. }
  3403. // If the execution took longer then a certain amount of time and
  3404. // `continueCallback` is specified, interrupt the execution.
  3405. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3406. if (Date.now() > endTime) {
  3407. continueCallback();
  3408. return i;
  3409. }
  3410. steps = 0;
  3411. }
  3412. // If the operatorList isn't executed completely yet OR the execution
  3413. // time was short enough, do another execution round.
  3414. }
  3415. },
  3416. endDrawing: function CanvasGraphics_endDrawing() {
  3417. this.ctx.restore();
  3418. CachedCanvases.clear();
  3419. WebGLUtils.clear();
  3420. if (this.imageLayer) {
  3421. this.imageLayer.endLayout();
  3422. }
  3423. },
  3424. // Graphics state
  3425. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3426. this.current.lineWidth = width;
  3427. this.ctx.lineWidth = width;
  3428. },
  3429. setLineCap: function CanvasGraphics_setLineCap(style) {
  3430. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3431. },
  3432. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3433. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3434. },
  3435. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3436. this.ctx.miterLimit = limit;
  3437. },
  3438. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3439. var ctx = this.ctx;
  3440. if ('setLineDash' in ctx) {
  3441. ctx.setLineDash(dashArray);
  3442. ctx.lineDashOffset = dashPhase;
  3443. } else {
  3444. ctx.mozDash = dashArray;
  3445. ctx.mozDashOffset = dashPhase;
  3446. }
  3447. },
  3448. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3449. // Maybe if we one day fully support color spaces this will be important
  3450. // for now we can ignore.
  3451. // TODO set rendering intent?
  3452. },
  3453. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3454. // There's no way to control this with canvas, but we can safely ignore.
  3455. // TODO set flatness?
  3456. },
  3457. setGState: function CanvasGraphics_setGState(states) {
  3458. for (var i = 0, ii = states.length; i < ii; i++) {
  3459. var state = states[i];
  3460. var key = state[0];
  3461. var value = state[1];
  3462. switch (key) {
  3463. case 'LW':
  3464. this.setLineWidth(value);
  3465. break;
  3466. case 'LC':
  3467. this.setLineCap(value);
  3468. break;
  3469. case 'LJ':
  3470. this.setLineJoin(value);
  3471. break;
  3472. case 'ML':
  3473. this.setMiterLimit(value);
  3474. break;
  3475. case 'D':
  3476. this.setDash(value[0], value[1]);
  3477. break;
  3478. case 'RI':
  3479. this.setRenderingIntent(value);
  3480. break;
  3481. case 'FL':
  3482. this.setFlatness(value);
  3483. break;
  3484. case 'Font':
  3485. this.setFont(value[0], value[1]);
  3486. break;
  3487. case 'CA':
  3488. this.current.strokeAlpha = state[1];
  3489. break;
  3490. case 'ca':
  3491. this.current.fillAlpha = state[1];
  3492. this.ctx.globalAlpha = state[1];
  3493. break;
  3494. case 'BM':
  3495. if (value && value.name && (value.name !== 'Normal')) {
  3496. var mode = value.name.replace(/([A-Z])/g,
  3497. function(c) {
  3498. return '-' + c.toLowerCase();
  3499. }
  3500. ).substring(1);
  3501. this.ctx.globalCompositeOperation = mode;
  3502. if (this.ctx.globalCompositeOperation !== mode) {
  3503. warn('globalCompositeOperation "' + mode +
  3504. '" is not supported');
  3505. }
  3506. } else {
  3507. this.ctx.globalCompositeOperation = 'source-over';
  3508. }
  3509. break;
  3510. case 'SMask':
  3511. if (this.current.activeSMask) {
  3512. this.endSMaskGroup();
  3513. }
  3514. this.current.activeSMask = value ? this.tempSMask : null;
  3515. if (this.current.activeSMask) {
  3516. this.beginSMaskGroup();
  3517. }
  3518. this.tempSMask = null;
  3519. break;
  3520. }
  3521. }
  3522. },
  3523. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3524. var activeSMask = this.current.activeSMask;
  3525. var drawnWidth = activeSMask.canvas.width;
  3526. var drawnHeight = activeSMask.canvas.height;
  3527. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3528. var scratchCanvas = CachedCanvases.getCanvas(
  3529. cacheId, drawnWidth, drawnHeight, true);
  3530. var currentCtx = this.ctx;
  3531. var currentTransform = currentCtx.mozCurrentTransform;
  3532. this.ctx.save();
  3533. var groupCtx = scratchCanvas.context;
  3534. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3535. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3536. groupCtx.transform.apply(groupCtx, currentTransform);
  3537. copyCtxState(currentCtx, groupCtx);
  3538. this.ctx = groupCtx;
  3539. this.setGState([
  3540. ['BM', 'Normal'],
  3541. ['ca', 1],
  3542. ['CA', 1]
  3543. ]);
  3544. this.groupStack.push(currentCtx);
  3545. this.groupLevel++;
  3546. },
  3547. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3548. var groupCtx = this.ctx;
  3549. this.groupLevel--;
  3550. this.ctx = this.groupStack.pop();
  3551. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3552. this.ctx.restore();
  3553. },
  3554. save: function CanvasGraphics_save() {
  3555. this.ctx.save();
  3556. var old = this.current;
  3557. this.stateStack.push(old);
  3558. this.current = old.clone();
  3559. this.current.activeSMask = null;
  3560. },
  3561. restore: function CanvasGraphics_restore() {
  3562. if (this.stateStack.length !== 0) {
  3563. if (this.current.activeSMask !== null) {
  3564. this.endSMaskGroup();
  3565. }
  3566. this.current = this.stateStack.pop();
  3567. this.ctx.restore();
  3568. }
  3569. },
  3570. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3571. this.ctx.transform(a, b, c, d, e, f);
  3572. },
  3573. // Path
  3574. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3575. var ctx = this.ctx;
  3576. var current = this.current;
  3577. var x = current.x, y = current.y;
  3578. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3579. switch (ops[i] | 0) {
  3580. case OPS.moveTo:
  3581. x = args[j++];
  3582. y = args[j++];
  3583. ctx.moveTo(x, y);
  3584. break;
  3585. case OPS.lineTo:
  3586. x = args[j++];
  3587. y = args[j++];
  3588. ctx.lineTo(x, y);
  3589. break;
  3590. case OPS.curveTo:
  3591. x = args[j + 4];
  3592. y = args[j + 5];
  3593. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3594. x, y);
  3595. j += 6;
  3596. break;
  3597. case OPS.curveTo2:
  3598. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3599. args[j + 2], args[j + 3]);
  3600. x = args[j + 2];
  3601. y = args[j + 3];
  3602. j += 4;
  3603. break;
  3604. case OPS.curveTo3:
  3605. x = args[j + 2];
  3606. y = args[j + 3];
  3607. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3608. j += 4;
  3609. break;
  3610. case OPS.closePath:
  3611. ctx.closePath();
  3612. break;
  3613. }
  3614. }
  3615. current.setCurrentPoint(x, y);
  3616. },
  3617. closePath: function CanvasGraphics_closePath() {
  3618. this.ctx.closePath();
  3619. },
  3620. rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
  3621. if (width === 0) {
  3622. width = this.getSinglePixelWidth();
  3623. }
  3624. if (height === 0) {
  3625. height = this.getSinglePixelWidth();
  3626. }
  3627. this.ctx.rect(x, y, width, height);
  3628. },
  3629. stroke: function CanvasGraphics_stroke(consumePath) {
  3630. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3631. var ctx = this.ctx;
  3632. var strokeColor = this.current.strokeColor;
  3633. if (this.current.lineWidth === 0) {
  3634. ctx.lineWidth = this.getSinglePixelWidth();
  3635. }
  3636. // For stroke we want to temporarily change the global alpha to the
  3637. // stroking alpha.
  3638. ctx.globalAlpha = this.current.strokeAlpha;
  3639. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3640. strokeColor.type === 'Pattern') {
  3641. // for patterns, we transform to pattern space, calculate
  3642. // the pattern, call stroke, and restore to user space
  3643. ctx.save();
  3644. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3645. ctx.stroke();
  3646. ctx.restore();
  3647. } else {
  3648. ctx.stroke();
  3649. }
  3650. if (consumePath) {
  3651. this.consumePath();
  3652. }
  3653. // Restore the global alpha to the fill alpha
  3654. ctx.globalAlpha = this.current.fillAlpha;
  3655. },
  3656. closeStroke: function CanvasGraphics_closeStroke() {
  3657. this.closePath();
  3658. this.stroke();
  3659. },
  3660. fill: function CanvasGraphics_fill(consumePath) {
  3661. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3662. var ctx = this.ctx;
  3663. var fillColor = this.current.fillColor;
  3664. var needRestore = false;
  3665. if (fillColor && fillColor.hasOwnProperty('type') &&
  3666. fillColor.type === 'Pattern') {
  3667. ctx.save();
  3668. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3669. needRestore = true;
  3670. }
  3671. if (this.pendingEOFill) {
  3672. if (ctx.mozFillRule !== undefined) {
  3673. ctx.mozFillRule = 'evenodd';
  3674. ctx.fill();
  3675. ctx.mozFillRule = 'nonzero';
  3676. } else {
  3677. try {
  3678. ctx.fill('evenodd');
  3679. } catch (ex) {
  3680. // shouldn't really happen, but browsers might think differently
  3681. ctx.fill();
  3682. }
  3683. }
  3684. this.pendingEOFill = false;
  3685. } else {
  3686. ctx.fill();
  3687. }
  3688. if (needRestore) {
  3689. ctx.restore();
  3690. }
  3691. if (consumePath) {
  3692. this.consumePath();
  3693. }
  3694. },
  3695. eoFill: function CanvasGraphics_eoFill() {
  3696. this.pendingEOFill = true;
  3697. this.fill();
  3698. },
  3699. fillStroke: function CanvasGraphics_fillStroke() {
  3700. this.fill(false);
  3701. this.stroke(false);
  3702. this.consumePath();
  3703. },
  3704. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3705. this.pendingEOFill = true;
  3706. this.fillStroke();
  3707. },
  3708. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3709. this.closePath();
  3710. this.fillStroke();
  3711. },
  3712. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3713. this.pendingEOFill = true;
  3714. this.closePath();
  3715. this.fillStroke();
  3716. },
  3717. endPath: function CanvasGraphics_endPath() {
  3718. this.consumePath();
  3719. },
  3720. // Clipping
  3721. clip: function CanvasGraphics_clip() {
  3722. this.pendingClip = NORMAL_CLIP;
  3723. },
  3724. eoClip: function CanvasGraphics_eoClip() {
  3725. this.pendingClip = EO_CLIP;
  3726. },
  3727. // Text
  3728. beginText: function CanvasGraphics_beginText() {
  3729. this.current.textMatrix = IDENTITY_MATRIX;
  3730. this.current.textMatrixScale = 1;
  3731. this.current.x = this.current.lineX = 0;
  3732. this.current.y = this.current.lineY = 0;
  3733. },
  3734. endText: function CanvasGraphics_endText() {
  3735. var paths = this.pendingTextPaths;
  3736. var ctx = this.ctx;
  3737. if (paths === undefined) {
  3738. ctx.beginPath();
  3739. return;
  3740. }
  3741. ctx.save();
  3742. ctx.beginPath();
  3743. for (var i = 0; i < paths.length; i++) {
  3744. var path = paths[i];
  3745. ctx.setTransform.apply(ctx, path.transform);
  3746. ctx.translate(path.x, path.y);
  3747. path.addToPath(ctx, path.fontSize);
  3748. }
  3749. ctx.restore();
  3750. ctx.clip();
  3751. ctx.beginPath();
  3752. delete this.pendingTextPaths;
  3753. },
  3754. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  3755. this.current.charSpacing = spacing;
  3756. },
  3757. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  3758. this.current.wordSpacing = spacing;
  3759. },
  3760. setHScale: function CanvasGraphics_setHScale(scale) {
  3761. this.current.textHScale = scale / 100;
  3762. },
  3763. setLeading: function CanvasGraphics_setLeading(leading) {
  3764. this.current.leading = -leading;
  3765. },
  3766. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  3767. var fontObj = this.commonObjs.get(fontRefName);
  3768. var current = this.current;
  3769. if (!fontObj) {
  3770. error('Can\'t find font for ' + fontRefName);
  3771. }
  3772. current.fontMatrix = (fontObj.fontMatrix ?
  3773. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3774. // A valid matrix needs all main diagonal elements to be non-zero
  3775. // This also ensures we bypass FF bugzilla bug #719844.
  3776. if (current.fontMatrix[0] === 0 ||
  3777. current.fontMatrix[3] === 0) {
  3778. warn('Invalid font matrix for font ' + fontRefName);
  3779. }
  3780. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  3781. // and in some docs this can be negative (inverted x-y axes).
  3782. if (size < 0) {
  3783. size = -size;
  3784. current.fontDirection = -1;
  3785. } else {
  3786. current.fontDirection = 1;
  3787. }
  3788. this.current.font = fontObj;
  3789. this.current.fontSize = size;
  3790. if (fontObj.isType3Font) {
  3791. return; // we don't need ctx.font for Type3 fonts
  3792. }
  3793. var name = fontObj.loadedName || 'sans-serif';
  3794. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3795. (fontObj.bold ? 'bold' : 'normal');
  3796. var italic = fontObj.italic ? 'italic' : 'normal';
  3797. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  3798. // Some font backends cannot handle fonts below certain size.
  3799. // Keeping the font at minimal size and using the fontSizeScale to change
  3800. // the current transformation matrix before the fillText/strokeText.
  3801. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  3802. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  3803. this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
  3804. size / MIN_FONT_SIZE;
  3805. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  3806. this.ctx.font = rule;
  3807. },
  3808. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  3809. this.current.textRenderingMode = mode;
  3810. },
  3811. setTextRise: function CanvasGraphics_setTextRise(rise) {
  3812. this.current.textRise = rise;
  3813. },
  3814. moveText: function CanvasGraphics_moveText(x, y) {
  3815. this.current.x = this.current.lineX += x;
  3816. this.current.y = this.current.lineY += y;
  3817. },
  3818. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  3819. this.setLeading(-y);
  3820. this.moveText(x, y);
  3821. },
  3822. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  3823. this.current.textMatrix = [a, b, c, d, e, f];
  3824. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  3825. this.current.x = this.current.lineX = 0;
  3826. this.current.y = this.current.lineY = 0;
  3827. },
  3828. nextLine: function CanvasGraphics_nextLine() {
  3829. this.moveText(0, this.current.leading);
  3830. },
  3831. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  3832. var ctx = this.ctx;
  3833. var current = this.current;
  3834. var font = current.font;
  3835. var textRenderingMode = current.textRenderingMode;
  3836. var fontSize = current.fontSize / current.fontSizeScale;
  3837. var fillStrokeMode = textRenderingMode &
  3838. TextRenderingMode.FILL_STROKE_MASK;
  3839. var isAddToPathSet = !!(textRenderingMode &
  3840. TextRenderingMode.ADD_TO_PATH_FLAG);
  3841. var addToPath;
  3842. if (font.disableFontFace || isAddToPathSet) {
  3843. addToPath = font.getPathGenerator(this.commonObjs, character);
  3844. }
  3845. if (font.disableFontFace) {
  3846. ctx.save();
  3847. ctx.translate(x, y);
  3848. ctx.beginPath();
  3849. addToPath(ctx, fontSize);
  3850. if (fillStrokeMode === TextRenderingMode.FILL ||
  3851. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3852. ctx.fill();
  3853. }
  3854. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3855. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3856. ctx.stroke();
  3857. }
  3858. ctx.restore();
  3859. } else {
  3860. if (fillStrokeMode === TextRenderingMode.FILL ||
  3861. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3862. ctx.fillText(character, x, y);
  3863. }
  3864. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3865. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3866. ctx.strokeText(character, x, y);
  3867. }
  3868. }
  3869. if (isAddToPathSet) {
  3870. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  3871. paths.push({
  3872. transform: ctx.mozCurrentTransform,
  3873. x: x,
  3874. y: y,
  3875. fontSize: fontSize,
  3876. addToPath: addToPath
  3877. });
  3878. }
  3879. },
  3880. get isFontSubpixelAAEnabled() {
  3881. // Checks if anti-aliasing is enabled when scaled text is painted.
  3882. // On Windows GDI scaled fonts looks bad.
  3883. var ctx = document.createElement('canvas').getContext('2d');
  3884. ctx.scale(1.5, 1);
  3885. ctx.fillText('I', 0, 10);
  3886. var data = ctx.getImageData(0, 0, 10, 10).data;
  3887. var enabled = false;
  3888. for (var i = 3; i < data.length; i += 4) {
  3889. if (data[i] > 0 && data[i] < 255) {
  3890. enabled = true;
  3891. break;
  3892. }
  3893. }
  3894. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  3895. },
  3896. showText: function CanvasGraphics_showText(glyphs) {
  3897. var current = this.current;
  3898. var font = current.font;
  3899. if (font.isType3Font) {
  3900. return this.showType3Text(glyphs);
  3901. }
  3902. var fontSize = current.fontSize;
  3903. if (fontSize === 0) {
  3904. return;
  3905. }
  3906. var ctx = this.ctx;
  3907. var fontSizeScale = current.fontSizeScale;
  3908. var charSpacing = current.charSpacing;
  3909. var wordSpacing = current.wordSpacing;
  3910. var fontDirection = current.fontDirection;
  3911. var textHScale = current.textHScale * fontDirection;
  3912. var glyphsLength = glyphs.length;
  3913. var vertical = font.vertical;
  3914. var defaultVMetrics = font.defaultVMetrics;
  3915. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3916. var simpleFillText =
  3917. current.textRenderingMode === TextRenderingMode.FILL &&
  3918. !font.disableFontFace;
  3919. ctx.save();
  3920. ctx.transform.apply(ctx, current.textMatrix);
  3921. ctx.translate(current.x, current.y + current.textRise);
  3922. if (fontDirection > 0) {
  3923. ctx.scale(textHScale, -1);
  3924. } else {
  3925. ctx.scale(textHScale, 1);
  3926. }
  3927. var lineWidth = current.lineWidth;
  3928. var scale = current.textMatrixScale;
  3929. if (scale === 0 || lineWidth === 0) {
  3930. lineWidth = this.getSinglePixelWidth();
  3931. } else {
  3932. lineWidth /= scale;
  3933. }
  3934. if (fontSizeScale != 1.0) {
  3935. ctx.scale(fontSizeScale, fontSizeScale);
  3936. lineWidth /= fontSizeScale;
  3937. }
  3938. ctx.lineWidth = lineWidth;
  3939. var x = 0, i;
  3940. for (i = 0; i < glyphsLength; ++i) {
  3941. var glyph = glyphs[i];
  3942. if (glyph === null) {
  3943. // word break
  3944. x += fontDirection * wordSpacing;
  3945. continue;
  3946. } else if (isNum(glyph)) {
  3947. x += -glyph * fontSize * 0.001;
  3948. continue;
  3949. }
  3950. var restoreNeeded = false;
  3951. var character = glyph.fontChar;
  3952. var accent = glyph.accent;
  3953. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  3954. var width = glyph.width;
  3955. if (vertical) {
  3956. var vmetric, vx, vy;
  3957. vmetric = glyph.vmetric || defaultVMetrics;
  3958. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  3959. vx = -vx * widthAdvanceScale;
  3960. vy = vmetric[2] * widthAdvanceScale;
  3961. width = vmetric ? -vmetric[0] : width;
  3962. scaledX = vx / fontSizeScale;
  3963. scaledY = (x + vy) / fontSizeScale;
  3964. } else {
  3965. scaledX = x / fontSizeScale;
  3966. scaledY = 0;
  3967. }
  3968. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  3969. // some standard fonts may not have the exact width, trying to
  3970. // rescale per character
  3971. var measuredWidth = ctx.measureText(character).width * 1000 /
  3972. fontSize * fontSizeScale;
  3973. var characterScaleX = width / measuredWidth;
  3974. restoreNeeded = true;
  3975. ctx.save();
  3976. ctx.scale(characterScaleX, 1);
  3977. scaledX /= characterScaleX;
  3978. }
  3979. if (simpleFillText && !accent) {
  3980. // common case
  3981. ctx.fillText(character, scaledX, scaledY);
  3982. } else {
  3983. this.paintChar(character, scaledX, scaledY);
  3984. if (accent) {
  3985. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  3986. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  3987. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  3988. }
  3989. }
  3990. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3991. x += charWidth;
  3992. if (restoreNeeded) {
  3993. ctx.restore();
  3994. }
  3995. }
  3996. if (vertical) {
  3997. current.y -= x * textHScale;
  3998. } else {
  3999. current.x += x * textHScale;
  4000. }
  4001. ctx.restore();
  4002. },
  4003. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4004. // Type3 fonts - each glyph is a "mini-PDF"
  4005. var ctx = this.ctx;
  4006. var current = this.current;
  4007. var font = current.font;
  4008. var fontSize = current.fontSize;
  4009. var fontDirection = current.fontDirection;
  4010. var charSpacing = current.charSpacing;
  4011. var wordSpacing = current.wordSpacing;
  4012. var textHScale = current.textHScale * fontDirection;
  4013. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4014. var glyphsLength = glyphs.length;
  4015. var i, glyph, width;
  4016. if (fontSize === 0) {
  4017. return;
  4018. }
  4019. ctx.save();
  4020. ctx.transform.apply(ctx, current.textMatrix);
  4021. ctx.translate(current.x, current.y);
  4022. ctx.scale(textHScale, 1);
  4023. for (i = 0; i < glyphsLength; ++i) {
  4024. glyph = glyphs[i];
  4025. if (glyph === null) {
  4026. // word break
  4027. this.ctx.translate(wordSpacing, 0);
  4028. current.x += wordSpacing * textHScale;
  4029. continue;
  4030. } else if (isNum(glyph)) {
  4031. var spacingLength = -glyph * 0.001 * fontSize;
  4032. this.ctx.translate(spacingLength, 0);
  4033. current.x += spacingLength * textHScale;
  4034. continue;
  4035. }
  4036. this.processingType3 = glyph;
  4037. this.save();
  4038. ctx.scale(fontSize, fontSize);
  4039. ctx.transform.apply(ctx, fontMatrix);
  4040. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4041. this.executeOperatorList(operatorList);
  4042. this.restore();
  4043. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4044. width = ((transformed[0] * fontSize + charSpacing) * fontDirection);
  4045. ctx.translate(width, 0);
  4046. current.x += width * textHScale;
  4047. }
  4048. ctx.restore();
  4049. this.processingType3 = null;
  4050. },
  4051. // Type3 fonts
  4052. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4053. // We can safely ignore this since the width should be the same
  4054. // as the width in the Widths array.
  4055. },
  4056. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4057. yWidth,
  4058. llx,
  4059. lly,
  4060. urx,
  4061. ury) {
  4062. // TODO According to the spec we're also suppose to ignore any operators
  4063. // that set color or include images while processing this type3 font.
  4064. this.rectangle(llx, lly, urx - llx, ury - lly);
  4065. this.clip();
  4066. this.endPath();
  4067. },
  4068. // Color
  4069. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4070. var pattern;
  4071. if (IR[0] === 'TilingPattern') {
  4072. var color = IR[1];
  4073. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4074. this.commonObjs, this.baseTransform);
  4075. } else {
  4076. pattern = getShadingPatternFromIR(IR);
  4077. }
  4078. return pattern;
  4079. },
  4080. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4081. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4082. },
  4083. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4084. this.current.fillColor = this.getColorN_Pattern(arguments);
  4085. },
  4086. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4087. var color = Util.makeCssRgb(arguments);
  4088. this.ctx.strokeStyle = color;
  4089. this.current.strokeColor = color;
  4090. },
  4091. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4092. var color = Util.makeCssRgb(arguments);
  4093. this.ctx.fillStyle = color;
  4094. this.current.fillColor = color;
  4095. },
  4096. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4097. var ctx = this.ctx;
  4098. this.save();
  4099. var pattern = getShadingPatternFromIR(patternIR);
  4100. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4101. var inv = ctx.mozCurrentTransformInverse;
  4102. if (inv) {
  4103. var canvas = ctx.canvas;
  4104. var width = canvas.width;
  4105. var height = canvas.height;
  4106. var bl = Util.applyTransform([0, 0], inv);
  4107. var br = Util.applyTransform([0, height], inv);
  4108. var ul = Util.applyTransform([width, 0], inv);
  4109. var ur = Util.applyTransform([width, height], inv);
  4110. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4111. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4112. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4113. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4114. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4115. } else {
  4116. // HACK to draw the gradient onto an infinite rectangle.
  4117. // PDF gradients are drawn across the entire image while
  4118. // Canvas only allows gradients to be drawn in a rectangle
  4119. // The following bug should allow us to remove this.
  4120. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4121. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4122. }
  4123. this.restore();
  4124. },
  4125. // Images
  4126. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4127. error('Should not call beginInlineImage');
  4128. },
  4129. beginImageData: function CanvasGraphics_beginImageData() {
  4130. error('Should not call beginImageData');
  4131. },
  4132. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4133. bbox) {
  4134. this.save();
  4135. this.baseTransformStack.push(this.baseTransform);
  4136. if (isArray(matrix) && 6 === matrix.length) {
  4137. this.transform.apply(this, matrix);
  4138. }
  4139. this.baseTransform = this.ctx.mozCurrentTransform;
  4140. if (isArray(bbox) && 4 === bbox.length) {
  4141. var width = bbox[2] - bbox[0];
  4142. var height = bbox[3] - bbox[1];
  4143. this.rectangle(bbox[0], bbox[1], width, height);
  4144. this.clip();
  4145. this.endPath();
  4146. }
  4147. },
  4148. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4149. this.restore();
  4150. this.baseTransform = this.baseTransformStack.pop();
  4151. },
  4152. beginGroup: function CanvasGraphics_beginGroup(group) {
  4153. this.save();
  4154. var currentCtx = this.ctx;
  4155. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4156. // group results aren't usually that different and they even have tools
  4157. // that ignore this setting. Notes from Rik on implmenting:
  4158. // - When you encounter an transparency group, create a new canvas with
  4159. // the dimensions of the bbox
  4160. // - copy the content from the previous canvas to the new canvas
  4161. // - draw as usual
  4162. // - remove the backdrop alpha:
  4163. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4164. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4165. // backdrop
  4166. // - remove background color:
  4167. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4168. if (!group.isolated) {
  4169. info('TODO: Support non-isolated groups.');
  4170. }
  4171. // TODO knockout - supposedly possible with the clever use of compositing
  4172. // modes.
  4173. if (group.knockout) {
  4174. warn('Knockout groups not supported.');
  4175. }
  4176. var currentTransform = currentCtx.mozCurrentTransform;
  4177. if (group.matrix) {
  4178. currentCtx.transform.apply(currentCtx, group.matrix);
  4179. }
  4180. assert(group.bbox, 'Bounding box is required.');
  4181. // Based on the current transform figure out how big the bounding box
  4182. // will actually be.
  4183. var bounds = Util.getAxialAlignedBoundingBox(
  4184. group.bbox,
  4185. currentCtx.mozCurrentTransform);
  4186. // Clip the bounding box to the current canvas.
  4187. var canvasBounds = [0,
  4188. 0,
  4189. currentCtx.canvas.width,
  4190. currentCtx.canvas.height];
  4191. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4192. // Use ceil in case we're between sizes so we don't create canvas that is
  4193. // too small and make the canvas at least 1x1 pixels.
  4194. var offsetX = Math.floor(bounds[0]);
  4195. var offsetY = Math.floor(bounds[1]);
  4196. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4197. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4198. var scaleX = 1, scaleY = 1;
  4199. if (drawnWidth > MAX_GROUP_SIZE) {
  4200. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4201. drawnWidth = MAX_GROUP_SIZE;
  4202. }
  4203. if (drawnHeight > MAX_GROUP_SIZE) {
  4204. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4205. drawnHeight = MAX_GROUP_SIZE;
  4206. }
  4207. var cacheId = 'groupAt' + this.groupLevel;
  4208. if (group.smask) {
  4209. // Using two cache entries is case if masks are used one after another.
  4210. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4211. }
  4212. var scratchCanvas = CachedCanvases.getCanvas(
  4213. cacheId, drawnWidth, drawnHeight, true);
  4214. var groupCtx = scratchCanvas.context;
  4215. // Since we created a new canvas that is just the size of the bounding box
  4216. // we have to translate the group ctx.
  4217. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4218. groupCtx.translate(-offsetX, -offsetY);
  4219. groupCtx.transform.apply(groupCtx, currentTransform);
  4220. if (group.smask) {
  4221. // Saving state and cached mask to be used in setGState.
  4222. this.smaskStack.push({
  4223. canvas: scratchCanvas.canvas,
  4224. context: groupCtx,
  4225. offsetX: offsetX,
  4226. offsetY: offsetY,
  4227. scaleX: scaleX,
  4228. scaleY: scaleY,
  4229. subtype: group.smask.subtype,
  4230. backdrop: group.smask.backdrop
  4231. });
  4232. } else {
  4233. // Setup the current ctx so when the group is popped we draw it at the
  4234. // right location.
  4235. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4236. currentCtx.translate(offsetX, offsetY);
  4237. currentCtx.scale(scaleX, scaleY);
  4238. }
  4239. // The transparency group inherits all off the current graphics state
  4240. // except the blend mode, soft mask, and alpha constants.
  4241. copyCtxState(currentCtx, groupCtx);
  4242. this.ctx = groupCtx;
  4243. this.setGState([
  4244. ['BM', 'Normal'],
  4245. ['ca', 1],
  4246. ['CA', 1]
  4247. ]);
  4248. this.groupStack.push(currentCtx);
  4249. this.groupLevel++;
  4250. },
  4251. endGroup: function CanvasGraphics_endGroup(group) {
  4252. this.groupLevel--;
  4253. var groupCtx = this.ctx;
  4254. this.ctx = this.groupStack.pop();
  4255. // Turn off image smoothing to avoid sub pixel interpolation which can
  4256. // look kind of blurry for some pdfs.
  4257. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4258. this.ctx.imageSmoothingEnabled = false;
  4259. } else {
  4260. this.ctx.mozImageSmoothingEnabled = false;
  4261. }
  4262. if (group.smask) {
  4263. this.tempSMask = this.smaskStack.pop();
  4264. } else {
  4265. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4266. }
  4267. this.restore();
  4268. },
  4269. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4270. this.save();
  4271. this.current = new CanvasExtraState();
  4272. },
  4273. endAnnotations: function CanvasGraphics_endAnnotations() {
  4274. this.restore();
  4275. },
  4276. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4277. matrix) {
  4278. this.save();
  4279. if (isArray(rect) && 4 === rect.length) {
  4280. var width = rect[2] - rect[0];
  4281. var height = rect[3] - rect[1];
  4282. this.rectangle(rect[0], rect[1], width, height);
  4283. this.clip();
  4284. this.endPath();
  4285. }
  4286. this.transform.apply(this, transform);
  4287. this.transform.apply(this, matrix);
  4288. },
  4289. endAnnotation: function CanvasGraphics_endAnnotation() {
  4290. this.restore();
  4291. },
  4292. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4293. var domImage = this.objs.get(objId);
  4294. if (!domImage) {
  4295. warn('Dependent image isn\'t ready yet');
  4296. return;
  4297. }
  4298. this.save();
  4299. var ctx = this.ctx;
  4300. // scale the image to the unit square
  4301. ctx.scale(1 / w, -1 / h);
  4302. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4303. 0, -h, w, h);
  4304. if (this.imageLayer) {
  4305. var currentTransform = ctx.mozCurrentTransformInverse;
  4306. var position = this.getCanvasPosition(0, 0);
  4307. this.imageLayer.appendImage({
  4308. objId: objId,
  4309. left: position[0],
  4310. top: position[1],
  4311. width: w / currentTransform[0],
  4312. height: h / currentTransform[3]
  4313. });
  4314. }
  4315. this.restore();
  4316. },
  4317. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4318. var ctx = this.ctx;
  4319. var width = img.width, height = img.height;
  4320. var glyph = this.processingType3;
  4321. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  4322. var MAX_SIZE_TO_COMPILE = 1000;
  4323. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4324. glyph.compiled =
  4325. compileType3Glyph({data: img.data, width: width, height: height});
  4326. } else {
  4327. glyph.compiled = null;
  4328. }
  4329. }
  4330. if (glyph && glyph.compiled) {
  4331. glyph.compiled(ctx);
  4332. return;
  4333. }
  4334. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4335. var maskCtx = maskCanvas.context;
  4336. maskCtx.save();
  4337. putBinaryImageMask(maskCtx, img);
  4338. maskCtx.globalCompositeOperation = 'source-in';
  4339. var fillColor = this.current.fillColor;
  4340. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4341. fillColor.type === 'Pattern') ?
  4342. fillColor.getPattern(maskCtx, this) : fillColor;
  4343. maskCtx.fillRect(0, 0, width, height);
  4344. maskCtx.restore();
  4345. this.paintInlineImageXObject(maskCanvas.canvas);
  4346. },
  4347. paintImageMaskXObjectRepeat:
  4348. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4349. scaleY, positions) {
  4350. var width = imgData.width;
  4351. var height = imgData.height;
  4352. var ctx = this.ctx;
  4353. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4354. var maskCtx = maskCanvas.context;
  4355. maskCtx.save();
  4356. putBinaryImageMask(maskCtx, imgData);
  4357. maskCtx.globalCompositeOperation = 'source-in';
  4358. var fillColor = this.current.fillColor;
  4359. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4360. fillColor.type === 'Pattern') ?
  4361. fillColor.getPattern(maskCtx, this) : fillColor;
  4362. maskCtx.fillRect(0, 0, width, height);
  4363. maskCtx.restore();
  4364. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4365. ctx.save();
  4366. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4367. ctx.scale(1, -1);
  4368. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4369. 0, -1, 1, 1);
  4370. ctx.restore();
  4371. }
  4372. },
  4373. paintImageMaskXObjectGroup:
  4374. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4375. var ctx = this.ctx;
  4376. for (var i = 0, ii = images.length; i < ii; i++) {
  4377. var image = images[i];
  4378. var width = image.width, height = image.height;
  4379. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4380. var maskCtx = maskCanvas.context;
  4381. maskCtx.save();
  4382. putBinaryImageMask(maskCtx, image);
  4383. maskCtx.globalCompositeOperation = 'source-in';
  4384. var fillColor = this.current.fillColor;
  4385. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4386. fillColor.type === 'Pattern') ?
  4387. fillColor.getPattern(maskCtx, this) : fillColor;
  4388. maskCtx.fillRect(0, 0, width, height);
  4389. maskCtx.restore();
  4390. ctx.save();
  4391. ctx.transform.apply(ctx, image.transform);
  4392. ctx.scale(1, -1);
  4393. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4394. 0, -1, 1, 1);
  4395. ctx.restore();
  4396. }
  4397. },
  4398. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4399. var imgData = this.objs.get(objId);
  4400. if (!imgData) {
  4401. warn('Dependent image isn\'t ready yet');
  4402. return;
  4403. }
  4404. this.paintInlineImageXObject(imgData);
  4405. },
  4406. paintImageXObjectRepeat:
  4407. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4408. positions) {
  4409. var imgData = this.objs.get(objId);
  4410. if (!imgData) {
  4411. warn('Dependent image isn\'t ready yet');
  4412. return;
  4413. }
  4414. var width = imgData.width;
  4415. var height = imgData.height;
  4416. var map = [];
  4417. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4418. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4419. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4420. }
  4421. this.paintInlineImageXObjectGroup(imgData, map);
  4422. },
  4423. paintInlineImageXObject:
  4424. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4425. var width = imgData.width;
  4426. var height = imgData.height;
  4427. var ctx = this.ctx;
  4428. this.save();
  4429. // scale the image to the unit square
  4430. ctx.scale(1 / width, -1 / height);
  4431. var currentTransform = ctx.mozCurrentTransformInverse;
  4432. var a = currentTransform[0], b = currentTransform[1];
  4433. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4434. var c = currentTransform[2], d = currentTransform[3];
  4435. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4436. var imgToPaint, tmpCanvas;
  4437. // instanceof HTMLElement does not work in jsdom node.js module
  4438. if (imgData instanceof HTMLElement || !imgData.data) {
  4439. imgToPaint = imgData;
  4440. } else {
  4441. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4442. var tmpCtx = tmpCanvas.context;
  4443. putBinaryImageData(tmpCtx, imgData);
  4444. imgToPaint = tmpCanvas.canvas;
  4445. }
  4446. var paintWidth = width, paintHeight = height;
  4447. var tmpCanvasId = 'prescale1';
  4448. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4449. // pixels during drawImage operation, painting on the temporary canvas(es)
  4450. // that are twice smaller in size
  4451. while ((widthScale > 2 && paintWidth > 1) ||
  4452. (heightScale > 2 && paintHeight > 1)) {
  4453. var newWidth = paintWidth, newHeight = paintHeight;
  4454. if (widthScale > 2 && paintWidth > 1) {
  4455. newWidth = Math.ceil(paintWidth / 2);
  4456. widthScale /= paintWidth / newWidth;
  4457. }
  4458. if (heightScale > 2 && paintHeight > 1) {
  4459. newHeight = Math.ceil(paintHeight / 2);
  4460. heightScale /= paintHeight / newHeight;
  4461. }
  4462. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4463. tmpCtx = tmpCanvas.context;
  4464. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4465. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4466. 0, 0, newWidth, newHeight);
  4467. imgToPaint = tmpCanvas.canvas;
  4468. paintWidth = newWidth;
  4469. paintHeight = newHeight;
  4470. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4471. }
  4472. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4473. 0, -height, width, height);
  4474. if (this.imageLayer) {
  4475. var position = this.getCanvasPosition(0, -height);
  4476. this.imageLayer.appendImage({
  4477. imgData: imgData,
  4478. left: position[0],
  4479. top: position[1],
  4480. width: width / currentTransform[0],
  4481. height: height / currentTransform[3]
  4482. });
  4483. }
  4484. this.restore();
  4485. },
  4486. paintInlineImageXObjectGroup:
  4487. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4488. var ctx = this.ctx;
  4489. var w = imgData.width;
  4490. var h = imgData.height;
  4491. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4492. var tmpCtx = tmpCanvas.context;
  4493. putBinaryImageData(tmpCtx, imgData);
  4494. for (var i = 0, ii = map.length; i < ii; i++) {
  4495. var entry = map[i];
  4496. ctx.save();
  4497. ctx.transform.apply(ctx, entry.transform);
  4498. ctx.scale(1, -1);
  4499. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4500. 0, -1, 1, 1);
  4501. if (this.imageLayer) {
  4502. var position = this.getCanvasPosition(entry.x, entry.y);
  4503. this.imageLayer.appendImage({
  4504. imgData: imgData,
  4505. left: position[0],
  4506. top: position[1],
  4507. width: w,
  4508. height: h
  4509. });
  4510. }
  4511. ctx.restore();
  4512. }
  4513. },
  4514. paintSolidColorImageMask:
  4515. function CanvasGraphics_paintSolidColorImageMask() {
  4516. this.ctx.fillRect(0, 0, 1, 1);
  4517. },
  4518. // Marked content
  4519. markPoint: function CanvasGraphics_markPoint(tag) {
  4520. // TODO Marked content.
  4521. },
  4522. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4523. // TODO Marked content.
  4524. },
  4525. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4526. // TODO Marked content.
  4527. },
  4528. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4529. tag, properties) {
  4530. // TODO Marked content.
  4531. },
  4532. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4533. // TODO Marked content.
  4534. },
  4535. // Compatibility
  4536. beginCompat: function CanvasGraphics_beginCompat() {
  4537. // TODO ignore undefined operators (should we do that anyway?)
  4538. },
  4539. endCompat: function CanvasGraphics_endCompat() {
  4540. // TODO stop ignoring undefined operators
  4541. },
  4542. // Helper functions
  4543. consumePath: function CanvasGraphics_consumePath() {
  4544. var ctx = this.ctx;
  4545. if (this.pendingClip) {
  4546. if (this.pendingClip === EO_CLIP) {
  4547. if (ctx.mozFillRule !== undefined) {
  4548. ctx.mozFillRule = 'evenodd';
  4549. ctx.clip();
  4550. ctx.mozFillRule = 'nonzero';
  4551. } else {
  4552. try {
  4553. ctx.clip('evenodd');
  4554. } catch (ex) {
  4555. // shouldn't really happen, but browsers might think differently
  4556. ctx.clip();
  4557. }
  4558. }
  4559. } else {
  4560. ctx.clip();
  4561. }
  4562. this.pendingClip = null;
  4563. }
  4564. ctx.beginPath();
  4565. },
  4566. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4567. var inverse = this.ctx.mozCurrentTransformInverse;
  4568. // max of the current horizontal and vertical scale
  4569. return Math.sqrt(Math.max(
  4570. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4571. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4572. },
  4573. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4574. var transform = this.ctx.mozCurrentTransform;
  4575. return [
  4576. transform[0] * x + transform[2] * y + transform[4],
  4577. transform[1] * x + transform[3] * y + transform[5]
  4578. ];
  4579. }
  4580. };
  4581. for (var op in OPS) {
  4582. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4583. }
  4584. return CanvasGraphics;
  4585. })();
  4586. var WebGLUtils = (function WebGLUtilsClosure() {
  4587. function loadShader(gl, code, shaderType) {
  4588. var shader = gl.createShader(shaderType);
  4589. gl.shaderSource(shader, code);
  4590. gl.compileShader(shader);
  4591. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4592. if (!compiled) {
  4593. var errorMsg = gl.getShaderInfoLog(shader);
  4594. throw new Error('Error during shader compilation: ' + errorMsg);
  4595. }
  4596. return shader;
  4597. }
  4598. function createVertexShader(gl, code) {
  4599. return loadShader(gl, code, gl.VERTEX_SHADER);
  4600. }
  4601. function createFragmentShader(gl, code) {
  4602. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4603. }
  4604. function createProgram(gl, shaders) {
  4605. var program = gl.createProgram();
  4606. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4607. gl.attachShader(program, shaders[i]);
  4608. }
  4609. gl.linkProgram(program);
  4610. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4611. if (!linked) {
  4612. var errorMsg = gl.getProgramInfoLog(program);
  4613. throw new Error('Error during program linking: ' + errorMsg);
  4614. }
  4615. return program;
  4616. }
  4617. function createTexture(gl, image, textureId) {
  4618. gl.activeTexture(textureId);
  4619. var texture = gl.createTexture();
  4620. gl.bindTexture(gl.TEXTURE_2D, texture);
  4621. // Set the parameters so we can render any size image.
  4622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4626. // Upload the image into the texture.
  4627. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4628. return texture;
  4629. }
  4630. var currentGL, currentCanvas;
  4631. function generageGL() {
  4632. if (currentGL) {
  4633. return;
  4634. }
  4635. currentCanvas = document.createElement('canvas');
  4636. currentGL = currentCanvas.getContext('webgl',
  4637. { premultipliedalpha: false });
  4638. }
  4639. var smaskVertexShaderCode = '\
  4640. attribute vec2 a_position; \
  4641. attribute vec2 a_texCoord; \
  4642. \
  4643. uniform vec2 u_resolution; \
  4644. \
  4645. varying vec2 v_texCoord; \
  4646. \
  4647. void main() { \
  4648. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4649. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4650. \
  4651. v_texCoord = a_texCoord; \
  4652. } ';
  4653. var smaskFragmentShaderCode = '\
  4654. precision mediump float; \
  4655. \
  4656. uniform vec4 u_backdrop; \
  4657. uniform int u_subtype; \
  4658. uniform sampler2D u_image; \
  4659. uniform sampler2D u_mask; \
  4660. \
  4661. varying vec2 v_texCoord; \
  4662. \
  4663. void main() { \
  4664. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4665. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4666. if (u_backdrop.a > 0.0) { \
  4667. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4668. u_backdrop.rgb * (1.0 - maskColor.a); \
  4669. } \
  4670. float lum; \
  4671. if (u_subtype == 0) { \
  4672. lum = maskColor.a; \
  4673. } else { \
  4674. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4675. maskColor.b * 0.11; \
  4676. } \
  4677. imageColor.a *= lum; \
  4678. imageColor.rgb *= imageColor.a; \
  4679. gl_FragColor = imageColor; \
  4680. } ';
  4681. var smaskCache = null;
  4682. function initSmaskGL() {
  4683. var canvas, gl;
  4684. generageGL();
  4685. canvas = currentCanvas;
  4686. currentCanvas = null;
  4687. gl = currentGL;
  4688. currentGL = null;
  4689. // setup a GLSL program
  4690. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4691. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4692. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4693. gl.useProgram(program);
  4694. var cache = {};
  4695. cache.gl = gl;
  4696. cache.canvas = canvas;
  4697. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4698. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4699. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4700. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4701. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4702. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4703. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4704. // provide texture coordinates for the rectangle.
  4705. var texCoordBuffer = gl.createBuffer();
  4706. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4707. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4708. 0.0, 0.0,
  4709. 1.0, 0.0,
  4710. 0.0, 1.0,
  4711. 0.0, 1.0,
  4712. 1.0, 0.0,
  4713. 1.0, 1.0]), gl.STATIC_DRAW);
  4714. gl.enableVertexAttribArray(texCoordLocation);
  4715. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4716. gl.uniform1i(texLayerLocation, 0);
  4717. gl.uniform1i(texMaskLocation, 1);
  4718. smaskCache = cache;
  4719. }
  4720. function composeSMask(layer, mask, properties) {
  4721. var width = layer.width, height = layer.height;
  4722. if (!smaskCache) {
  4723. initSmaskGL();
  4724. }
  4725. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4726. canvas.width = width;
  4727. canvas.height = height;
  4728. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4729. gl.uniform2f(cache.resolutionLocation, width, height);
  4730. if (properties.backdrop) {
  4731. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4732. properties.backdrop[1], properties.backdrop[2], 1);
  4733. } else {
  4734. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4735. }
  4736. gl.uniform1i(cache.subtypeLocation,
  4737. properties.subtype === 'Luminosity' ? 1 : 0);
  4738. // Create a textures
  4739. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4740. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4741. // Create a buffer and put a single clipspace rectangle in
  4742. // it (2 triangles)
  4743. var buffer = gl.createBuffer();
  4744. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4745. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4746. 0, 0,
  4747. width, 0,
  4748. 0, height,
  4749. 0, height,
  4750. width, 0,
  4751. width, height]), gl.STATIC_DRAW);
  4752. gl.enableVertexAttribArray(cache.positionLocation);
  4753. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4754. // draw
  4755. gl.clearColor(0, 0, 0, 0);
  4756. gl.enable(gl.BLEND);
  4757. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4758. gl.clear(gl.COLOR_BUFFER_BIT);
  4759. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4760. gl.flush();
  4761. gl.deleteTexture(texture);
  4762. gl.deleteTexture(maskTexture);
  4763. gl.deleteBuffer(buffer);
  4764. return canvas;
  4765. }
  4766. var figuresVertexShaderCode = '\
  4767. attribute vec2 a_position; \
  4768. attribute vec3 a_color; \
  4769. \
  4770. uniform vec2 u_resolution; \
  4771. uniform vec2 u_scale; \
  4772. uniform vec2 u_offset; \
  4773. \
  4774. varying vec4 v_color; \
  4775. \
  4776. void main() { \
  4777. vec2 position = (a_position + u_offset) * u_scale; \
  4778. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4779. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4780. \
  4781. v_color = vec4(a_color / 255.0, 1.0); \
  4782. } ';
  4783. var figuresFragmentShaderCode = '\
  4784. precision mediump float; \
  4785. \
  4786. varying vec4 v_color; \
  4787. \
  4788. void main() { \
  4789. gl_FragColor = v_color; \
  4790. } ';
  4791. var figuresCache = null;
  4792. function initFiguresGL() {
  4793. var canvas, gl;
  4794. generageGL();
  4795. canvas = currentCanvas;
  4796. currentCanvas = null;
  4797. gl = currentGL;
  4798. currentGL = null;
  4799. // setup a GLSL program
  4800. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  4801. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  4802. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4803. gl.useProgram(program);
  4804. var cache = {};
  4805. cache.gl = gl;
  4806. cache.canvas = canvas;
  4807. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4808. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  4809. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  4810. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4811. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  4812. figuresCache = cache;
  4813. }
  4814. function drawFigures(width, height, backgroundColor, figures, context) {
  4815. if (!figuresCache) {
  4816. initFiguresGL();
  4817. }
  4818. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  4819. canvas.width = width;
  4820. canvas.height = height;
  4821. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4822. gl.uniform2f(cache.resolutionLocation, width, height);
  4823. // count triangle points
  4824. var count = 0;
  4825. var i, ii, rows;
  4826. for (i = 0, ii = figures.length; i < ii; i++) {
  4827. switch (figures[i].type) {
  4828. case 'lattice':
  4829. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  4830. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  4831. break;
  4832. case 'triangles':
  4833. count += figures[i].coords.length;
  4834. break;
  4835. }
  4836. }
  4837. // transfer data
  4838. var coords = new Float32Array(count * 2);
  4839. var colors = new Uint8Array(count * 3);
  4840. var coordsMap = context.coords, colorsMap = context.colors;
  4841. var pIndex = 0, cIndex = 0;
  4842. for (i = 0, ii = figures.length; i < ii; i++) {
  4843. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  4844. switch (figure.type) {
  4845. case 'lattice':
  4846. var cols = figure.verticesPerRow;
  4847. rows = (ps.length / cols) | 0;
  4848. for (var row = 1; row < rows; row++) {
  4849. var offset = row * cols + 1;
  4850. for (var col = 1; col < cols; col++, offset++) {
  4851. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  4852. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  4853. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  4854. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  4855. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  4856. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  4857. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  4858. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  4859. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  4860. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  4861. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  4862. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  4863. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  4864. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  4865. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  4866. coords[pIndex + 6] = coords[pIndex + 2];
  4867. coords[pIndex + 7] = coords[pIndex + 3];
  4868. coords[pIndex + 8] = coords[pIndex + 4];
  4869. coords[pIndex + 9] = coords[pIndex + 5];
  4870. coords[pIndex + 10] = coordsMap[ps[offset]];
  4871. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  4872. colors[cIndex + 9] = colors[cIndex + 3];
  4873. colors[cIndex + 10] = colors[cIndex + 4];
  4874. colors[cIndex + 11] = colors[cIndex + 5];
  4875. colors[cIndex + 12] = colors[cIndex + 6];
  4876. colors[cIndex + 13] = colors[cIndex + 7];
  4877. colors[cIndex + 14] = colors[cIndex + 8];
  4878. colors[cIndex + 15] = colorsMap[cs[offset]];
  4879. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  4880. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  4881. pIndex += 12;
  4882. cIndex += 18;
  4883. }
  4884. }
  4885. break;
  4886. case 'triangles':
  4887. for (var j = 0, jj = ps.length; j < jj; j++) {
  4888. coords[pIndex] = coordsMap[ps[j]];
  4889. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  4890. colors[cIndex] = colorsMap[cs[i]];
  4891. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  4892. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  4893. pIndex += 2;
  4894. cIndex += 3;
  4895. }
  4896. break;
  4897. }
  4898. }
  4899. // draw
  4900. if (backgroundColor) {
  4901. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  4902. backgroundColor[2] / 255, 1.0);
  4903. } else {
  4904. gl.clearColor(0, 0, 0, 0);
  4905. }
  4906. gl.clear(gl.COLOR_BUFFER_BIT);
  4907. var coordsBuffer = gl.createBuffer();
  4908. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  4909. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  4910. gl.enableVertexAttribArray(cache.positionLocation);
  4911. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4912. var colorsBuffer = gl.createBuffer();
  4913. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  4914. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  4915. gl.enableVertexAttribArray(cache.colorLocation);
  4916. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  4917. 0, 0);
  4918. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  4919. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  4920. gl.drawArrays(gl.TRIANGLES, 0, count);
  4921. gl.flush();
  4922. gl.deleteBuffer(coordsBuffer);
  4923. gl.deleteBuffer(colorsBuffer);
  4924. return canvas;
  4925. }
  4926. function cleanup() {
  4927. smaskCache = null;
  4928. figuresCache = null;
  4929. }
  4930. return {
  4931. get isEnabled() {
  4932. if (PDFJS.disableWebGL) {
  4933. return false;
  4934. }
  4935. var enabled = false;
  4936. try {
  4937. generageGL();
  4938. enabled = !!currentGL;
  4939. } catch (e) { }
  4940. return shadow(this, 'isEnabled', enabled);
  4941. },
  4942. composeSMask: composeSMask,
  4943. drawFigures: drawFigures,
  4944. clear: cleanup
  4945. };
  4946. })();
  4947. var ShadingIRs = {};
  4948. ShadingIRs.RadialAxial = {
  4949. fromIR: function RadialAxial_fromIR(raw) {
  4950. var type = raw[1];
  4951. var colorStops = raw[2];
  4952. var p0 = raw[3];
  4953. var p1 = raw[4];
  4954. var r0 = raw[5];
  4955. var r1 = raw[6];
  4956. return {
  4957. type: 'Pattern',
  4958. getPattern: function RadialAxial_getPattern(ctx) {
  4959. var grad;
  4960. if (type === 'axial') {
  4961. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  4962. } else if (type === 'radial') {
  4963. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  4964. }
  4965. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  4966. var c = colorStops[i];
  4967. grad.addColorStop(c[0], c[1]);
  4968. }
  4969. return grad;
  4970. }
  4971. };
  4972. }
  4973. };
  4974. var createMeshCanvas = (function createMeshCanvasClosure() {
  4975. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  4976. // Very basic Gouraud-shaded triangle rasterization algorithm.
  4977. var coords = context.coords, colors = context.colors;
  4978. var bytes = data.data, rowSize = data.width * 4;
  4979. var tmp;
  4980. if (coords[p1 + 1] > coords[p2 + 1]) {
  4981. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  4982. }
  4983. if (coords[p2 + 1] > coords[p3 + 1]) {
  4984. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  4985. }
  4986. if (coords[p1 + 1] > coords[p2 + 1]) {
  4987. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  4988. }
  4989. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  4990. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  4991. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  4992. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  4993. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  4994. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  4995. if (y1 >= y3) {
  4996. return;
  4997. }
  4998. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  4999. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5000. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5001. var minY = Math.round(y1), maxY = Math.round(y3);
  5002. var xa, car, cag, cab;
  5003. var xb, cbr, cbg, cbb;
  5004. var k;
  5005. for (var y = minY; y <= maxY; y++) {
  5006. if (y < y2) {
  5007. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5008. xa = x1 - (x1 - x2) * k;
  5009. car = c1r - (c1r - c2r) * k;
  5010. cag = c1g - (c1g - c2g) * k;
  5011. cab = c1b - (c1b - c2b) * k;
  5012. } else {
  5013. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5014. xa = x2 - (x2 - x3) * k;
  5015. car = c2r - (c2r - c3r) * k;
  5016. cag = c2g - (c2g - c3g) * k;
  5017. cab = c2b - (c2b - c3b) * k;
  5018. }
  5019. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5020. xb = x1 - (x1 - x3) * k;
  5021. cbr = c1r - (c1r - c3r) * k;
  5022. cbg = c1g - (c1g - c3g) * k;
  5023. cbb = c1b - (c1b - c3b) * k;
  5024. var x1_ = Math.round(Math.min(xa, xb));
  5025. var x2_ = Math.round(Math.max(xa, xb));
  5026. var j = rowSize * y + x1_ * 4;
  5027. for (var x = x1_; x <= x2_; x++) {
  5028. k = (xa - x) / (xa - xb);
  5029. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5030. bytes[j++] = (car - (car - cbr) * k) | 0;
  5031. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5032. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5033. bytes[j++] = 255;
  5034. }
  5035. }
  5036. }
  5037. function drawFigure(data, figure, context) {
  5038. var ps = figure.coords;
  5039. var cs = figure.colors;
  5040. var i, ii;
  5041. switch (figure.type) {
  5042. case 'lattice':
  5043. var verticesPerRow = figure.verticesPerRow;
  5044. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5045. var cols = verticesPerRow - 1;
  5046. for (i = 0; i < rows; i++) {
  5047. var q = i * verticesPerRow;
  5048. for (var j = 0; j < cols; j++, q++) {
  5049. drawTriangle(data, context,
  5050. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5051. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5052. drawTriangle(data, context,
  5053. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5054. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5055. }
  5056. }
  5057. break;
  5058. case 'triangles':
  5059. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5060. drawTriangle(data, context,
  5061. ps[i], ps[i + 1], ps[i + 2],
  5062. cs[i], cs[i + 1], cs[i + 2]);
  5063. }
  5064. break;
  5065. default:
  5066. error('illigal figure');
  5067. break;
  5068. }
  5069. }
  5070. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5071. backgroundColor) {
  5072. // we will increase scale on some weird factor to let antialiasing take
  5073. // care of "rough" edges
  5074. var EXPECTED_SCALE = 1.1;
  5075. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5076. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5077. var offsetX = Math.floor(bounds[0]);
  5078. var offsetY = Math.floor(bounds[1]);
  5079. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5080. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5081. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5082. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5083. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5084. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5085. var scaleX = boundsWidth / width;
  5086. var scaleY = boundsHeight / height;
  5087. var context = {
  5088. coords: coords,
  5089. colors: colors,
  5090. offsetX: -offsetX,
  5091. offsetY: -offsetY,
  5092. scaleX: 1 / scaleX,
  5093. scaleY: 1 / scaleY
  5094. };
  5095. var canvas, tmpCanvas, i, ii;
  5096. if (WebGLUtils.isEnabled) {
  5097. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5098. figures, context);
  5099. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5100. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5101. tmpCanvas.context.drawImage(canvas, 0, 0);
  5102. canvas = tmpCanvas.canvas;
  5103. } else {
  5104. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5105. var tmpCtx = tmpCanvas.context;
  5106. var data = tmpCtx.createImageData(width, height);
  5107. if (backgroundColor) {
  5108. var bytes = data.data;
  5109. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5110. bytes[i] = backgroundColor[0];
  5111. bytes[i + 1] = backgroundColor[1];
  5112. bytes[i + 2] = backgroundColor[2];
  5113. bytes[i + 3] = 255;
  5114. }
  5115. }
  5116. for (i = 0; i < figures.length; i++) {
  5117. drawFigure(data, figures[i], context);
  5118. }
  5119. tmpCtx.putImageData(data, 0, 0);
  5120. canvas = tmpCanvas.canvas;
  5121. }
  5122. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5123. scaleX: scaleX, scaleY: scaleY};
  5124. }
  5125. return createMeshCanvas;
  5126. })();
  5127. ShadingIRs.Mesh = {
  5128. fromIR: function Mesh_fromIR(raw) {
  5129. //var type = raw[1];
  5130. var coords = raw[2];
  5131. var colors = raw[3];
  5132. var figures = raw[4];
  5133. var bounds = raw[5];
  5134. var matrix = raw[6];
  5135. //var bbox = raw[7];
  5136. var background = raw[8];
  5137. return {
  5138. type: 'Pattern',
  5139. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5140. var combinedScale;
  5141. // Obtain scale from matrix and current transformation matrix.
  5142. if (shadingFill) {
  5143. combinedScale = Util.singularValueDecompose2dScale(
  5144. ctx.mozCurrentTransform);
  5145. } else {
  5146. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5147. var curMatrixScale = Util.singularValueDecompose2dScale(
  5148. owner.baseTransform);
  5149. combinedScale = [matrixScale[0] * curMatrixScale[0],
  5150. matrixScale[1] * curMatrixScale[1]];
  5151. }
  5152. // Rasterizing on the main thread since sending/queue large canvases
  5153. // might cause OOM.
  5154. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  5155. coords, colors, figures, shadingFill ? null : background);
  5156. if (!shadingFill) {
  5157. ctx.setTransform.apply(ctx, owner.baseTransform);
  5158. if (matrix) {
  5159. ctx.transform.apply(ctx, matrix);
  5160. }
  5161. }
  5162. ctx.translate(temporaryPatternCanvas.offsetX,
  5163. temporaryPatternCanvas.offsetY);
  5164. ctx.scale(temporaryPatternCanvas.scaleX,
  5165. temporaryPatternCanvas.scaleY);
  5166. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5167. }
  5168. };
  5169. }
  5170. };
  5171. ShadingIRs.Dummy = {
  5172. fromIR: function Dummy_fromIR() {
  5173. return {
  5174. type: 'Pattern',
  5175. getPattern: function Dummy_fromIR_getPattern() {
  5176. return 'hotpink';
  5177. }
  5178. };
  5179. }
  5180. };
  5181. function getShadingPatternFromIR(raw) {
  5182. var shadingIR = ShadingIRs[raw[0]];
  5183. if (!shadingIR) {
  5184. error('Unknown IR type: ' + raw[0]);
  5185. }
  5186. return shadingIR.fromIR(raw);
  5187. }
  5188. var TilingPattern = (function TilingPatternClosure() {
  5189. var PaintType = {
  5190. COLORED: 1,
  5191. UNCOLORED: 2
  5192. };
  5193. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5194. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5195. this.operatorList = IR[2];
  5196. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5197. this.bbox = IR[4];
  5198. this.xstep = IR[5];
  5199. this.ystep = IR[6];
  5200. this.paintType = IR[7];
  5201. this.tilingType = IR[8];
  5202. this.color = color;
  5203. this.objs = objs;
  5204. this.commonObjs = commonObjs;
  5205. this.baseTransform = baseTransform;
  5206. this.type = 'Pattern';
  5207. this.ctx = ctx;
  5208. }
  5209. TilingPattern.prototype = {
  5210. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5211. var operatorList = this.operatorList;
  5212. var bbox = this.bbox;
  5213. var xstep = this.xstep;
  5214. var ystep = this.ystep;
  5215. var paintType = this.paintType;
  5216. var tilingType = this.tilingType;
  5217. var color = this.color;
  5218. var objs = this.objs;
  5219. var commonObjs = this.commonObjs;
  5220. info('TilingType: ' + tilingType);
  5221. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5222. var topLeft = [x0, y0];
  5223. // we want the canvas to be as large as the step size
  5224. var botRight = [x0 + xstep, y0 + ystep];
  5225. var width = botRight[0] - topLeft[0];
  5226. var height = botRight[1] - topLeft[1];
  5227. // Obtain scale from matrix and current transformation matrix.
  5228. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5229. var curMatrixScale = Util.singularValueDecompose2dScale(
  5230. this.baseTransform);
  5231. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5232. matrixScale[1] * curMatrixScale[1]];
  5233. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5234. // Use width and height values that are as close as possible to the end
  5235. // result when the pattern is used. Too low value makes the pattern look
  5236. // blurry. Too large value makes it look too crispy.
  5237. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5238. MAX_PATTERN_SIZE);
  5239. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5240. MAX_PATTERN_SIZE);
  5241. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5242. var tmpCtx = tmpCanvas.context;
  5243. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5244. graphics.groupLevel = owner.groupLevel;
  5245. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5246. this.setScale(width, height, xstep, ystep);
  5247. this.transformToScale(graphics);
  5248. // transform coordinates to pattern space
  5249. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5250. graphics.transform.apply(graphics, tmpTranslate);
  5251. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5252. graphics.executeOperatorList(operatorList);
  5253. return tmpCanvas.canvas;
  5254. },
  5255. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5256. this.scale = [width / xstep, height / ystep];
  5257. },
  5258. transformToScale: function TilingPattern_transformToScale(graphics) {
  5259. var scale = this.scale;
  5260. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5261. graphics.transform.apply(graphics, tmpScale);
  5262. },
  5263. scaleToContext: function TilingPattern_scaleToContext() {
  5264. var scale = this.scale;
  5265. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5266. },
  5267. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5268. if (bbox && isArray(bbox) && 4 == bbox.length) {
  5269. var bboxWidth = x1 - x0;
  5270. var bboxHeight = y1 - y0;
  5271. graphics.rectangle(x0, y0, bboxWidth, bboxHeight);
  5272. graphics.clip();
  5273. graphics.endPath();
  5274. }
  5275. },
  5276. setFillAndStrokeStyleToContext:
  5277. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5278. switch (paintType) {
  5279. case PaintType.COLORED:
  5280. var ctx = this.ctx;
  5281. context.fillStyle = ctx.fillStyle;
  5282. context.strokeStyle = ctx.strokeStyle;
  5283. break;
  5284. case PaintType.UNCOLORED:
  5285. var cssColor = Util.makeCssRgb(color);
  5286. context.fillStyle = cssColor;
  5287. context.strokeStyle = cssColor;
  5288. break;
  5289. default:
  5290. error('Unsupported paint type: ' + paintType);
  5291. }
  5292. },
  5293. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5294. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5295. ctx = this.ctx;
  5296. ctx.setTransform.apply(ctx, this.baseTransform);
  5297. ctx.transform.apply(ctx, this.matrix);
  5298. this.scaleToContext();
  5299. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5300. }
  5301. };
  5302. return TilingPattern;
  5303. })();
  5304. PDFJS.disableFontFace = false;
  5305. var FontLoader = {
  5306. insertRule: function fontLoaderInsertRule(rule) {
  5307. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5308. if (!styleElement) {
  5309. styleElement = document.createElement('style');
  5310. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5311. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5312. styleElement);
  5313. }
  5314. var styleSheet = styleElement.sheet;
  5315. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5316. },
  5317. clear: function fontLoaderClear() {
  5318. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5319. if (styleElement) {
  5320. styleElement.parentNode.removeChild(styleElement);
  5321. }
  5322. },
  5323. get loadTestFont() {
  5324. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5325. // height.
  5326. return shadow(this, 'loadTestFont', atob(
  5327. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5328. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5329. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5330. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5331. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5332. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5333. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5334. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5335. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5336. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5337. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5338. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5339. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5340. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5341. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5342. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5343. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5344. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5345. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5346. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5347. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5348. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5349. ));
  5350. },
  5351. loadTestFontId: 0,
  5352. loadingContext: {
  5353. requests: [],
  5354. nextRequestId: 0
  5355. },
  5356. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5357. if (isWorker) {
  5358. return false;
  5359. }
  5360. // User agent string sniffing is bad, but there is no reliable way to tell
  5361. // if font is fully loaded and ready to be used with canvas.
  5362. var userAgent = window.navigator.userAgent;
  5363. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5364. if (m && m[1] >= 14) {
  5365. return true;
  5366. }
  5367. // TODO other browsers
  5368. return false;
  5369. })(),
  5370. bind: function fontLoaderBind(fonts, callback) {
  5371. assert(!isWorker, 'bind() shall be called from main thread');
  5372. var rules = [], fontsToLoad = [];
  5373. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5374. var font = fonts[i];
  5375. // Add the font to the DOM only once or skip if the font
  5376. // is already loaded.
  5377. if (font.attached || font.loading === false) {
  5378. continue;
  5379. }
  5380. font.attached = true;
  5381. var rule = font.bindDOM();
  5382. if (rule) {
  5383. rules.push(rule);
  5384. fontsToLoad.push(font);
  5385. }
  5386. }
  5387. var request = FontLoader.queueLoadingCallback(callback);
  5388. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5389. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5390. } else {
  5391. request.complete();
  5392. }
  5393. },
  5394. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5395. function LoadLoader_completeRequest() {
  5396. assert(!request.end, 'completeRequest() cannot be called twice');
  5397. request.end = Date.now();
  5398. // sending all completed requests in order how they were queued
  5399. while (context.requests.length > 0 && context.requests[0].end) {
  5400. var otherRequest = context.requests.shift();
  5401. setTimeout(otherRequest.callback, 0);
  5402. }
  5403. }
  5404. var context = FontLoader.loadingContext;
  5405. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5406. var request = {
  5407. id: requestId,
  5408. complete: LoadLoader_completeRequest,
  5409. callback: callback,
  5410. started: Date.now()
  5411. };
  5412. context.requests.push(request);
  5413. return request;
  5414. },
  5415. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5416. fonts,
  5417. request) {
  5418. /** Hack begin */
  5419. // There's currently no event when a font has finished downloading so the
  5420. // following code is a dirty hack to 'guess' when a font is
  5421. // ready. It's assumed fonts are loaded in order, so add a known test
  5422. // font after the desired fonts and then test for the loading of that
  5423. // test font.
  5424. function int32(data, offset) {
  5425. return (data.charCodeAt(offset) << 24) |
  5426. (data.charCodeAt(offset + 1) << 16) |
  5427. (data.charCodeAt(offset + 2) << 8) |
  5428. (data.charCodeAt(offset + 3) & 0xff);
  5429. }
  5430. function spliceString(s, offset, remove, insert) {
  5431. var chunk1 = s.substr(0, offset);
  5432. var chunk2 = s.substr(offset + remove);
  5433. return chunk1 + insert + chunk2;
  5434. }
  5435. var i, ii;
  5436. var canvas = document.createElement('canvas');
  5437. canvas.width = 1;
  5438. canvas.height = 1;
  5439. var ctx = canvas.getContext('2d');
  5440. var called = 0;
  5441. function isFontReady(name, callback) {
  5442. called++;
  5443. // With setTimeout clamping this gives the font ~100ms to load.
  5444. if(called > 30) {
  5445. warn('Load test font never loaded.');
  5446. callback();
  5447. return;
  5448. }
  5449. ctx.font = '30px ' + name;
  5450. ctx.fillText('.', 0, 20);
  5451. var imageData = ctx.getImageData(0, 0, 1, 1);
  5452. if (imageData.data[3] > 0) {
  5453. callback();
  5454. return;
  5455. }
  5456. setTimeout(isFontReady.bind(null, name, callback));
  5457. }
  5458. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5459. // Chromium seems to cache fonts based on a hash of the actual font data,
  5460. // so the font must be modified for each load test else it will appear to
  5461. // be loaded already.
  5462. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5463. // font by splitting it in chunks before hand and padding the font id.
  5464. var data = this.loadTestFont;
  5465. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5466. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5467. loadTestFontId);
  5468. // CFF checksum is important for IE, adjusting it
  5469. var CFF_CHECKSUM_OFFSET = 16;
  5470. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5471. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5472. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5473. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5474. }
  5475. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5476. checksum = (checksum - XXXX_VALUE +
  5477. int32(loadTestFontId + 'XXX', i)) | 0;
  5478. }
  5479. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5480. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5481. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5482. url + '}';
  5483. FontLoader.insertRule(rule);
  5484. var names = [];
  5485. for (i = 0, ii = fonts.length; i < ii; i++) {
  5486. names.push(fonts[i].loadedName);
  5487. }
  5488. names.push(loadTestFontId);
  5489. var div = document.createElement('div');
  5490. div.setAttribute('style',
  5491. 'visibility: hidden;' +
  5492. 'width: 10px; height: 10px;' +
  5493. 'position: absolute; top: 0px; left: 0px;');
  5494. for (i = 0, ii = names.length; i < ii; ++i) {
  5495. var span = document.createElement('span');
  5496. span.textContent = 'Hi';
  5497. span.style.fontFamily = names[i];
  5498. div.appendChild(span);
  5499. }
  5500. document.body.appendChild(div);
  5501. isFontReady(loadTestFontId, function() {
  5502. document.body.removeChild(div);
  5503. request.complete();
  5504. });
  5505. /** Hack end */
  5506. }
  5507. };
  5508. var FontFace = (function FontFaceClosure() {
  5509. function FontFace(name, file, properties) {
  5510. this.compiledGlyphs = {};
  5511. if (arguments.length === 1) {
  5512. // importing translated data
  5513. var data = arguments[0];
  5514. for (var i in data) {
  5515. this[i] = data[i];
  5516. }
  5517. return;
  5518. }
  5519. }
  5520. FontFace.prototype = {
  5521. bindDOM: function FontFace_bindDOM() {
  5522. if (!this.data) {
  5523. return null;
  5524. }
  5525. if (PDFJS.disableFontFace) {
  5526. this.disableFontFace = true;
  5527. return null;
  5528. }
  5529. var data = bytesToString(new Uint8Array(this.data));
  5530. var fontName = this.loadedName;
  5531. // Add the font-face rule to the document
  5532. var url = ('url(data:' + this.mimetype + ';base64,' +
  5533. window.btoa(data) + ');');
  5534. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5535. FontLoader.insertRule(rule);
  5536. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5537. globalScope['FontInspector'].enabled) {
  5538. globalScope['FontInspector'].fontAdded(this, url);
  5539. }
  5540. return rule;
  5541. },
  5542. getPathGenerator: function (objs, character) {
  5543. if (!(character in this.compiledGlyphs)) {
  5544. var js = objs.get(this.loadedName + '_path_' + character);
  5545. /*jshint -W054 */
  5546. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5547. }
  5548. return this.compiledGlyphs[character];
  5549. }
  5550. };
  5551. return FontFace;
  5552. })();
  5553. var HIGHLIGHT_OFFSET = 4; // px
  5554. var ANNOT_MIN_SIZE = 10; // px
  5555. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5556. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5557. function setTextStyles(element, item, fontObj) {
  5558. var style = element.style;
  5559. style.fontSize = item.fontSize + 'px';
  5560. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5561. if (!fontObj) {
  5562. return;
  5563. }
  5564. style.fontWeight = fontObj.black ?
  5565. (fontObj.bold ? 'bolder' : 'bold') :
  5566. (fontObj.bold ? 'bold' : 'normal');
  5567. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5568. var fontName = fontObj.loadedName;
  5569. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5570. // Use a reasonable default font if the font doesn't specify a fallback
  5571. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5572. style.fontFamily = fontFamily + fallbackName;
  5573. }
  5574. // TODO(mack): Remove this, it's not really that helpful.
  5575. function getEmptyContainer(tagName, rect, borderWidth) {
  5576. var bWidth = borderWidth || 0;
  5577. var element = document.createElement(tagName);
  5578. element.style.borderWidth = bWidth + 'px';
  5579. var width = rect[2] - rect[0] - 2 * bWidth;
  5580. var height = rect[3] - rect[1] - 2 * bWidth;
  5581. element.style.width = width + 'px';
  5582. element.style.height = height + 'px';
  5583. return element;
  5584. }
  5585. function initContainer(item) {
  5586. var container = getEmptyContainer('section', item.rect, item.borderWidth);
  5587. container.style.backgroundColor = item.color;
  5588. var color = item.color;
  5589. var rgb = [];
  5590. for (var i = 0; i < 3; ++i) {
  5591. rgb[i] = Math.round(color[i] * 255);
  5592. }
  5593. item.colorCssRgb = Util.makeCssRgb(rgb);
  5594. var highlight = document.createElement('div');
  5595. highlight.className = 'annotationHighlight';
  5596. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  5597. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  5598. highlight.setAttribute('hidden', true);
  5599. item.highlightElement = highlight;
  5600. container.appendChild(item.highlightElement);
  5601. return container;
  5602. }
  5603. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5604. var element = getEmptyContainer('div', item.rect, 0);
  5605. element.style.display = 'table';
  5606. var content = document.createElement('div');
  5607. content.textContent = item.fieldValue;
  5608. var textAlignment = item.textAlignment;
  5609. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5610. content.style.verticalAlign = 'middle';
  5611. content.style.display = 'table-cell';
  5612. var fontObj = item.fontRefName ?
  5613. commonObjs.getData(item.fontRefName) : null;
  5614. setTextStyles(content, item, fontObj);
  5615. element.appendChild(content);
  5616. return element;
  5617. }
  5618. function getHtmlElementForTextAnnotation(item, commonObjs) {
  5619. var rect = item.rect;
  5620. // sanity check because of OOo-generated PDFs
  5621. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5622. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5623. }
  5624. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5625. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5626. }
  5627. var container = initContainer(item);
  5628. container.className = 'annotText';
  5629. var image = document.createElement('img');
  5630. image.style.height = container.style.height;
  5631. image.style.width = container.style.width;
  5632. var iconName = item.name;
  5633. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5634. iconName.toLowerCase() + '.svg';
  5635. image.alt = '[{{type}} Annotation]';
  5636. image.dataset.l10nId = 'text_annotation_type';
  5637. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5638. var contentWrapper = document.createElement('div');
  5639. contentWrapper.className = 'annotTextContentWrapper';
  5640. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5641. contentWrapper.style.top = '-10px';
  5642. var content = document.createElement('div');
  5643. content.className = 'annotTextContent';
  5644. content.setAttribute('hidden', true);
  5645. var i, ii;
  5646. if (item.hasBgColor) {
  5647. var color = item.color;
  5648. var rgb = [];
  5649. for (i = 0; i < 3; ++i) {
  5650. // Enlighten the color (70%)
  5651. var c = Math.round(color[i] * 255);
  5652. rgb[i] = Math.round((255 - c) * 0.7) + c;
  5653. }
  5654. content.style.backgroundColor = Util.makeCssRgb(rgb);
  5655. }
  5656. var title = document.createElement('h1');
  5657. var text = document.createElement('p');
  5658. title.textContent = item.title;
  5659. if (!item.content && !item.title) {
  5660. content.setAttribute('hidden', true);
  5661. } else {
  5662. var e = document.createElement('span');
  5663. var lines = item.content.split(/(?:\r\n?|\n)/);
  5664. for (i = 0, ii = lines.length; i < ii; ++i) {
  5665. var line = lines[i];
  5666. e.appendChild(document.createTextNode(line));
  5667. if (i < (ii - 1)) {
  5668. e.appendChild(document.createElement('br'));
  5669. }
  5670. }
  5671. text.appendChild(e);
  5672. var pinned = false;
  5673. var showAnnotation = function showAnnotation(pin) {
  5674. if (pin) {
  5675. pinned = true;
  5676. }
  5677. if (content.hasAttribute('hidden')) {
  5678. container.style.zIndex += 1;
  5679. content.removeAttribute('hidden');
  5680. }
  5681. };
  5682. var hideAnnotation = function hideAnnotation(unpin) {
  5683. if (unpin) {
  5684. pinned = false;
  5685. }
  5686. if (!content.hasAttribute('hidden') && !pinned) {
  5687. container.style.zIndex -= 1;
  5688. content.setAttribute('hidden', true);
  5689. }
  5690. };
  5691. var toggleAnnotation = function toggleAnnotation() {
  5692. if (pinned) {
  5693. hideAnnotation(true);
  5694. } else {
  5695. showAnnotation(true);
  5696. }
  5697. };
  5698. image.addEventListener('click', function image_clickHandler() {
  5699. toggleAnnotation();
  5700. }, false);
  5701. image.addEventListener('mouseover', function image_mouseOverHandler() {
  5702. showAnnotation();
  5703. }, false);
  5704. image.addEventListener('mouseout', function image_mouseOutHandler() {
  5705. hideAnnotation();
  5706. }, false);
  5707. content.addEventListener('click', function content_clickHandler() {
  5708. hideAnnotation(true);
  5709. }, false);
  5710. }
  5711. content.appendChild(title);
  5712. content.appendChild(text);
  5713. contentWrapper.appendChild(content);
  5714. container.appendChild(image);
  5715. container.appendChild(contentWrapper);
  5716. return container;
  5717. }
  5718. function getHtmlElementForLinkAnnotation(item, commonObjs) {
  5719. var container = initContainer(item);
  5720. container.className = 'annotLink';
  5721. container.style.borderColor = item.colorCssRgb;
  5722. container.style.borderStyle = 'solid';
  5723. var link = document.createElement('a');
  5724. link.href = link.title = item.url || '';
  5725. container.appendChild(link);
  5726. return container;
  5727. }
  5728. function getHtmlElement(data, objs) {
  5729. switch (data.annotationType) {
  5730. case AnnotationType.WIDGET:
  5731. return getHtmlElementForTextWidgetAnnotation(data, objs);
  5732. case AnnotationType.TEXT:
  5733. return getHtmlElementForTextAnnotation(data, objs);
  5734. case AnnotationType.LINK:
  5735. return getHtmlElementForLinkAnnotation(data, objs);
  5736. default:
  5737. throw new Error('Unsupported annotationType: ' + data.annotationType);
  5738. }
  5739. }
  5740. return {
  5741. getHtmlElement: getHtmlElement
  5742. };
  5743. })();
  5744. }).call((typeof window === 'undefined') ? this : window);
  5745. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  5746. // workerSrc is not set -- using last script url to define default location
  5747. PDFJS.workerSrc = (function () {
  5748. 'use strict';
  5749. var scriptTagContainer = document.body ||
  5750. document.getElementsByTagName('head')[0];
  5751. var pdfjsSrc = scriptTagContainer.lastChild.src;
  5752. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  5753. })();
  5754. }