pdf.js 300 KB

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