pdf.js 300 KB

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