pdf.js 308 KB

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