pdf.js 280 KB

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