pdf.js 281 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847
  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.78';
  22. PDFJS.build = 'f93a220';
  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, transferMap) {
  3900. var length = maskData.length;
  3901. var scale = 1 / 255;
  3902. for (var i = 3; i < length; i += 4) {
  3903. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  3904. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3905. }
  3906. }
  3907. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  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] = transferMap ?
  3914. (layerData[i] * transferMap[y >> 8]) >> 8 :
  3915. (layerData[i] * y) >> 16;
  3916. }
  3917. }
  3918. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3919. subtype, backdrop, transferMap) {
  3920. var hasBackdrop = !!backdrop;
  3921. var r0 = hasBackdrop ? backdrop[0] : 0;
  3922. var g0 = hasBackdrop ? backdrop[1] : 0;
  3923. var b0 = hasBackdrop ? backdrop[2] : 0;
  3924. var composeFn;
  3925. if (subtype === 'Luminosity') {
  3926. composeFn = composeSMaskLuminosity;
  3927. } else {
  3928. composeFn = composeSMaskAlpha;
  3929. }
  3930. // processing image in chunks to save memory
  3931. var PIXELS_TO_PROCESS = 1048576;
  3932. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3933. for (var row = 0; row < height; row += chunkSize) {
  3934. var chunkHeight = Math.min(chunkSize, height - row);
  3935. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3936. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3937. if (hasBackdrop) {
  3938. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3939. }
  3940. composeFn(maskData.data, layerData.data, transferMap);
  3941. maskCtx.putImageData(layerData, 0, row);
  3942. }
  3943. }
  3944. function composeSMask(ctx, smask, layerCtx) {
  3945. var mask = smask.canvas;
  3946. var maskCtx = smask.context;
  3947. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3948. smask.offsetX, smask.offsetY);
  3949. var backdrop = smask.backdrop || null;
  3950. if (!smask.transferMap && WebGLUtils.isEnabled) {
  3951. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3952. {subtype: smask.subtype, backdrop: backdrop});
  3953. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3954. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3955. return;
  3956. }
  3957. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3958. smask.subtype, backdrop, smask.transferMap);
  3959. ctx.drawImage(mask, 0, 0);
  3960. }
  3961. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3962. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3963. var NORMAL_CLIP = {};
  3964. var EO_CLIP = {};
  3965. CanvasGraphics.prototype = {
  3966. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  3967. transparency) {
  3968. // For pdfs that use blend modes we have to clear the canvas else certain
  3969. // blend modes can look wrong since we'd be blending with a white
  3970. // backdrop. The problem with a transparent backdrop though is we then
  3971. // don't get sub pixel anti aliasing on text, creating temporary
  3972. // transparent canvas when we have blend modes.
  3973. var width = this.ctx.canvas.width;
  3974. var height = this.ctx.canvas.height;
  3975. this.ctx.save();
  3976. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3977. this.ctx.fillRect(0, 0, width, height);
  3978. this.ctx.restore();
  3979. if (transparency) {
  3980. var transparentCanvas = this.cachedCanvases.getCanvas(
  3981. 'transparent', width, height, true);
  3982. this.compositeCtx = this.ctx;
  3983. this.transparentCanvas = transparentCanvas.canvas;
  3984. this.ctx = transparentCanvas.context;
  3985. this.ctx.save();
  3986. // The transform can be applied before rendering, transferring it to
  3987. // the new canvas.
  3988. this.ctx.transform.apply(this.ctx,
  3989. this.compositeCtx.mozCurrentTransform);
  3990. }
  3991. this.ctx.save();
  3992. if (transform) {
  3993. this.ctx.transform.apply(this.ctx, transform);
  3994. }
  3995. this.ctx.transform.apply(this.ctx, viewport.transform);
  3996. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3997. if (this.imageLayer) {
  3998. this.imageLayer.beginLayout();
  3999. }
  4000. },
  4001. executeOperatorList: function CanvasGraphics_executeOperatorList(
  4002. operatorList,
  4003. executionStartIdx, continueCallback,
  4004. stepper) {
  4005. var argsArray = operatorList.argsArray;
  4006. var fnArray = operatorList.fnArray;
  4007. var i = executionStartIdx || 0;
  4008. var argsArrayLen = argsArray.length;
  4009. // Sometimes the OperatorList to execute is empty.
  4010. if (argsArrayLen === i) {
  4011. return i;
  4012. }
  4013. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  4014. typeof continueCallback === 'function');
  4015. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  4016. var steps = 0;
  4017. var commonObjs = this.commonObjs;
  4018. var objs = this.objs;
  4019. var fnId;
  4020. while (true) {
  4021. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  4022. stepper.breakIt(i, continueCallback);
  4023. return i;
  4024. }
  4025. fnId = fnArray[i];
  4026. if (fnId !== OPS.dependency) {
  4027. this[fnId].apply(this, argsArray[i]);
  4028. } else {
  4029. var deps = argsArray[i];
  4030. for (var n = 0, nn = deps.length; n < nn; n++) {
  4031. var depObjId = deps[n];
  4032. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  4033. var objsPool = common ? commonObjs : objs;
  4034. // If the promise isn't resolved yet, add the continueCallback
  4035. // to the promise and bail out.
  4036. if (!objsPool.isResolved(depObjId)) {
  4037. objsPool.get(depObjId, continueCallback);
  4038. return i;
  4039. }
  4040. }
  4041. }
  4042. i++;
  4043. // If the entire operatorList was executed, stop as were done.
  4044. if (i === argsArrayLen) {
  4045. return i;
  4046. }
  4047. // If the execution took longer then a certain amount of time and
  4048. // `continueCallback` is specified, interrupt the execution.
  4049. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  4050. if (Date.now() > endTime) {
  4051. continueCallback();
  4052. return i;
  4053. }
  4054. steps = 0;
  4055. }
  4056. // If the operatorList isn't executed completely yet OR the execution
  4057. // time was short enough, do another execution round.
  4058. }
  4059. },
  4060. endDrawing: function CanvasGraphics_endDrawing() {
  4061. this.ctx.restore();
  4062. if (this.transparentCanvas) {
  4063. this.ctx = this.compositeCtx;
  4064. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  4065. this.transparentCanvas = null;
  4066. }
  4067. this.cachedCanvases.clear();
  4068. WebGLUtils.clear();
  4069. if (this.imageLayer) {
  4070. this.imageLayer.endLayout();
  4071. }
  4072. },
  4073. // Graphics state
  4074. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  4075. this.current.lineWidth = width;
  4076. this.ctx.lineWidth = width;
  4077. },
  4078. setLineCap: function CanvasGraphics_setLineCap(style) {
  4079. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4080. },
  4081. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  4082. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4083. },
  4084. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  4085. this.ctx.miterLimit = limit;
  4086. },
  4087. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  4088. var ctx = this.ctx;
  4089. if (ctx.setLineDash !== undefined) {
  4090. ctx.setLineDash(dashArray);
  4091. ctx.lineDashOffset = dashPhase;
  4092. } else {
  4093. ctx.mozDash = dashArray;
  4094. ctx.mozDashOffset = dashPhase;
  4095. }
  4096. },
  4097. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  4098. // Maybe if we one day fully support color spaces this will be important
  4099. // for now we can ignore.
  4100. // TODO set rendering intent?
  4101. },
  4102. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  4103. // There's no way to control this with canvas, but we can safely ignore.
  4104. // TODO set flatness?
  4105. },
  4106. setGState: function CanvasGraphics_setGState(states) {
  4107. for (var i = 0, ii = states.length; i < ii; i++) {
  4108. var state = states[i];
  4109. var key = state[0];
  4110. var value = state[1];
  4111. switch (key) {
  4112. case 'LW':
  4113. this.setLineWidth(value);
  4114. break;
  4115. case 'LC':
  4116. this.setLineCap(value);
  4117. break;
  4118. case 'LJ':
  4119. this.setLineJoin(value);
  4120. break;
  4121. case 'ML':
  4122. this.setMiterLimit(value);
  4123. break;
  4124. case 'D':
  4125. this.setDash(value[0], value[1]);
  4126. break;
  4127. case 'RI':
  4128. this.setRenderingIntent(value);
  4129. break;
  4130. case 'FL':
  4131. this.setFlatness(value);
  4132. break;
  4133. case 'Font':
  4134. this.setFont(value[0], value[1]);
  4135. break;
  4136. case 'CA':
  4137. this.current.strokeAlpha = state[1];
  4138. break;
  4139. case 'ca':
  4140. this.current.fillAlpha = state[1];
  4141. this.ctx.globalAlpha = state[1];
  4142. break;
  4143. case 'BM':
  4144. if (value && value.name && (value.name !== 'Normal')) {
  4145. var mode = value.name.replace(/([A-Z])/g,
  4146. function(c) {
  4147. return '-' + c.toLowerCase();
  4148. }
  4149. ).substring(1);
  4150. this.ctx.globalCompositeOperation = mode;
  4151. if (this.ctx.globalCompositeOperation !== mode) {
  4152. warn('globalCompositeOperation "' + mode +
  4153. '" is not supported');
  4154. }
  4155. } else {
  4156. this.ctx.globalCompositeOperation = 'source-over';
  4157. }
  4158. break;
  4159. case 'SMask':
  4160. if (this.current.activeSMask) {
  4161. this.endSMaskGroup();
  4162. }
  4163. this.current.activeSMask = value ? this.tempSMask : null;
  4164. if (this.current.activeSMask) {
  4165. this.beginSMaskGroup();
  4166. }
  4167. this.tempSMask = null;
  4168. break;
  4169. }
  4170. }
  4171. },
  4172. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  4173. var activeSMask = this.current.activeSMask;
  4174. var drawnWidth = activeSMask.canvas.width;
  4175. var drawnHeight = activeSMask.canvas.height;
  4176. var cacheId = 'smaskGroupAt' + this.groupLevel;
  4177. var scratchCanvas = this.cachedCanvases.getCanvas(
  4178. cacheId, drawnWidth, drawnHeight, true);
  4179. var currentCtx = this.ctx;
  4180. var currentTransform = currentCtx.mozCurrentTransform;
  4181. this.ctx.save();
  4182. var groupCtx = scratchCanvas.context;
  4183. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4184. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4185. groupCtx.transform.apply(groupCtx, currentTransform);
  4186. copyCtxState(currentCtx, groupCtx);
  4187. this.ctx = groupCtx;
  4188. this.setGState([
  4189. ['BM', 'Normal'],
  4190. ['ca', 1],
  4191. ['CA', 1]
  4192. ]);
  4193. this.groupStack.push(currentCtx);
  4194. this.groupLevel++;
  4195. },
  4196. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  4197. var groupCtx = this.ctx;
  4198. this.groupLevel--;
  4199. this.ctx = this.groupStack.pop();
  4200. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4201. this.ctx.restore();
  4202. copyCtxState(groupCtx, this.ctx);
  4203. },
  4204. save: function CanvasGraphics_save() {
  4205. this.ctx.save();
  4206. var old = this.current;
  4207. this.stateStack.push(old);
  4208. this.current = old.clone();
  4209. this.current.activeSMask = null;
  4210. },
  4211. restore: function CanvasGraphics_restore() {
  4212. if (this.stateStack.length !== 0) {
  4213. if (this.current.activeSMask !== null) {
  4214. this.endSMaskGroup();
  4215. }
  4216. this.current = this.stateStack.pop();
  4217. this.ctx.restore();
  4218. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  4219. this.pendingClip = null;
  4220. this.cachedGetSinglePixelWidth = null;
  4221. }
  4222. },
  4223. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  4224. this.ctx.transform(a, b, c, d, e, f);
  4225. this.cachedGetSinglePixelWidth = null;
  4226. },
  4227. // Path
  4228. constructPath: function CanvasGraphics_constructPath(ops, args) {
  4229. var ctx = this.ctx;
  4230. var current = this.current;
  4231. var x = current.x, y = current.y;
  4232. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4233. switch (ops[i] | 0) {
  4234. case OPS.rectangle:
  4235. x = args[j++];
  4236. y = args[j++];
  4237. var width = args[j++];
  4238. var height = args[j++];
  4239. if (width === 0) {
  4240. width = this.getSinglePixelWidth();
  4241. }
  4242. if (height === 0) {
  4243. height = this.getSinglePixelWidth();
  4244. }
  4245. var xw = x + width;
  4246. var yh = y + height;
  4247. this.ctx.moveTo(x, y);
  4248. this.ctx.lineTo(xw, y);
  4249. this.ctx.lineTo(xw, yh);
  4250. this.ctx.lineTo(x, yh);
  4251. this.ctx.lineTo(x, y);
  4252. this.ctx.closePath();
  4253. break;
  4254. case OPS.moveTo:
  4255. x = args[j++];
  4256. y = args[j++];
  4257. ctx.moveTo(x, y);
  4258. break;
  4259. case OPS.lineTo:
  4260. x = args[j++];
  4261. y = args[j++];
  4262. ctx.lineTo(x, y);
  4263. break;
  4264. case OPS.curveTo:
  4265. x = args[j + 4];
  4266. y = args[j + 5];
  4267. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  4268. x, y);
  4269. j += 6;
  4270. break;
  4271. case OPS.curveTo2:
  4272. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  4273. args[j + 2], args[j + 3]);
  4274. x = args[j + 2];
  4275. y = args[j + 3];
  4276. j += 4;
  4277. break;
  4278. case OPS.curveTo3:
  4279. x = args[j + 2];
  4280. y = args[j + 3];
  4281. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4282. j += 4;
  4283. break;
  4284. case OPS.closePath:
  4285. ctx.closePath();
  4286. break;
  4287. }
  4288. }
  4289. current.setCurrentPoint(x, y);
  4290. },
  4291. closePath: function CanvasGraphics_closePath() {
  4292. this.ctx.closePath();
  4293. },
  4294. stroke: function CanvasGraphics_stroke(consumePath) {
  4295. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4296. var ctx = this.ctx;
  4297. var strokeColor = this.current.strokeColor;
  4298. // Prevent drawing too thin lines by enforcing a minimum line width.
  4299. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  4300. this.current.lineWidth);
  4301. // For stroke we want to temporarily change the global alpha to the
  4302. // stroking alpha.
  4303. ctx.globalAlpha = this.current.strokeAlpha;
  4304. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  4305. strokeColor.type === 'Pattern') {
  4306. // for patterns, we transform to pattern space, calculate
  4307. // the pattern, call stroke, and restore to user space
  4308. ctx.save();
  4309. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  4310. ctx.stroke();
  4311. ctx.restore();
  4312. } else {
  4313. ctx.stroke();
  4314. }
  4315. if (consumePath) {
  4316. this.consumePath();
  4317. }
  4318. // Restore the global alpha to the fill alpha
  4319. ctx.globalAlpha = this.current.fillAlpha;
  4320. },
  4321. closeStroke: function CanvasGraphics_closeStroke() {
  4322. this.closePath();
  4323. this.stroke();
  4324. },
  4325. fill: function CanvasGraphics_fill(consumePath) {
  4326. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4327. var ctx = this.ctx;
  4328. var fillColor = this.current.fillColor;
  4329. var isPatternFill = this.current.patternFill;
  4330. var needRestore = false;
  4331. if (isPatternFill) {
  4332. ctx.save();
  4333. if (this.baseTransform) {
  4334. ctx.setTransform.apply(ctx, this.baseTransform);
  4335. }
  4336. ctx.fillStyle = fillColor.getPattern(ctx, this);
  4337. needRestore = true;
  4338. }
  4339. if (this.pendingEOFill) {
  4340. if (ctx.mozFillRule !== undefined) {
  4341. ctx.mozFillRule = 'evenodd';
  4342. ctx.fill();
  4343. ctx.mozFillRule = 'nonzero';
  4344. } else {
  4345. ctx.fill('evenodd');
  4346. }
  4347. this.pendingEOFill = false;
  4348. } else {
  4349. ctx.fill();
  4350. }
  4351. if (needRestore) {
  4352. ctx.restore();
  4353. }
  4354. if (consumePath) {
  4355. this.consumePath();
  4356. }
  4357. },
  4358. eoFill: function CanvasGraphics_eoFill() {
  4359. this.pendingEOFill = true;
  4360. this.fill();
  4361. },
  4362. fillStroke: function CanvasGraphics_fillStroke() {
  4363. this.fill(false);
  4364. this.stroke(false);
  4365. this.consumePath();
  4366. },
  4367. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  4368. this.pendingEOFill = true;
  4369. this.fillStroke();
  4370. },
  4371. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  4372. this.closePath();
  4373. this.fillStroke();
  4374. },
  4375. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  4376. this.pendingEOFill = true;
  4377. this.closePath();
  4378. this.fillStroke();
  4379. },
  4380. endPath: function CanvasGraphics_endPath() {
  4381. this.consumePath();
  4382. },
  4383. // Clipping
  4384. clip: function CanvasGraphics_clip() {
  4385. this.pendingClip = NORMAL_CLIP;
  4386. },
  4387. eoClip: function CanvasGraphics_eoClip() {
  4388. this.pendingClip = EO_CLIP;
  4389. },
  4390. // Text
  4391. beginText: function CanvasGraphics_beginText() {
  4392. this.current.textMatrix = IDENTITY_MATRIX;
  4393. this.current.textMatrixScale = 1;
  4394. this.current.x = this.current.lineX = 0;
  4395. this.current.y = this.current.lineY = 0;
  4396. },
  4397. endText: function CanvasGraphics_endText() {
  4398. var paths = this.pendingTextPaths;
  4399. var ctx = this.ctx;
  4400. if (paths === undefined) {
  4401. ctx.beginPath();
  4402. return;
  4403. }
  4404. ctx.save();
  4405. ctx.beginPath();
  4406. for (var i = 0; i < paths.length; i++) {
  4407. var path = paths[i];
  4408. ctx.setTransform.apply(ctx, path.transform);
  4409. ctx.translate(path.x, path.y);
  4410. path.addToPath(ctx, path.fontSize);
  4411. }
  4412. ctx.restore();
  4413. ctx.clip();
  4414. ctx.beginPath();
  4415. delete this.pendingTextPaths;
  4416. },
  4417. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  4418. this.current.charSpacing = spacing;
  4419. },
  4420. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  4421. this.current.wordSpacing = spacing;
  4422. },
  4423. setHScale: function CanvasGraphics_setHScale(scale) {
  4424. this.current.textHScale = scale / 100;
  4425. },
  4426. setLeading: function CanvasGraphics_setLeading(leading) {
  4427. this.current.leading = -leading;
  4428. },
  4429. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  4430. var fontObj = this.commonObjs.get(fontRefName);
  4431. var current = this.current;
  4432. if (!fontObj) {
  4433. error('Can\'t find font for ' + fontRefName);
  4434. }
  4435. current.fontMatrix = (fontObj.fontMatrix ?
  4436. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4437. // A valid matrix needs all main diagonal elements to be non-zero
  4438. // This also ensures we bypass FF bugzilla bug #719844.
  4439. if (current.fontMatrix[0] === 0 ||
  4440. current.fontMatrix[3] === 0) {
  4441. warn('Invalid font matrix for font ' + fontRefName);
  4442. }
  4443. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4444. // and in some docs this can be negative (inverted x-y axes).
  4445. if (size < 0) {
  4446. size = -size;
  4447. current.fontDirection = -1;
  4448. } else {
  4449. current.fontDirection = 1;
  4450. }
  4451. this.current.font = fontObj;
  4452. this.current.fontSize = size;
  4453. if (fontObj.isType3Font) {
  4454. return; // we don't need ctx.font for Type3 fonts
  4455. }
  4456. var name = fontObj.loadedName || 'sans-serif';
  4457. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  4458. (fontObj.bold ? 'bold' : 'normal');
  4459. var italic = fontObj.italic ? 'italic' : 'normal';
  4460. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4461. // Some font backends cannot handle fonts below certain size.
  4462. // Keeping the font at minimal size and using the fontSizeScale to change
  4463. // the current transformation matrix before the fillText/strokeText.
  4464. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4465. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  4466. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  4467. this.current.fontSizeScale = size / browserFontSize;
  4468. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4469. this.ctx.font = rule;
  4470. },
  4471. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4472. this.current.textRenderingMode = mode;
  4473. },
  4474. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4475. this.current.textRise = rise;
  4476. },
  4477. moveText: function CanvasGraphics_moveText(x, y) {
  4478. this.current.x = this.current.lineX += x;
  4479. this.current.y = this.current.lineY += y;
  4480. },
  4481. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4482. this.setLeading(-y);
  4483. this.moveText(x, y);
  4484. },
  4485. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4486. this.current.textMatrix = [a, b, c, d, e, f];
  4487. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4488. this.current.x = this.current.lineX = 0;
  4489. this.current.y = this.current.lineY = 0;
  4490. },
  4491. nextLine: function CanvasGraphics_nextLine() {
  4492. this.moveText(0, this.current.leading);
  4493. },
  4494. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4495. var ctx = this.ctx;
  4496. var current = this.current;
  4497. var font = current.font;
  4498. var textRenderingMode = current.textRenderingMode;
  4499. var fontSize = current.fontSize / current.fontSizeScale;
  4500. var fillStrokeMode = textRenderingMode &
  4501. TextRenderingMode.FILL_STROKE_MASK;
  4502. var isAddToPathSet = !!(textRenderingMode &
  4503. TextRenderingMode.ADD_TO_PATH_FLAG);
  4504. var addToPath;
  4505. if (font.disableFontFace || isAddToPathSet) {
  4506. addToPath = font.getPathGenerator(this.commonObjs, character);
  4507. }
  4508. if (font.disableFontFace) {
  4509. ctx.save();
  4510. ctx.translate(x, y);
  4511. ctx.beginPath();
  4512. addToPath(ctx, fontSize);
  4513. if (fillStrokeMode === TextRenderingMode.FILL ||
  4514. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4515. ctx.fill();
  4516. }
  4517. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4518. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4519. ctx.stroke();
  4520. }
  4521. ctx.restore();
  4522. } else {
  4523. if (fillStrokeMode === TextRenderingMode.FILL ||
  4524. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4525. ctx.fillText(character, x, y);
  4526. }
  4527. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4528. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4529. ctx.strokeText(character, x, y);
  4530. }
  4531. }
  4532. if (isAddToPathSet) {
  4533. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4534. paths.push({
  4535. transform: ctx.mozCurrentTransform,
  4536. x: x,
  4537. y: y,
  4538. fontSize: fontSize,
  4539. addToPath: addToPath
  4540. });
  4541. }
  4542. },
  4543. get isFontSubpixelAAEnabled() {
  4544. // Checks if anti-aliasing is enabled when scaled text is painted.
  4545. // On Windows GDI scaled fonts looks bad.
  4546. var ctx = document.createElement('canvas').getContext('2d');
  4547. ctx.scale(1.5, 1);
  4548. ctx.fillText('I', 0, 10);
  4549. var data = ctx.getImageData(0, 0, 10, 10).data;
  4550. var enabled = false;
  4551. for (var i = 3; i < data.length; i += 4) {
  4552. if (data[i] > 0 && data[i] < 255) {
  4553. enabled = true;
  4554. break;
  4555. }
  4556. }
  4557. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4558. },
  4559. showText: function CanvasGraphics_showText(glyphs) {
  4560. var current = this.current;
  4561. var font = current.font;
  4562. if (font.isType3Font) {
  4563. return this.showType3Text(glyphs);
  4564. }
  4565. var fontSize = current.fontSize;
  4566. if (fontSize === 0) {
  4567. return;
  4568. }
  4569. var ctx = this.ctx;
  4570. var fontSizeScale = current.fontSizeScale;
  4571. var charSpacing = current.charSpacing;
  4572. var wordSpacing = current.wordSpacing;
  4573. var fontDirection = current.fontDirection;
  4574. var textHScale = current.textHScale * fontDirection;
  4575. var glyphsLength = glyphs.length;
  4576. var vertical = font.vertical;
  4577. var spacingDir = vertical ? 1 : -1;
  4578. var defaultVMetrics = font.defaultVMetrics;
  4579. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4580. var simpleFillText =
  4581. current.textRenderingMode === TextRenderingMode.FILL &&
  4582. !font.disableFontFace;
  4583. ctx.save();
  4584. ctx.transform.apply(ctx, current.textMatrix);
  4585. ctx.translate(current.x, current.y + current.textRise);
  4586. if (fontDirection > 0) {
  4587. ctx.scale(textHScale, -1);
  4588. } else {
  4589. ctx.scale(textHScale, 1);
  4590. }
  4591. var lineWidth = current.lineWidth;
  4592. var scale = current.textMatrixScale;
  4593. if (scale === 0 || lineWidth === 0) {
  4594. var fillStrokeMode = current.textRenderingMode &
  4595. TextRenderingMode.FILL_STROKE_MASK;
  4596. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4597. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4598. this.cachedGetSinglePixelWidth = null;
  4599. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  4600. }
  4601. } else {
  4602. lineWidth /= scale;
  4603. }
  4604. if (fontSizeScale !== 1.0) {
  4605. ctx.scale(fontSizeScale, fontSizeScale);
  4606. lineWidth /= fontSizeScale;
  4607. }
  4608. ctx.lineWidth = lineWidth;
  4609. var x = 0, i;
  4610. for (i = 0; i < glyphsLength; ++i) {
  4611. var glyph = glyphs[i];
  4612. if (isNum(glyph)) {
  4613. x += spacingDir * glyph * fontSize / 1000;
  4614. continue;
  4615. }
  4616. var restoreNeeded = false;
  4617. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  4618. var character = glyph.fontChar;
  4619. var accent = glyph.accent;
  4620. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4621. var width = glyph.width;
  4622. if (vertical) {
  4623. var vmetric, vx, vy;
  4624. vmetric = glyph.vmetric || defaultVMetrics;
  4625. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4626. vx = -vx * widthAdvanceScale;
  4627. vy = vmetric[2] * widthAdvanceScale;
  4628. width = vmetric ? -vmetric[0] : width;
  4629. scaledX = vx / fontSizeScale;
  4630. scaledY = (x + vy) / fontSizeScale;
  4631. } else {
  4632. scaledX = x / fontSizeScale;
  4633. scaledY = 0;
  4634. }
  4635. if (font.remeasure && width > 0) {
  4636. // Some standard fonts may not have the exact width: rescale per
  4637. // character if measured width is greater than expected glyph width
  4638. // and subpixel-aa is enabled, otherwise just center the glyph.
  4639. var measuredWidth = ctx.measureText(character).width * 1000 /
  4640. fontSize * fontSizeScale;
  4641. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  4642. var characterScaleX = width / measuredWidth;
  4643. restoreNeeded = true;
  4644. ctx.save();
  4645. ctx.scale(characterScaleX, 1);
  4646. scaledX /= characterScaleX;
  4647. } else if (width !== measuredWidth) {
  4648. scaledX += (width - measuredWidth) / 2000 *
  4649. fontSize / fontSizeScale;
  4650. }
  4651. }
  4652. if (simpleFillText && !accent) {
  4653. // common case
  4654. ctx.fillText(character, scaledX, scaledY);
  4655. } else {
  4656. this.paintChar(character, scaledX, scaledY);
  4657. if (accent) {
  4658. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4659. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4660. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4661. }
  4662. }
  4663. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  4664. x += charWidth;
  4665. if (restoreNeeded) {
  4666. ctx.restore();
  4667. }
  4668. }
  4669. if (vertical) {
  4670. current.y -= x * textHScale;
  4671. } else {
  4672. current.x += x * textHScale;
  4673. }
  4674. ctx.restore();
  4675. },
  4676. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4677. // Type3 fonts - each glyph is a "mini-PDF"
  4678. var ctx = this.ctx;
  4679. var current = this.current;
  4680. var font = current.font;
  4681. var fontSize = current.fontSize;
  4682. var fontDirection = current.fontDirection;
  4683. var spacingDir = font.vertical ? 1 : -1;
  4684. var charSpacing = current.charSpacing;
  4685. var wordSpacing = current.wordSpacing;
  4686. var textHScale = current.textHScale * fontDirection;
  4687. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4688. var glyphsLength = glyphs.length;
  4689. var isTextInvisible =
  4690. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4691. var i, glyph, width, spacingLength;
  4692. if (isTextInvisible || fontSize === 0) {
  4693. return;
  4694. }
  4695. this.cachedGetSinglePixelWidth = null;
  4696. ctx.save();
  4697. ctx.transform.apply(ctx, current.textMatrix);
  4698. ctx.translate(current.x, current.y);
  4699. ctx.scale(textHScale, fontDirection);
  4700. for (i = 0; i < glyphsLength; ++i) {
  4701. glyph = glyphs[i];
  4702. if (isNum(glyph)) {
  4703. spacingLength = spacingDir * glyph * fontSize / 1000;
  4704. this.ctx.translate(spacingLength, 0);
  4705. current.x += spacingLength * textHScale;
  4706. continue;
  4707. }
  4708. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  4709. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4710. if (!operatorList) {
  4711. warn('Type3 character \"' + glyph.operatorListId +
  4712. '\" is not available');
  4713. continue;
  4714. }
  4715. this.processingType3 = glyph;
  4716. this.save();
  4717. ctx.scale(fontSize, fontSize);
  4718. ctx.transform.apply(ctx, fontMatrix);
  4719. this.executeOperatorList(operatorList);
  4720. this.restore();
  4721. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4722. width = transformed[0] * fontSize + spacing;
  4723. ctx.translate(width, 0);
  4724. current.x += width * textHScale;
  4725. }
  4726. ctx.restore();
  4727. this.processingType3 = null;
  4728. },
  4729. // Type3 fonts
  4730. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4731. // We can safely ignore this since the width should be the same
  4732. // as the width in the Widths array.
  4733. },
  4734. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4735. yWidth,
  4736. llx,
  4737. lly,
  4738. urx,
  4739. ury) {
  4740. // TODO According to the spec we're also suppose to ignore any operators
  4741. // that set color or include images while processing this type3 font.
  4742. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4743. this.clip();
  4744. this.endPath();
  4745. },
  4746. // Color
  4747. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4748. var pattern;
  4749. if (IR[0] === 'TilingPattern') {
  4750. var color = IR[1];
  4751. var baseTransform = this.baseTransform ||
  4752. this.ctx.mozCurrentTransform.slice();
  4753. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4754. this.commonObjs, baseTransform);
  4755. } else {
  4756. pattern = getShadingPatternFromIR(IR);
  4757. }
  4758. return pattern;
  4759. },
  4760. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4761. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4762. },
  4763. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4764. this.current.fillColor = this.getColorN_Pattern(arguments);
  4765. this.current.patternFill = true;
  4766. },
  4767. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4768. var color = Util.makeCssRgb(r, g, b);
  4769. this.ctx.strokeStyle = color;
  4770. this.current.strokeColor = color;
  4771. },
  4772. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4773. var color = Util.makeCssRgb(r, g, b);
  4774. this.ctx.fillStyle = color;
  4775. this.current.fillColor = color;
  4776. this.current.patternFill = false;
  4777. },
  4778. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4779. var ctx = this.ctx;
  4780. this.save();
  4781. var pattern = getShadingPatternFromIR(patternIR);
  4782. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4783. var inv = ctx.mozCurrentTransformInverse;
  4784. if (inv) {
  4785. var canvas = ctx.canvas;
  4786. var width = canvas.width;
  4787. var height = canvas.height;
  4788. var bl = Util.applyTransform([0, 0], inv);
  4789. var br = Util.applyTransform([0, height], inv);
  4790. var ul = Util.applyTransform([width, 0], inv);
  4791. var ur = Util.applyTransform([width, height], inv);
  4792. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4793. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4794. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4795. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4796. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4797. } else {
  4798. // HACK to draw the gradient onto an infinite rectangle.
  4799. // PDF gradients are drawn across the entire image while
  4800. // Canvas only allows gradients to be drawn in a rectangle
  4801. // The following bug should allow us to remove this.
  4802. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4803. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4804. }
  4805. this.restore();
  4806. },
  4807. // Images
  4808. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4809. error('Should not call beginInlineImage');
  4810. },
  4811. beginImageData: function CanvasGraphics_beginImageData() {
  4812. error('Should not call beginImageData');
  4813. },
  4814. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4815. bbox) {
  4816. this.save();
  4817. this.baseTransformStack.push(this.baseTransform);
  4818. if (isArray(matrix) && 6 === matrix.length) {
  4819. this.transform.apply(this, matrix);
  4820. }
  4821. this.baseTransform = this.ctx.mozCurrentTransform;
  4822. if (isArray(bbox) && 4 === bbox.length) {
  4823. var width = bbox[2] - bbox[0];
  4824. var height = bbox[3] - bbox[1];
  4825. this.ctx.rect(bbox[0], bbox[1], width, height);
  4826. this.clip();
  4827. this.endPath();
  4828. }
  4829. },
  4830. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4831. this.restore();
  4832. this.baseTransform = this.baseTransformStack.pop();
  4833. },
  4834. beginGroup: function CanvasGraphics_beginGroup(group) {
  4835. this.save();
  4836. var currentCtx = this.ctx;
  4837. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4838. // group results aren't usually that different and they even have tools
  4839. // that ignore this setting. Notes from Rik on implmenting:
  4840. // - When you encounter an transparency group, create a new canvas with
  4841. // the dimensions of the bbox
  4842. // - copy the content from the previous canvas to the new canvas
  4843. // - draw as usual
  4844. // - remove the backdrop alpha:
  4845. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4846. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4847. // backdrop
  4848. // - remove background color:
  4849. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4850. if (!group.isolated) {
  4851. info('TODO: Support non-isolated groups.');
  4852. }
  4853. // TODO knockout - supposedly possible with the clever use of compositing
  4854. // modes.
  4855. if (group.knockout) {
  4856. warn('Knockout groups not supported.');
  4857. }
  4858. var currentTransform = currentCtx.mozCurrentTransform;
  4859. if (group.matrix) {
  4860. currentCtx.transform.apply(currentCtx, group.matrix);
  4861. }
  4862. assert(group.bbox, 'Bounding box is required.');
  4863. // Based on the current transform figure out how big the bounding box
  4864. // will actually be.
  4865. var bounds = Util.getAxialAlignedBoundingBox(
  4866. group.bbox,
  4867. currentCtx.mozCurrentTransform);
  4868. // Clip the bounding box to the current canvas.
  4869. var canvasBounds = [0,
  4870. 0,
  4871. currentCtx.canvas.width,
  4872. currentCtx.canvas.height];
  4873. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4874. // Use ceil in case we're between sizes so we don't create canvas that is
  4875. // too small and make the canvas at least 1x1 pixels.
  4876. var offsetX = Math.floor(bounds[0]);
  4877. var offsetY = Math.floor(bounds[1]);
  4878. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4879. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4880. var scaleX = 1, scaleY = 1;
  4881. if (drawnWidth > MAX_GROUP_SIZE) {
  4882. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4883. drawnWidth = MAX_GROUP_SIZE;
  4884. }
  4885. if (drawnHeight > MAX_GROUP_SIZE) {
  4886. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4887. drawnHeight = MAX_GROUP_SIZE;
  4888. }
  4889. var cacheId = 'groupAt' + this.groupLevel;
  4890. if (group.smask) {
  4891. // Using two cache entries is case if masks are used one after another.
  4892. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4893. }
  4894. var scratchCanvas = this.cachedCanvases.getCanvas(
  4895. cacheId, drawnWidth, drawnHeight, true);
  4896. var groupCtx = scratchCanvas.context;
  4897. // Since we created a new canvas that is just the size of the bounding box
  4898. // we have to translate the group ctx.
  4899. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4900. groupCtx.translate(-offsetX, -offsetY);
  4901. groupCtx.transform.apply(groupCtx, currentTransform);
  4902. if (group.smask) {
  4903. // Saving state and cached mask to be used in setGState.
  4904. this.smaskStack.push({
  4905. canvas: scratchCanvas.canvas,
  4906. context: groupCtx,
  4907. offsetX: offsetX,
  4908. offsetY: offsetY,
  4909. scaleX: scaleX,
  4910. scaleY: scaleY,
  4911. subtype: group.smask.subtype,
  4912. backdrop: group.smask.backdrop,
  4913. transferMap: group.smask.transferMap || null
  4914. });
  4915. } else {
  4916. // Setup the current ctx so when the group is popped we draw it at the
  4917. // right location.
  4918. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4919. currentCtx.translate(offsetX, offsetY);
  4920. currentCtx.scale(scaleX, scaleY);
  4921. }
  4922. // The transparency group inherits all off the current graphics state
  4923. // except the blend mode, soft mask, and alpha constants.
  4924. copyCtxState(currentCtx, groupCtx);
  4925. this.ctx = groupCtx;
  4926. this.setGState([
  4927. ['BM', 'Normal'],
  4928. ['ca', 1],
  4929. ['CA', 1]
  4930. ]);
  4931. this.groupStack.push(currentCtx);
  4932. this.groupLevel++;
  4933. },
  4934. endGroup: function CanvasGraphics_endGroup(group) {
  4935. this.groupLevel--;
  4936. var groupCtx = this.ctx;
  4937. this.ctx = this.groupStack.pop();
  4938. // Turn off image smoothing to avoid sub pixel interpolation which can
  4939. // look kind of blurry for some pdfs.
  4940. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4941. this.ctx.imageSmoothingEnabled = false;
  4942. } else {
  4943. this.ctx.mozImageSmoothingEnabled = false;
  4944. }
  4945. if (group.smask) {
  4946. this.tempSMask = this.smaskStack.pop();
  4947. } else {
  4948. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4949. }
  4950. this.restore();
  4951. },
  4952. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4953. this.save();
  4954. this.current = new CanvasExtraState();
  4955. },
  4956. endAnnotations: function CanvasGraphics_endAnnotations() {
  4957. this.restore();
  4958. },
  4959. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4960. matrix) {
  4961. this.save();
  4962. if (isArray(rect) && 4 === rect.length) {
  4963. var width = rect[2] - rect[0];
  4964. var height = rect[3] - rect[1];
  4965. this.ctx.rect(rect[0], rect[1], width, height);
  4966. this.clip();
  4967. this.endPath();
  4968. }
  4969. this.transform.apply(this, transform);
  4970. this.transform.apply(this, matrix);
  4971. },
  4972. endAnnotation: function CanvasGraphics_endAnnotation() {
  4973. this.restore();
  4974. },
  4975. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4976. var domImage = this.objs.get(objId);
  4977. if (!domImage) {
  4978. warn('Dependent image isn\'t ready yet');
  4979. return;
  4980. }
  4981. this.save();
  4982. var ctx = this.ctx;
  4983. // scale the image to the unit square
  4984. ctx.scale(1 / w, -1 / h);
  4985. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4986. 0, -h, w, h);
  4987. if (this.imageLayer) {
  4988. var currentTransform = ctx.mozCurrentTransformInverse;
  4989. var position = this.getCanvasPosition(0, 0);
  4990. this.imageLayer.appendImage({
  4991. objId: objId,
  4992. left: position[0],
  4993. top: position[1],
  4994. width: w / currentTransform[0],
  4995. height: h / currentTransform[3]
  4996. });
  4997. }
  4998. this.restore();
  4999. },
  5000. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  5001. var ctx = this.ctx;
  5002. var width = img.width, height = img.height;
  5003. var fillColor = this.current.fillColor;
  5004. var isPatternFill = this.current.patternFill;
  5005. var glyph = this.processingType3;
  5006. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  5007. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  5008. glyph.compiled =
  5009. compileType3Glyph({data: img.data, width: width, height: height});
  5010. } else {
  5011. glyph.compiled = null;
  5012. }
  5013. }
  5014. if (glyph && glyph.compiled) {
  5015. glyph.compiled(ctx);
  5016. return;
  5017. }
  5018. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  5019. width, height);
  5020. var maskCtx = maskCanvas.context;
  5021. maskCtx.save();
  5022. putBinaryImageMask(maskCtx, img);
  5023. maskCtx.globalCompositeOperation = 'source-in';
  5024. maskCtx.fillStyle = isPatternFill ?
  5025. fillColor.getPattern(maskCtx, this) : fillColor;
  5026. maskCtx.fillRect(0, 0, width, height);
  5027. maskCtx.restore();
  5028. this.paintInlineImageXObject(maskCanvas.canvas);
  5029. },
  5030. paintImageMaskXObjectRepeat:
  5031. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  5032. scaleY, positions) {
  5033. var width = imgData.width;
  5034. var height = imgData.height;
  5035. var fillColor = this.current.fillColor;
  5036. var isPatternFill = this.current.patternFill;
  5037. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  5038. width, height);
  5039. var maskCtx = maskCanvas.context;
  5040. maskCtx.save();
  5041. putBinaryImageMask(maskCtx, imgData);
  5042. maskCtx.globalCompositeOperation = 'source-in';
  5043. maskCtx.fillStyle = isPatternFill ?
  5044. fillColor.getPattern(maskCtx, this) : fillColor;
  5045. maskCtx.fillRect(0, 0, width, height);
  5046. maskCtx.restore();
  5047. var ctx = this.ctx;
  5048. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  5049. ctx.save();
  5050. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  5051. ctx.scale(1, -1);
  5052. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  5053. 0, -1, 1, 1);
  5054. ctx.restore();
  5055. }
  5056. },
  5057. paintImageMaskXObjectGroup:
  5058. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  5059. var ctx = this.ctx;
  5060. var fillColor = this.current.fillColor;
  5061. var isPatternFill = this.current.patternFill;
  5062. for (var i = 0, ii = images.length; i < ii; i++) {
  5063. var image = images[i];
  5064. var width = image.width, height = image.height;
  5065. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  5066. width, height);
  5067. var maskCtx = maskCanvas.context;
  5068. maskCtx.save();
  5069. putBinaryImageMask(maskCtx, image);
  5070. maskCtx.globalCompositeOperation = 'source-in';
  5071. maskCtx.fillStyle = isPatternFill ?
  5072. fillColor.getPattern(maskCtx, this) : fillColor;
  5073. maskCtx.fillRect(0, 0, width, height);
  5074. maskCtx.restore();
  5075. ctx.save();
  5076. ctx.transform.apply(ctx, image.transform);
  5077. ctx.scale(1, -1);
  5078. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  5079. 0, -1, 1, 1);
  5080. ctx.restore();
  5081. }
  5082. },
  5083. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  5084. var imgData = this.objs.get(objId);
  5085. if (!imgData) {
  5086. warn('Dependent image isn\'t ready yet');
  5087. return;
  5088. }
  5089. this.paintInlineImageXObject(imgData);
  5090. },
  5091. paintImageXObjectRepeat:
  5092. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  5093. positions) {
  5094. var imgData = this.objs.get(objId);
  5095. if (!imgData) {
  5096. warn('Dependent image isn\'t ready yet');
  5097. return;
  5098. }
  5099. var width = imgData.width;
  5100. var height = imgData.height;
  5101. var map = [];
  5102. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  5103. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  5104. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  5105. }
  5106. this.paintInlineImageXObjectGroup(imgData, map);
  5107. },
  5108. paintInlineImageXObject:
  5109. function CanvasGraphics_paintInlineImageXObject(imgData) {
  5110. var width = imgData.width;
  5111. var height = imgData.height;
  5112. var ctx = this.ctx;
  5113. this.save();
  5114. // scale the image to the unit square
  5115. ctx.scale(1 / width, -1 / height);
  5116. var currentTransform = ctx.mozCurrentTransformInverse;
  5117. var a = currentTransform[0], b = currentTransform[1];
  5118. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  5119. var c = currentTransform[2], d = currentTransform[3];
  5120. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  5121. var imgToPaint, tmpCanvas;
  5122. // instanceof HTMLElement does not work in jsdom node.js module
  5123. if (imgData instanceof HTMLElement || !imgData.data) {
  5124. imgToPaint = imgData;
  5125. } else {
  5126. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  5127. width, height);
  5128. var tmpCtx = tmpCanvas.context;
  5129. putBinaryImageData(tmpCtx, imgData);
  5130. imgToPaint = tmpCanvas.canvas;
  5131. }
  5132. var paintWidth = width, paintHeight = height;
  5133. var tmpCanvasId = 'prescale1';
  5134. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  5135. // pixels during drawImage operation, painting on the temporary canvas(es)
  5136. // that are twice smaller in size
  5137. while ((widthScale > 2 && paintWidth > 1) ||
  5138. (heightScale > 2 && paintHeight > 1)) {
  5139. var newWidth = paintWidth, newHeight = paintHeight;
  5140. if (widthScale > 2 && paintWidth > 1) {
  5141. newWidth = Math.ceil(paintWidth / 2);
  5142. widthScale /= paintWidth / newWidth;
  5143. }
  5144. if (heightScale > 2 && paintHeight > 1) {
  5145. newHeight = Math.ceil(paintHeight / 2);
  5146. heightScale /= paintHeight / newHeight;
  5147. }
  5148. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  5149. newWidth, newHeight);
  5150. tmpCtx = tmpCanvas.context;
  5151. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5152. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5153. 0, 0, newWidth, newHeight);
  5154. imgToPaint = tmpCanvas.canvas;
  5155. paintWidth = newWidth;
  5156. paintHeight = newHeight;
  5157. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  5158. }
  5159. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5160. 0, -height, width, height);
  5161. if (this.imageLayer) {
  5162. var position = this.getCanvasPosition(0, -height);
  5163. this.imageLayer.appendImage({
  5164. imgData: imgData,
  5165. left: position[0],
  5166. top: position[1],
  5167. width: width / currentTransform[0],
  5168. height: height / currentTransform[3]
  5169. });
  5170. }
  5171. this.restore();
  5172. },
  5173. paintInlineImageXObjectGroup:
  5174. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  5175. var ctx = this.ctx;
  5176. var w = imgData.width;
  5177. var h = imgData.height;
  5178. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  5179. var tmpCtx = tmpCanvas.context;
  5180. putBinaryImageData(tmpCtx, imgData);
  5181. for (var i = 0, ii = map.length; i < ii; i++) {
  5182. var entry = map[i];
  5183. ctx.save();
  5184. ctx.transform.apply(ctx, entry.transform);
  5185. ctx.scale(1, -1);
  5186. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  5187. 0, -1, 1, 1);
  5188. if (this.imageLayer) {
  5189. var position = this.getCanvasPosition(entry.x, entry.y);
  5190. this.imageLayer.appendImage({
  5191. imgData: imgData,
  5192. left: position[0],
  5193. top: position[1],
  5194. width: w,
  5195. height: h
  5196. });
  5197. }
  5198. ctx.restore();
  5199. }
  5200. },
  5201. paintSolidColorImageMask:
  5202. function CanvasGraphics_paintSolidColorImageMask() {
  5203. this.ctx.fillRect(0, 0, 1, 1);
  5204. },
  5205. paintXObject: function CanvasGraphics_paintXObject() {
  5206. warn('Unsupported \'paintXObject\' command.');
  5207. },
  5208. // Marked content
  5209. markPoint: function CanvasGraphics_markPoint(tag) {
  5210. // TODO Marked content.
  5211. },
  5212. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  5213. // TODO Marked content.
  5214. },
  5215. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  5216. // TODO Marked content.
  5217. },
  5218. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  5219. tag, properties) {
  5220. // TODO Marked content.
  5221. },
  5222. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  5223. // TODO Marked content.
  5224. },
  5225. // Compatibility
  5226. beginCompat: function CanvasGraphics_beginCompat() {
  5227. // TODO ignore undefined operators (should we do that anyway?)
  5228. },
  5229. endCompat: function CanvasGraphics_endCompat() {
  5230. // TODO stop ignoring undefined operators
  5231. },
  5232. // Helper functions
  5233. consumePath: function CanvasGraphics_consumePath() {
  5234. var ctx = this.ctx;
  5235. if (this.pendingClip) {
  5236. if (this.pendingClip === EO_CLIP) {
  5237. if (ctx.mozFillRule !== undefined) {
  5238. ctx.mozFillRule = 'evenodd';
  5239. ctx.clip();
  5240. ctx.mozFillRule = 'nonzero';
  5241. } else {
  5242. ctx.clip('evenodd');
  5243. }
  5244. } else {
  5245. ctx.clip();
  5246. }
  5247. this.pendingClip = null;
  5248. }
  5249. ctx.beginPath();
  5250. },
  5251. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  5252. if (this.cachedGetSinglePixelWidth === null) {
  5253. var inverse = this.ctx.mozCurrentTransformInverse;
  5254. // max of the current horizontal and vertical scale
  5255. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  5256. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  5257. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  5258. }
  5259. return this.cachedGetSinglePixelWidth;
  5260. },
  5261. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  5262. var transform = this.ctx.mozCurrentTransform;
  5263. return [
  5264. transform[0] * x + transform[2] * y + transform[4],
  5265. transform[1] * x + transform[3] * y + transform[5]
  5266. ];
  5267. }
  5268. };
  5269. for (var op in OPS) {
  5270. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  5271. }
  5272. return CanvasGraphics;
  5273. })();
  5274. var WebGLUtils = (function WebGLUtilsClosure() {
  5275. function loadShader(gl, code, shaderType) {
  5276. var shader = gl.createShader(shaderType);
  5277. gl.shaderSource(shader, code);
  5278. gl.compileShader(shader);
  5279. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5280. if (!compiled) {
  5281. var errorMsg = gl.getShaderInfoLog(shader);
  5282. throw new Error('Error during shader compilation: ' + errorMsg);
  5283. }
  5284. return shader;
  5285. }
  5286. function createVertexShader(gl, code) {
  5287. return loadShader(gl, code, gl.VERTEX_SHADER);
  5288. }
  5289. function createFragmentShader(gl, code) {
  5290. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5291. }
  5292. function createProgram(gl, shaders) {
  5293. var program = gl.createProgram();
  5294. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5295. gl.attachShader(program, shaders[i]);
  5296. }
  5297. gl.linkProgram(program);
  5298. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5299. if (!linked) {
  5300. var errorMsg = gl.getProgramInfoLog(program);
  5301. throw new Error('Error during program linking: ' + errorMsg);
  5302. }
  5303. return program;
  5304. }
  5305. function createTexture(gl, image, textureId) {
  5306. gl.activeTexture(textureId);
  5307. var texture = gl.createTexture();
  5308. gl.bindTexture(gl.TEXTURE_2D, texture);
  5309. // Set the parameters so we can render any size image.
  5310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5314. // Upload the image into the texture.
  5315. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5316. return texture;
  5317. }
  5318. var currentGL, currentCanvas;
  5319. function generateGL() {
  5320. if (currentGL) {
  5321. return;
  5322. }
  5323. currentCanvas = document.createElement('canvas');
  5324. currentGL = currentCanvas.getContext('webgl',
  5325. { premultipliedalpha: false });
  5326. }
  5327. var smaskVertexShaderCode = '\
  5328. attribute vec2 a_position; \
  5329. attribute vec2 a_texCoord; \
  5330. \
  5331. uniform vec2 u_resolution; \
  5332. \
  5333. varying vec2 v_texCoord; \
  5334. \
  5335. void main() { \
  5336. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5337. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5338. \
  5339. v_texCoord = a_texCoord; \
  5340. } ';
  5341. var smaskFragmentShaderCode = '\
  5342. precision mediump float; \
  5343. \
  5344. uniform vec4 u_backdrop; \
  5345. uniform int u_subtype; \
  5346. uniform sampler2D u_image; \
  5347. uniform sampler2D u_mask; \
  5348. \
  5349. varying vec2 v_texCoord; \
  5350. \
  5351. void main() { \
  5352. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5353. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5354. if (u_backdrop.a > 0.0) { \
  5355. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5356. u_backdrop.rgb * (1.0 - maskColor.a); \
  5357. } \
  5358. float lum; \
  5359. if (u_subtype == 0) { \
  5360. lum = maskColor.a; \
  5361. } else { \
  5362. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5363. maskColor.b * 0.11; \
  5364. } \
  5365. imageColor.a *= lum; \
  5366. imageColor.rgb *= imageColor.a; \
  5367. gl_FragColor = imageColor; \
  5368. } ';
  5369. var smaskCache = null;
  5370. function initSmaskGL() {
  5371. var canvas, gl;
  5372. generateGL();
  5373. canvas = currentCanvas;
  5374. currentCanvas = null;
  5375. gl = currentGL;
  5376. currentGL = null;
  5377. // setup a GLSL program
  5378. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5379. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5380. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5381. gl.useProgram(program);
  5382. var cache = {};
  5383. cache.gl = gl;
  5384. cache.canvas = canvas;
  5385. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5386. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5387. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5388. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5389. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5390. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5391. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5392. // provide texture coordinates for the rectangle.
  5393. var texCoordBuffer = gl.createBuffer();
  5394. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5395. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5396. 0.0, 0.0,
  5397. 1.0, 0.0,
  5398. 0.0, 1.0,
  5399. 0.0, 1.0,
  5400. 1.0, 0.0,
  5401. 1.0, 1.0]), gl.STATIC_DRAW);
  5402. gl.enableVertexAttribArray(texCoordLocation);
  5403. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5404. gl.uniform1i(texLayerLocation, 0);
  5405. gl.uniform1i(texMaskLocation, 1);
  5406. smaskCache = cache;
  5407. }
  5408. function composeSMask(layer, mask, properties) {
  5409. var width = layer.width, height = layer.height;
  5410. if (!smaskCache) {
  5411. initSmaskGL();
  5412. }
  5413. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5414. canvas.width = width;
  5415. canvas.height = height;
  5416. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5417. gl.uniform2f(cache.resolutionLocation, width, height);
  5418. if (properties.backdrop) {
  5419. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5420. properties.backdrop[1], properties.backdrop[2], 1);
  5421. } else {
  5422. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5423. }
  5424. gl.uniform1i(cache.subtypeLocation,
  5425. properties.subtype === 'Luminosity' ? 1 : 0);
  5426. // Create a textures
  5427. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5428. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5429. // Create a buffer and put a single clipspace rectangle in
  5430. // it (2 triangles)
  5431. var buffer = gl.createBuffer();
  5432. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5433. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5434. 0, 0,
  5435. width, 0,
  5436. 0, height,
  5437. 0, height,
  5438. width, 0,
  5439. width, height]), gl.STATIC_DRAW);
  5440. gl.enableVertexAttribArray(cache.positionLocation);
  5441. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5442. // draw
  5443. gl.clearColor(0, 0, 0, 0);
  5444. gl.enable(gl.BLEND);
  5445. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5446. gl.clear(gl.COLOR_BUFFER_BIT);
  5447. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5448. gl.flush();
  5449. gl.deleteTexture(texture);
  5450. gl.deleteTexture(maskTexture);
  5451. gl.deleteBuffer(buffer);
  5452. return canvas;
  5453. }
  5454. var figuresVertexShaderCode = '\
  5455. attribute vec2 a_position; \
  5456. attribute vec3 a_color; \
  5457. \
  5458. uniform vec2 u_resolution; \
  5459. uniform vec2 u_scale; \
  5460. uniform vec2 u_offset; \
  5461. \
  5462. varying vec4 v_color; \
  5463. \
  5464. void main() { \
  5465. vec2 position = (a_position + u_offset) * u_scale; \
  5466. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5467. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5468. \
  5469. v_color = vec4(a_color / 255.0, 1.0); \
  5470. } ';
  5471. var figuresFragmentShaderCode = '\
  5472. precision mediump float; \
  5473. \
  5474. varying vec4 v_color; \
  5475. \
  5476. void main() { \
  5477. gl_FragColor = v_color; \
  5478. } ';
  5479. var figuresCache = null;
  5480. function initFiguresGL() {
  5481. var canvas, gl;
  5482. generateGL();
  5483. canvas = currentCanvas;
  5484. currentCanvas = null;
  5485. gl = currentGL;
  5486. currentGL = null;
  5487. // setup a GLSL program
  5488. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5489. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5490. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5491. gl.useProgram(program);
  5492. var cache = {};
  5493. cache.gl = gl;
  5494. cache.canvas = canvas;
  5495. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5496. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5497. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5498. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5499. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5500. figuresCache = cache;
  5501. }
  5502. function drawFigures(width, height, backgroundColor, figures, context) {
  5503. if (!figuresCache) {
  5504. initFiguresGL();
  5505. }
  5506. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5507. canvas.width = width;
  5508. canvas.height = height;
  5509. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5510. gl.uniform2f(cache.resolutionLocation, width, height);
  5511. // count triangle points
  5512. var count = 0;
  5513. var i, ii, rows;
  5514. for (i = 0, ii = figures.length; i < ii; i++) {
  5515. switch (figures[i].type) {
  5516. case 'lattice':
  5517. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5518. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5519. break;
  5520. case 'triangles':
  5521. count += figures[i].coords.length;
  5522. break;
  5523. }
  5524. }
  5525. // transfer data
  5526. var coords = new Float32Array(count * 2);
  5527. var colors = new Uint8Array(count * 3);
  5528. var coordsMap = context.coords, colorsMap = context.colors;
  5529. var pIndex = 0, cIndex = 0;
  5530. for (i = 0, ii = figures.length; i < ii; i++) {
  5531. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5532. switch (figure.type) {
  5533. case 'lattice':
  5534. var cols = figure.verticesPerRow;
  5535. rows = (ps.length / cols) | 0;
  5536. for (var row = 1; row < rows; row++) {
  5537. var offset = row * cols + 1;
  5538. for (var col = 1; col < cols; col++, offset++) {
  5539. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5540. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5541. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5542. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5543. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5544. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5545. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5546. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5547. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5548. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5549. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5550. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5551. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5552. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5553. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5554. coords[pIndex + 6] = coords[pIndex + 2];
  5555. coords[pIndex + 7] = coords[pIndex + 3];
  5556. coords[pIndex + 8] = coords[pIndex + 4];
  5557. coords[pIndex + 9] = coords[pIndex + 5];
  5558. coords[pIndex + 10] = coordsMap[ps[offset]];
  5559. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5560. colors[cIndex + 9] = colors[cIndex + 3];
  5561. colors[cIndex + 10] = colors[cIndex + 4];
  5562. colors[cIndex + 11] = colors[cIndex + 5];
  5563. colors[cIndex + 12] = colors[cIndex + 6];
  5564. colors[cIndex + 13] = colors[cIndex + 7];
  5565. colors[cIndex + 14] = colors[cIndex + 8];
  5566. colors[cIndex + 15] = colorsMap[cs[offset]];
  5567. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5568. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5569. pIndex += 12;
  5570. cIndex += 18;
  5571. }
  5572. }
  5573. break;
  5574. case 'triangles':
  5575. for (var j = 0, jj = ps.length; j < jj; j++) {
  5576. coords[pIndex] = coordsMap[ps[j]];
  5577. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5578. colors[cIndex] = colorsMap[cs[j]];
  5579. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5580. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5581. pIndex += 2;
  5582. cIndex += 3;
  5583. }
  5584. break;
  5585. }
  5586. }
  5587. // draw
  5588. if (backgroundColor) {
  5589. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5590. backgroundColor[2] / 255, 1.0);
  5591. } else {
  5592. gl.clearColor(0, 0, 0, 0);
  5593. }
  5594. gl.clear(gl.COLOR_BUFFER_BIT);
  5595. var coordsBuffer = gl.createBuffer();
  5596. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5597. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5598. gl.enableVertexAttribArray(cache.positionLocation);
  5599. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5600. var colorsBuffer = gl.createBuffer();
  5601. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5602. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5603. gl.enableVertexAttribArray(cache.colorLocation);
  5604. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5605. 0, 0);
  5606. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5607. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5608. gl.drawArrays(gl.TRIANGLES, 0, count);
  5609. gl.flush();
  5610. gl.deleteBuffer(coordsBuffer);
  5611. gl.deleteBuffer(colorsBuffer);
  5612. return canvas;
  5613. }
  5614. function cleanup() {
  5615. if (smaskCache && smaskCache.canvas) {
  5616. smaskCache.canvas.width = 0;
  5617. smaskCache.canvas.height = 0;
  5618. }
  5619. if (figuresCache && figuresCache.canvas) {
  5620. figuresCache.canvas.width = 0;
  5621. figuresCache.canvas.height = 0;
  5622. }
  5623. smaskCache = null;
  5624. figuresCache = null;
  5625. }
  5626. return {
  5627. get isEnabled() {
  5628. if (PDFJS.disableWebGL) {
  5629. return false;
  5630. }
  5631. var enabled = false;
  5632. try {
  5633. generateGL();
  5634. enabled = !!currentGL;
  5635. } catch (e) { }
  5636. return shadow(this, 'isEnabled', enabled);
  5637. },
  5638. composeSMask: composeSMask,
  5639. drawFigures: drawFigures,
  5640. clear: cleanup
  5641. };
  5642. })();
  5643. var ShadingIRs = {};
  5644. ShadingIRs.RadialAxial = {
  5645. fromIR: function RadialAxial_fromIR(raw) {
  5646. var type = raw[1];
  5647. var colorStops = raw[2];
  5648. var p0 = raw[3];
  5649. var p1 = raw[4];
  5650. var r0 = raw[5];
  5651. var r1 = raw[6];
  5652. return {
  5653. type: 'Pattern',
  5654. getPattern: function RadialAxial_getPattern(ctx) {
  5655. var grad;
  5656. if (type === 'axial') {
  5657. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5658. } else if (type === 'radial') {
  5659. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5660. }
  5661. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5662. var c = colorStops[i];
  5663. grad.addColorStop(c[0], c[1]);
  5664. }
  5665. return grad;
  5666. }
  5667. };
  5668. }
  5669. };
  5670. var createMeshCanvas = (function createMeshCanvasClosure() {
  5671. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5672. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5673. var coords = context.coords, colors = context.colors;
  5674. var bytes = data.data, rowSize = data.width * 4;
  5675. var tmp;
  5676. if (coords[p1 + 1] > coords[p2 + 1]) {
  5677. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5678. }
  5679. if (coords[p2 + 1] > coords[p3 + 1]) {
  5680. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5681. }
  5682. if (coords[p1 + 1] > coords[p2 + 1]) {
  5683. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5684. }
  5685. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5686. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5687. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5688. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5689. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5690. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5691. if (y1 >= y3) {
  5692. return;
  5693. }
  5694. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5695. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5696. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5697. var minY = Math.round(y1), maxY = Math.round(y3);
  5698. var xa, car, cag, cab;
  5699. var xb, cbr, cbg, cbb;
  5700. var k;
  5701. for (var y = minY; y <= maxY; y++) {
  5702. if (y < y2) {
  5703. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5704. xa = x1 - (x1 - x2) * k;
  5705. car = c1r - (c1r - c2r) * k;
  5706. cag = c1g - (c1g - c2g) * k;
  5707. cab = c1b - (c1b - c2b) * k;
  5708. } else {
  5709. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5710. xa = x2 - (x2 - x3) * k;
  5711. car = c2r - (c2r - c3r) * k;
  5712. cag = c2g - (c2g - c3g) * k;
  5713. cab = c2b - (c2b - c3b) * k;
  5714. }
  5715. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5716. xb = x1 - (x1 - x3) * k;
  5717. cbr = c1r - (c1r - c3r) * k;
  5718. cbg = c1g - (c1g - c3g) * k;
  5719. cbb = c1b - (c1b - c3b) * k;
  5720. var x1_ = Math.round(Math.min(xa, xb));
  5721. var x2_ = Math.round(Math.max(xa, xb));
  5722. var j = rowSize * y + x1_ * 4;
  5723. for (var x = x1_; x <= x2_; x++) {
  5724. k = (xa - x) / (xa - xb);
  5725. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5726. bytes[j++] = (car - (car - cbr) * k) | 0;
  5727. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5728. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5729. bytes[j++] = 255;
  5730. }
  5731. }
  5732. }
  5733. function drawFigure(data, figure, context) {
  5734. var ps = figure.coords;
  5735. var cs = figure.colors;
  5736. var i, ii;
  5737. switch (figure.type) {
  5738. case 'lattice':
  5739. var verticesPerRow = figure.verticesPerRow;
  5740. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5741. var cols = verticesPerRow - 1;
  5742. for (i = 0; i < rows; i++) {
  5743. var q = i * verticesPerRow;
  5744. for (var j = 0; j < cols; j++, q++) {
  5745. drawTriangle(data, context,
  5746. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5747. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5748. drawTriangle(data, context,
  5749. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5750. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5751. }
  5752. }
  5753. break;
  5754. case 'triangles':
  5755. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5756. drawTriangle(data, context,
  5757. ps[i], ps[i + 1], ps[i + 2],
  5758. cs[i], cs[i + 1], cs[i + 2]);
  5759. }
  5760. break;
  5761. default:
  5762. error('illigal figure');
  5763. break;
  5764. }
  5765. }
  5766. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5767. backgroundColor, cachedCanvases) {
  5768. // we will increase scale on some weird factor to let antialiasing take
  5769. // care of "rough" edges
  5770. var EXPECTED_SCALE = 1.1;
  5771. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5772. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5773. var offsetX = Math.floor(bounds[0]);
  5774. var offsetY = Math.floor(bounds[1]);
  5775. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5776. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5777. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5778. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5779. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5780. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5781. var scaleX = boundsWidth / width;
  5782. var scaleY = boundsHeight / height;
  5783. var context = {
  5784. coords: coords,
  5785. colors: colors,
  5786. offsetX: -offsetX,
  5787. offsetY: -offsetY,
  5788. scaleX: 1 / scaleX,
  5789. scaleY: 1 / scaleY
  5790. };
  5791. var canvas, tmpCanvas, i, ii;
  5792. if (WebGLUtils.isEnabled) {
  5793. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5794. figures, context);
  5795. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5796. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5797. tmpCanvas.context.drawImage(canvas, 0, 0);
  5798. canvas = tmpCanvas.canvas;
  5799. } else {
  5800. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5801. var tmpCtx = tmpCanvas.context;
  5802. var data = tmpCtx.createImageData(width, height);
  5803. if (backgroundColor) {
  5804. var bytes = data.data;
  5805. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5806. bytes[i] = backgroundColor[0];
  5807. bytes[i + 1] = backgroundColor[1];
  5808. bytes[i + 2] = backgroundColor[2];
  5809. bytes[i + 3] = 255;
  5810. }
  5811. }
  5812. for (i = 0; i < figures.length; i++) {
  5813. drawFigure(data, figures[i], context);
  5814. }
  5815. tmpCtx.putImageData(data, 0, 0);
  5816. canvas = tmpCanvas.canvas;
  5817. }
  5818. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5819. scaleX: scaleX, scaleY: scaleY};
  5820. }
  5821. return createMeshCanvas;
  5822. })();
  5823. ShadingIRs.Mesh = {
  5824. fromIR: function Mesh_fromIR(raw) {
  5825. //var type = raw[1];
  5826. var coords = raw[2];
  5827. var colors = raw[3];
  5828. var figures = raw[4];
  5829. var bounds = raw[5];
  5830. var matrix = raw[6];
  5831. //var bbox = raw[7];
  5832. var background = raw[8];
  5833. return {
  5834. type: 'Pattern',
  5835. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5836. var scale;
  5837. if (shadingFill) {
  5838. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5839. } else {
  5840. // Obtain scale from matrix and current transformation matrix.
  5841. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5842. if (matrix) {
  5843. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5844. scale = [scale[0] * matrixScale[0],
  5845. scale[1] * matrixScale[1]];
  5846. }
  5847. }
  5848. // Rasterizing on the main thread since sending/queue large canvases
  5849. // might cause OOM.
  5850. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5851. colors, figures, shadingFill ? null : background,
  5852. owner.cachedCanvases);
  5853. if (!shadingFill) {
  5854. ctx.setTransform.apply(ctx, owner.baseTransform);
  5855. if (matrix) {
  5856. ctx.transform.apply(ctx, matrix);
  5857. }
  5858. }
  5859. ctx.translate(temporaryPatternCanvas.offsetX,
  5860. temporaryPatternCanvas.offsetY);
  5861. ctx.scale(temporaryPatternCanvas.scaleX,
  5862. temporaryPatternCanvas.scaleY);
  5863. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5864. }
  5865. };
  5866. }
  5867. };
  5868. ShadingIRs.Dummy = {
  5869. fromIR: function Dummy_fromIR() {
  5870. return {
  5871. type: 'Pattern',
  5872. getPattern: function Dummy_fromIR_getPattern() {
  5873. return 'hotpink';
  5874. }
  5875. };
  5876. }
  5877. };
  5878. function getShadingPatternFromIR(raw) {
  5879. var shadingIR = ShadingIRs[raw[0]];
  5880. if (!shadingIR) {
  5881. error('Unknown IR type: ' + raw[0]);
  5882. }
  5883. return shadingIR.fromIR(raw);
  5884. }
  5885. var TilingPattern = (function TilingPatternClosure() {
  5886. var PaintType = {
  5887. COLORED: 1,
  5888. UNCOLORED: 2
  5889. };
  5890. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5891. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5892. this.operatorList = IR[2];
  5893. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5894. this.bbox = IR[4];
  5895. this.xstep = IR[5];
  5896. this.ystep = IR[6];
  5897. this.paintType = IR[7];
  5898. this.tilingType = IR[8];
  5899. this.color = color;
  5900. this.objs = objs;
  5901. this.commonObjs = commonObjs;
  5902. this.baseTransform = baseTransform;
  5903. this.type = 'Pattern';
  5904. this.ctx = ctx;
  5905. }
  5906. TilingPattern.prototype = {
  5907. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5908. var operatorList = this.operatorList;
  5909. var bbox = this.bbox;
  5910. var xstep = this.xstep;
  5911. var ystep = this.ystep;
  5912. var paintType = this.paintType;
  5913. var tilingType = this.tilingType;
  5914. var color = this.color;
  5915. var objs = this.objs;
  5916. var commonObjs = this.commonObjs;
  5917. info('TilingType: ' + tilingType);
  5918. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5919. var topLeft = [x0, y0];
  5920. // we want the canvas to be as large as the step size
  5921. var botRight = [x0 + xstep, y0 + ystep];
  5922. var width = botRight[0] - topLeft[0];
  5923. var height = botRight[1] - topLeft[1];
  5924. // Obtain scale from matrix and current transformation matrix.
  5925. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5926. var curMatrixScale = Util.singularValueDecompose2dScale(
  5927. this.baseTransform);
  5928. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5929. matrixScale[1] * curMatrixScale[1]];
  5930. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5931. // Use width and height values that are as close as possible to the end
  5932. // result when the pattern is used. Too low value makes the pattern look
  5933. // blurry. Too large value makes it look too crispy.
  5934. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5935. MAX_PATTERN_SIZE);
  5936. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5937. MAX_PATTERN_SIZE);
  5938. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5939. width, height, true);
  5940. var tmpCtx = tmpCanvas.context;
  5941. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5942. graphics.groupLevel = owner.groupLevel;
  5943. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5944. this.setScale(width, height, xstep, ystep);
  5945. this.transformToScale(graphics);
  5946. // transform coordinates to pattern space
  5947. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5948. graphics.transform.apply(graphics, tmpTranslate);
  5949. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5950. graphics.executeOperatorList(operatorList);
  5951. return tmpCanvas.canvas;
  5952. },
  5953. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5954. this.scale = [width / xstep, height / ystep];
  5955. },
  5956. transformToScale: function TilingPattern_transformToScale(graphics) {
  5957. var scale = this.scale;
  5958. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5959. graphics.transform.apply(graphics, tmpScale);
  5960. },
  5961. scaleToContext: function TilingPattern_scaleToContext() {
  5962. var scale = this.scale;
  5963. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5964. },
  5965. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5966. if (bbox && isArray(bbox) && bbox.length === 4) {
  5967. var bboxWidth = x1 - x0;
  5968. var bboxHeight = y1 - y0;
  5969. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5970. graphics.clip();
  5971. graphics.endPath();
  5972. }
  5973. },
  5974. setFillAndStrokeStyleToContext:
  5975. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5976. switch (paintType) {
  5977. case PaintType.COLORED:
  5978. var ctx = this.ctx;
  5979. context.fillStyle = ctx.fillStyle;
  5980. context.strokeStyle = ctx.strokeStyle;
  5981. break;
  5982. case PaintType.UNCOLORED:
  5983. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5984. context.fillStyle = cssColor;
  5985. context.strokeStyle = cssColor;
  5986. break;
  5987. default:
  5988. error('Unsupported paint type: ' + paintType);
  5989. }
  5990. },
  5991. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5992. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5993. ctx = this.ctx;
  5994. ctx.setTransform.apply(ctx, this.baseTransform);
  5995. ctx.transform.apply(ctx, this.matrix);
  5996. this.scaleToContext();
  5997. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5998. }
  5999. };
  6000. return TilingPattern;
  6001. })();
  6002. function FontLoader(docId) {
  6003. this.docId = docId;
  6004. this.styleElement = null;
  6005. this.nativeFontFaces = [];
  6006. this.loadTestFontId = 0;
  6007. this.loadingContext = {
  6008. requests: [],
  6009. nextRequestId: 0
  6010. };
  6011. }
  6012. FontLoader.prototype = {
  6013. insertRule: function fontLoaderInsertRule(rule) {
  6014. var styleElement = this.styleElement;
  6015. if (!styleElement) {
  6016. styleElement = this.styleElement = document.createElement('style');
  6017. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  6018. document.documentElement.getElementsByTagName('head')[0].appendChild(
  6019. styleElement);
  6020. }
  6021. var styleSheet = styleElement.sheet;
  6022. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  6023. },
  6024. clear: function fontLoaderClear() {
  6025. var styleElement = this.styleElement;
  6026. if (styleElement) {
  6027. styleElement.parentNode.removeChild(styleElement);
  6028. styleElement = this.styleElement = null;
  6029. }
  6030. this.nativeFontFaces.forEach(function(nativeFontFace) {
  6031. document.fonts.delete(nativeFontFace);
  6032. });
  6033. this.nativeFontFaces.length = 0;
  6034. },
  6035. get loadTestFont() {
  6036. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  6037. // height.
  6038. return shadow(this, 'loadTestFont', atob(
  6039. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  6040. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  6041. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  6042. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  6043. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  6044. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  6045. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  6046. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  6047. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  6048. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  6049. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  6050. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  6051. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  6052. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  6053. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  6054. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  6055. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  6056. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  6057. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  6058. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  6059. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  6060. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  6061. ));
  6062. },
  6063. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  6064. this.nativeFontFaces.push(nativeFontFace);
  6065. document.fonts.add(nativeFontFace);
  6066. },
  6067. bind: function fontLoaderBind(fonts, callback) {
  6068. assert(!isWorker, 'bind() shall be called from main thread');
  6069. var rules = [];
  6070. var fontsToLoad = [];
  6071. var fontLoadPromises = [];
  6072. var getNativeFontPromise = function(nativeFontFace) {
  6073. // Return a promise that is always fulfilled, even when the font fails to
  6074. // load.
  6075. return nativeFontFace.loaded.catch(function(e) {
  6076. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  6077. });
  6078. };
  6079. for (var i = 0, ii = fonts.length; i < ii; i++) {
  6080. var font = fonts[i];
  6081. // Add the font to the DOM only once or skip if the font
  6082. // is already loaded.
  6083. if (font.attached || font.loading === false) {
  6084. continue;
  6085. }
  6086. font.attached = true;
  6087. if (FontLoader.isFontLoadingAPISupported) {
  6088. var nativeFontFace = font.createNativeFontFace();
  6089. if (nativeFontFace) {
  6090. this.addNativeFontFace(nativeFontFace);
  6091. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  6092. }
  6093. } else {
  6094. var rule = font.createFontFaceRule();
  6095. if (rule) {
  6096. this.insertRule(rule);
  6097. rules.push(rule);
  6098. fontsToLoad.push(font);
  6099. }
  6100. }
  6101. }
  6102. var request = this.queueLoadingCallback(callback);
  6103. if (FontLoader.isFontLoadingAPISupported) {
  6104. Promise.all(fontLoadPromises).then(function() {
  6105. request.complete();
  6106. });
  6107. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  6108. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  6109. } else {
  6110. request.complete();
  6111. }
  6112. },
  6113. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  6114. function LoadLoader_completeRequest() {
  6115. assert(!request.end, 'completeRequest() cannot be called twice');
  6116. request.end = Date.now();
  6117. // sending all completed requests in order how they were queued
  6118. while (context.requests.length > 0 && context.requests[0].end) {
  6119. var otherRequest = context.requests.shift();
  6120. setTimeout(otherRequest.callback, 0);
  6121. }
  6122. }
  6123. var context = this.loadingContext;
  6124. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  6125. var request = {
  6126. id: requestId,
  6127. complete: LoadLoader_completeRequest,
  6128. callback: callback,
  6129. started: Date.now()
  6130. };
  6131. context.requests.push(request);
  6132. return request;
  6133. },
  6134. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  6135. fonts,
  6136. request) {
  6137. /** Hack begin */
  6138. // There's currently no event when a font has finished downloading so the
  6139. // following code is a dirty hack to 'guess' when a font is
  6140. // ready. It's assumed fonts are loaded in order, so add a known test
  6141. // font after the desired fonts and then test for the loading of that
  6142. // test font.
  6143. function int32(data, offset) {
  6144. return (data.charCodeAt(offset) << 24) |
  6145. (data.charCodeAt(offset + 1) << 16) |
  6146. (data.charCodeAt(offset + 2) << 8) |
  6147. (data.charCodeAt(offset + 3) & 0xff);
  6148. }
  6149. function spliceString(s, offset, remove, insert) {
  6150. var chunk1 = s.substr(0, offset);
  6151. var chunk2 = s.substr(offset + remove);
  6152. return chunk1 + insert + chunk2;
  6153. }
  6154. var i, ii;
  6155. var canvas = document.createElement('canvas');
  6156. canvas.width = 1;
  6157. canvas.height = 1;
  6158. var ctx = canvas.getContext('2d');
  6159. var called = 0;
  6160. function isFontReady(name, callback) {
  6161. called++;
  6162. // With setTimeout clamping this gives the font ~100ms to load.
  6163. if(called > 30) {
  6164. warn('Load test font never loaded.');
  6165. callback();
  6166. return;
  6167. }
  6168. ctx.font = '30px ' + name;
  6169. ctx.fillText('.', 0, 20);
  6170. var imageData = ctx.getImageData(0, 0, 1, 1);
  6171. if (imageData.data[3] > 0) {
  6172. callback();
  6173. return;
  6174. }
  6175. setTimeout(isFontReady.bind(null, name, callback));
  6176. }
  6177. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  6178. // Chromium seems to cache fonts based on a hash of the actual font data,
  6179. // so the font must be modified for each load test else it will appear to
  6180. // be loaded already.
  6181. // TODO: This could maybe be made faster by avoiding the btoa of the full
  6182. // font by splitting it in chunks before hand and padding the font id.
  6183. var data = this.loadTestFont;
  6184. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  6185. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  6186. loadTestFontId);
  6187. // CFF checksum is important for IE, adjusting it
  6188. var CFF_CHECKSUM_OFFSET = 16;
  6189. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  6190. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  6191. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  6192. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  6193. }
  6194. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  6195. checksum = (checksum - XXXX_VALUE +
  6196. int32(loadTestFontId + 'XXX', i)) | 0;
  6197. }
  6198. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  6199. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  6200. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  6201. url + '}';
  6202. this.insertRule(rule);
  6203. var names = [];
  6204. for (i = 0, ii = fonts.length; i < ii; i++) {
  6205. names.push(fonts[i].loadedName);
  6206. }
  6207. names.push(loadTestFontId);
  6208. var div = document.createElement('div');
  6209. div.setAttribute('style',
  6210. 'visibility: hidden;' +
  6211. 'width: 10px; height: 10px;' +
  6212. 'position: absolute; top: 0px; left: 0px;');
  6213. for (i = 0, ii = names.length; i < ii; ++i) {
  6214. var span = document.createElement('span');
  6215. span.textContent = 'Hi';
  6216. span.style.fontFamily = names[i];
  6217. div.appendChild(span);
  6218. }
  6219. document.body.appendChild(div);
  6220. isFontReady(loadTestFontId, function() {
  6221. document.body.removeChild(div);
  6222. request.complete();
  6223. });
  6224. /** Hack end */
  6225. }
  6226. };
  6227. FontLoader.isFontLoadingAPISupported = (!isWorker &&
  6228. typeof document !== 'undefined' && !!document.fonts);
  6229. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  6230. get: function () {
  6231. var supported = false;
  6232. // User agent string sniffing is bad, but there is no reliable way to tell
  6233. // if font is fully loaded and ready to be used with canvas.
  6234. var userAgent = window.navigator.userAgent;
  6235. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  6236. if (m && m[1] >= 14) {
  6237. supported = true;
  6238. }
  6239. // TODO other browsers
  6240. if (userAgent === 'node') {
  6241. supported = true;
  6242. }
  6243. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  6244. },
  6245. enumerable: true,
  6246. configurable: true
  6247. });
  6248. var FontFaceObject = (function FontFaceObjectClosure() {
  6249. function FontFaceObject(translatedData) {
  6250. this.compiledGlyphs = {};
  6251. // importing translated data
  6252. for (var i in translatedData) {
  6253. this[i] = translatedData[i];
  6254. }
  6255. }
  6256. Object.defineProperty(FontFaceObject, 'isEvalSupported', {
  6257. get: function () {
  6258. var evalSupport = false;
  6259. if (PDFJS.isEvalSupported) {
  6260. try {
  6261. /* jshint evil: true */
  6262. new Function('');
  6263. evalSupport = true;
  6264. } catch (e) {}
  6265. }
  6266. return shadow(this, 'isEvalSupported', evalSupport);
  6267. },
  6268. enumerable: true,
  6269. configurable: true
  6270. });
  6271. FontFaceObject.prototype = {
  6272. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  6273. if (!this.data) {
  6274. return null;
  6275. }
  6276. if (PDFJS.disableFontFace) {
  6277. this.disableFontFace = true;
  6278. return null;
  6279. }
  6280. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  6281. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  6282. globalScope['FontInspector'].enabled) {
  6283. globalScope['FontInspector'].fontAdded(this);
  6284. }
  6285. return nativeFontFace;
  6286. },
  6287. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  6288. if (!this.data) {
  6289. return null;
  6290. }
  6291. if (PDFJS.disableFontFace) {
  6292. this.disableFontFace = true;
  6293. return null;
  6294. }
  6295. var data = bytesToString(new Uint8Array(this.data));
  6296. var fontName = this.loadedName;
  6297. // Add the font-face rule to the document
  6298. var url = ('url(data:' + this.mimetype + ';base64,' +
  6299. window.btoa(data) + ');');
  6300. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  6301. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  6302. globalScope['FontInspector'].enabled) {
  6303. globalScope['FontInspector'].fontAdded(this, url);
  6304. }
  6305. return rule;
  6306. },
  6307. getPathGenerator:
  6308. function FontFaceObject_getPathGenerator(objs, character) {
  6309. if (!(character in this.compiledGlyphs)) {
  6310. var cmds = objs.get(this.loadedName + '_path_' + character);
  6311. var current, i, len;
  6312. // If we can, compile cmds into JS for MAXIMUM SPEED
  6313. if (FontFaceObject.isEvalSupported) {
  6314. var args, js = '';
  6315. for (i = 0, len = cmds.length; i < len; i++) {
  6316. current = cmds[i];
  6317. if (current.args !== undefined) {
  6318. args = current.args.join(',');
  6319. } else {
  6320. args = '';
  6321. }
  6322. js += 'c.' + current.cmd + '(' + args + ');\n';
  6323. }
  6324. /* jshint -W054 */
  6325. this.compiledGlyphs[character] = new Function('c', 'size', js);
  6326. } else {
  6327. // But fall back on using Function.prototype.apply() if we're
  6328. // blocked from using eval() for whatever reason (like CSP policies)
  6329. this.compiledGlyphs[character] = function(c, size) {
  6330. for (i = 0, len = cmds.length; i < len; i++) {
  6331. current = cmds[i];
  6332. if (current.cmd === 'scale') {
  6333. current.args = [size, -size];
  6334. }
  6335. c[current.cmd].apply(c, current.args);
  6336. }
  6337. };
  6338. }
  6339. }
  6340. return this.compiledGlyphs[character];
  6341. }
  6342. };
  6343. return FontFaceObject;
  6344. })();
  6345. /**
  6346. * Optimised CSS custom property getter/setter.
  6347. * @class
  6348. */
  6349. var CustomStyle = (function CustomStyleClosure() {
  6350. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  6351. // animate-css-transforms-firefox-webkit.html
  6352. // in some versions of IE9 it is critical that ms appear in this list
  6353. // before Moz
  6354. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  6355. var _cache = {};
  6356. function CustomStyle() {}
  6357. CustomStyle.getProp = function get(propName, element) {
  6358. // check cache only when no element is given
  6359. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  6360. return _cache[propName];
  6361. }
  6362. element = element || document.documentElement;
  6363. var style = element.style, prefixed, uPropName;
  6364. // test standard property first
  6365. if (typeof style[propName] === 'string') {
  6366. return (_cache[propName] = propName);
  6367. }
  6368. // capitalize
  6369. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  6370. // test vendor specific properties
  6371. for (var i = 0, l = prefixes.length; i < l; i++) {
  6372. prefixed = prefixes[i] + uPropName;
  6373. if (typeof style[prefixed] === 'string') {
  6374. return (_cache[propName] = prefixed);
  6375. }
  6376. }
  6377. //if all fails then set to undefined
  6378. return (_cache[propName] = 'undefined');
  6379. };
  6380. CustomStyle.setProp = function set(propName, element, str) {
  6381. var prop = this.getProp(propName);
  6382. if (prop !== 'undefined') {
  6383. element.style[prop] = str;
  6384. }
  6385. };
  6386. return CustomStyle;
  6387. })();
  6388. PDFJS.CustomStyle = CustomStyle;
  6389. var ANNOT_MIN_SIZE = 10; // px
  6390. var AnnotationUtils = (function AnnotationUtilsClosure() {
  6391. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  6392. function setTextStyles(element, item, fontObj) {
  6393. var style = element.style;
  6394. style.fontSize = item.fontSize + 'px';
  6395. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  6396. if (!fontObj) {
  6397. return;
  6398. }
  6399. style.fontWeight = fontObj.black ?
  6400. (fontObj.bold ? 'bolder' : 'bold') :
  6401. (fontObj.bold ? 'bold' : 'normal');
  6402. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  6403. var fontName = fontObj.loadedName;
  6404. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  6405. // Use a reasonable default font if the font doesn't specify a fallback
  6406. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  6407. style.fontFamily = fontFamily + fallbackName;
  6408. }
  6409. function initContainer(item) {
  6410. var container = document.createElement('section');
  6411. var cstyle = container.style;
  6412. var width = item.rect[2] - item.rect[0];
  6413. var height = item.rect[3] - item.rect[1];
  6414. // Border
  6415. if (item.borderStyle.width > 0) {
  6416. // Border width
  6417. container.style.borderWidth = item.borderStyle.width + 'px';
  6418. if (item.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  6419. // Underline styles only have a bottom border, so we do not need
  6420. // to adjust for all borders. This yields a similar result as
  6421. // Adobe Acrobat/Reader.
  6422. width = width - 2 * item.borderStyle.width;
  6423. height = height - 2 * item.borderStyle.width;
  6424. }
  6425. // Horizontal and vertical border radius
  6426. var horizontalRadius = item.borderStyle.horizontalCornerRadius;
  6427. var verticalRadius = item.borderStyle.verticalCornerRadius;
  6428. if (horizontalRadius > 0 || verticalRadius > 0) {
  6429. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  6430. CustomStyle.setProp('borderRadius', container, radius);
  6431. }
  6432. // Border style
  6433. switch (item.borderStyle.style) {
  6434. case AnnotationBorderStyleType.SOLID:
  6435. container.style.borderStyle = 'solid';
  6436. break;
  6437. case AnnotationBorderStyleType.DASHED:
  6438. container.style.borderStyle = 'dashed';
  6439. break;
  6440. case AnnotationBorderStyleType.BEVELED:
  6441. warn('Unimplemented border style: beveled');
  6442. break;
  6443. case AnnotationBorderStyleType.INSET:
  6444. warn('Unimplemented border style: inset');
  6445. break;
  6446. case AnnotationBorderStyleType.UNDERLINE:
  6447. container.style.borderBottomStyle = 'solid';
  6448. break;
  6449. default:
  6450. break;
  6451. }
  6452. // Border color
  6453. if (item.color) {
  6454. container.style.borderColor =
  6455. Util.makeCssRgb(item.color[0] | 0,
  6456. item.color[1] | 0,
  6457. item.color[2] | 0);
  6458. } else {
  6459. // Transparent (invisible) border, so do not draw it at all.
  6460. container.style.borderWidth = 0;
  6461. }
  6462. }
  6463. cstyle.width = width + 'px';
  6464. cstyle.height = height + 'px';
  6465. return container;
  6466. }
  6467. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  6468. var element = document.createElement('div');
  6469. var width = item.rect[2] - item.rect[0];
  6470. var height = item.rect[3] - item.rect[1];
  6471. element.style.width = width + 'px';
  6472. element.style.height = height + 'px';
  6473. element.style.display = 'table';
  6474. var content = document.createElement('div');
  6475. content.textContent = item.fieldValue;
  6476. var textAlignment = item.textAlignment;
  6477. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  6478. content.style.verticalAlign = 'middle';
  6479. content.style.display = 'table-cell';
  6480. var fontObj = item.fontRefName ?
  6481. commonObjs.getData(item.fontRefName) : null;
  6482. setTextStyles(content, item, fontObj);
  6483. element.appendChild(content);
  6484. return element;
  6485. }
  6486. function getHtmlElementForTextAnnotation(item) {
  6487. var rect = item.rect;
  6488. // sanity check because of OOo-generated PDFs
  6489. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  6490. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  6491. }
  6492. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  6493. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  6494. }
  6495. var container = initContainer(item);
  6496. container.className = 'annotText';
  6497. var image = document.createElement('img');
  6498. image.style.height = container.style.height;
  6499. image.style.width = container.style.width;
  6500. var iconName = item.name;
  6501. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  6502. iconName.toLowerCase() + '.svg';
  6503. image.alt = '[{{type}} Annotation]';
  6504. image.dataset.l10nId = 'text_annotation_type';
  6505. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  6506. var contentWrapper = document.createElement('div');
  6507. contentWrapper.className = 'annotTextContentWrapper';
  6508. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  6509. contentWrapper.style.top = '-10px';
  6510. var content = document.createElement('div');
  6511. content.className = 'annotTextContent';
  6512. content.setAttribute('hidden', true);
  6513. var i, ii;
  6514. if (item.hasBgColor && item.color) {
  6515. var color = item.color;
  6516. // Enlighten the color (70%)
  6517. var BACKGROUND_ENLIGHT = 0.7;
  6518. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  6519. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  6520. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  6521. content.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  6522. }
  6523. var title = document.createElement('h1');
  6524. var text = document.createElement('p');
  6525. title.textContent = item.title;
  6526. if (!item.content && !item.title) {
  6527. content.setAttribute('hidden', true);
  6528. } else {
  6529. var e = document.createElement('span');
  6530. var lines = item.content.split(/(?:\r\n?|\n)/);
  6531. for (i = 0, ii = lines.length; i < ii; ++i) {
  6532. var line = lines[i];
  6533. e.appendChild(document.createTextNode(line));
  6534. if (i < (ii - 1)) {
  6535. e.appendChild(document.createElement('br'));
  6536. }
  6537. }
  6538. text.appendChild(e);
  6539. var pinned = false;
  6540. var showAnnotation = function showAnnotation(pin) {
  6541. if (pin) {
  6542. pinned = true;
  6543. }
  6544. if (content.hasAttribute('hidden')) {
  6545. container.style.zIndex += 1;
  6546. content.removeAttribute('hidden');
  6547. }
  6548. };
  6549. var hideAnnotation = function hideAnnotation(unpin) {
  6550. if (unpin) {
  6551. pinned = false;
  6552. }
  6553. if (!content.hasAttribute('hidden') && !pinned) {
  6554. container.style.zIndex -= 1;
  6555. content.setAttribute('hidden', true);
  6556. }
  6557. };
  6558. var toggleAnnotation = function toggleAnnotation() {
  6559. if (pinned) {
  6560. hideAnnotation(true);
  6561. } else {
  6562. showAnnotation(true);
  6563. }
  6564. };
  6565. image.addEventListener('click', function image_clickHandler() {
  6566. toggleAnnotation();
  6567. }, false);
  6568. image.addEventListener('mouseover', function image_mouseOverHandler() {
  6569. showAnnotation();
  6570. }, false);
  6571. image.addEventListener('mouseout', function image_mouseOutHandler() {
  6572. hideAnnotation();
  6573. }, false);
  6574. content.addEventListener('click', function content_clickHandler() {
  6575. hideAnnotation(true);
  6576. }, false);
  6577. }
  6578. content.appendChild(title);
  6579. content.appendChild(text);
  6580. contentWrapper.appendChild(content);
  6581. container.appendChild(image);
  6582. container.appendChild(contentWrapper);
  6583. return container;
  6584. }
  6585. function getHtmlElementForLinkAnnotation(item) {
  6586. var container = initContainer(item);
  6587. container.className = 'annotLink';
  6588. var link = document.createElement('a');
  6589. link.href = link.title = item.url || '';
  6590. if (item.url && isExternalLinkTargetSet()) {
  6591. link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];
  6592. }
  6593. container.appendChild(link);
  6594. return container;
  6595. }
  6596. function getHtmlElement(data, objs) {
  6597. switch (data.annotationType) {
  6598. case AnnotationType.WIDGET:
  6599. return getHtmlElementForTextWidgetAnnotation(data, objs);
  6600. case AnnotationType.TEXT:
  6601. return getHtmlElementForTextAnnotation(data);
  6602. case AnnotationType.LINK:
  6603. return getHtmlElementForLinkAnnotation(data);
  6604. default:
  6605. throw new Error('Unsupported annotationType: ' + data.annotationType);
  6606. }
  6607. }
  6608. return {
  6609. getHtmlElement: getHtmlElement
  6610. };
  6611. })();
  6612. PDFJS.AnnotationUtils = AnnotationUtils;
  6613. /**
  6614. * Text layer render parameters.
  6615. *
  6616. * @typedef {Object} TextLayerRenderParameters
  6617. * @property {TextContent} textContent - Text content to render (the object is
  6618. * returned by the page's getTextContent() method).
  6619. * @property {HTMLElement} container - HTML element that will contain text runs.
  6620. * @property {PDFJS.PageViewport} viewport - The target viewport to properly
  6621. * layout the text runs.
  6622. * @property {Array} textDivs - (optional) HTML elements that are correspond
  6623. * the text items of the textContent input. This is output and shall be
  6624. * initially be set to empty array.
  6625. * @property {number} timeout - (optional) Delay in milliseconds before
  6626. * rendering of the text runs occurs.
  6627. */
  6628. var renderTextLayer = (function renderTextLayerClosure() {
  6629. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  6630. var NonWhitespaceRegexp = /\S/;
  6631. function isAllWhitespace(str) {
  6632. return !NonWhitespaceRegexp.test(str);
  6633. }
  6634. function appendText(textDivs, viewport, geom, styles) {
  6635. var style = styles[geom.fontName];
  6636. var textDiv = document.createElement('div');
  6637. textDivs.push(textDiv);
  6638. if (isAllWhitespace(geom.str)) {
  6639. textDiv.dataset.isWhitespace = true;
  6640. return;
  6641. }
  6642. var tx = PDFJS.Util.transform(viewport.transform, geom.transform);
  6643. var angle = Math.atan2(tx[1], tx[0]);
  6644. if (style.vertical) {
  6645. angle += Math.PI / 2;
  6646. }
  6647. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  6648. var fontAscent = fontHeight;
  6649. if (style.ascent) {
  6650. fontAscent = style.ascent * fontAscent;
  6651. } else if (style.descent) {
  6652. fontAscent = (1 + style.descent) * fontAscent;
  6653. }
  6654. var left;
  6655. var top;
  6656. if (angle === 0) {
  6657. left = tx[4];
  6658. top = tx[5] - fontAscent;
  6659. } else {
  6660. left = tx[4] + (fontAscent * Math.sin(angle));
  6661. top = tx[5] - (fontAscent * Math.cos(angle));
  6662. }
  6663. textDiv.style.left = left + 'px';
  6664. textDiv.style.top = top + 'px';
  6665. textDiv.style.fontSize = fontHeight + 'px';
  6666. textDiv.style.fontFamily = style.fontFamily;
  6667. textDiv.textContent = geom.str;
  6668. // |fontName| is only used by the Font Inspector. This test will succeed
  6669. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  6670. // not worth the effort to do a more accurate test.
  6671. if (PDFJS.pdfBug) {
  6672. textDiv.dataset.fontName = geom.fontName;
  6673. }
  6674. // Storing into dataset will convert number into string.
  6675. if (angle !== 0) {
  6676. textDiv.dataset.angle = angle * (180 / Math.PI);
  6677. }
  6678. // We don't bother scaling single-char text divs, because it has very
  6679. // little effect on text highlighting. This makes scrolling on docs with
  6680. // lots of such divs a lot faster.
  6681. if (geom.str.length > 1) {
  6682. if (style.vertical) {
  6683. textDiv.dataset.canvasWidth = geom.height * viewport.scale;
  6684. } else {
  6685. textDiv.dataset.canvasWidth = geom.width * viewport.scale;
  6686. }
  6687. }
  6688. }
  6689. function render(task) {
  6690. if (task._canceled) {
  6691. return;
  6692. }
  6693. var textLayerFrag = task._container;
  6694. var textDivs = task._textDivs;
  6695. var capability = task._capability;
  6696. var textDivsLength = textDivs.length;
  6697. // No point in rendering many divs as it would make the browser
  6698. // unusable even after the divs are rendered.
  6699. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  6700. capability.resolve();
  6701. return;
  6702. }
  6703. var canvas = document.createElement('canvas');
  6704. canvas.mozOpaque = true;
  6705. var ctx = canvas.getContext('2d', {alpha: false});
  6706. var lastFontSize;
  6707. var lastFontFamily;
  6708. for (var i = 0; i < textDivsLength; i++) {
  6709. var textDiv = textDivs[i];
  6710. if (textDiv.dataset.isWhitespace !== undefined) {
  6711. continue;
  6712. }
  6713. var fontSize = textDiv.style.fontSize;
  6714. var fontFamily = textDiv.style.fontFamily;
  6715. // Only build font string and set to context if different from last.
  6716. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  6717. ctx.font = fontSize + ' ' + fontFamily;
  6718. lastFontSize = fontSize;
  6719. lastFontFamily = fontFamily;
  6720. }
  6721. var width = ctx.measureText(textDiv.textContent).width;
  6722. if (width > 0) {
  6723. textLayerFrag.appendChild(textDiv);
  6724. var transform;
  6725. if (textDiv.dataset.canvasWidth !== undefined) {
  6726. // Dataset values come of type string.
  6727. var textScale = textDiv.dataset.canvasWidth / width;
  6728. transform = 'scaleX(' + textScale + ')';
  6729. } else {
  6730. transform = '';
  6731. }
  6732. var rotation = textDiv.dataset.angle;
  6733. if (rotation) {
  6734. transform = 'rotate(' + rotation + 'deg) ' + transform;
  6735. }
  6736. if (transform) {
  6737. PDFJS.CustomStyle.setProp('transform' , textDiv, transform);
  6738. }
  6739. }
  6740. }
  6741. capability.resolve();
  6742. }
  6743. /**
  6744. * Text layer rendering task.
  6745. *
  6746. * @param {TextContent} textContent
  6747. * @param {HTMLElement} container
  6748. * @param {PDFJS.PageViewport} viewport
  6749. * @param {Array} textDivs
  6750. * @private
  6751. */
  6752. function TextLayerRenderTask(textContent, container, viewport, textDivs) {
  6753. this._textContent = textContent;
  6754. this._container = container;
  6755. this._viewport = viewport;
  6756. textDivs = textDivs || [];
  6757. this._textDivs = textDivs;
  6758. this._canceled = false;
  6759. this._capability = createPromiseCapability();
  6760. this._renderTimer = null;
  6761. }
  6762. TextLayerRenderTask.prototype = {
  6763. get promise() {
  6764. return this._capability.promise;
  6765. },
  6766. cancel: function TextLayer_cancel() {
  6767. this._canceled = true;
  6768. if (this._renderTimer !== null) {
  6769. clearTimeout(this._renderTimer);
  6770. this._renderTimer = null;
  6771. }
  6772. this._capability.reject('canceled');
  6773. },
  6774. _render: function TextLayer_render(timeout) {
  6775. var textItems = this._textContent.items;
  6776. var styles = this._textContent.styles;
  6777. var textDivs = this._textDivs;
  6778. var viewport = this._viewport;
  6779. for (var i = 0, len = textItems.length; i < len; i++) {
  6780. appendText(textDivs, viewport, textItems[i], styles);
  6781. }
  6782. if (!timeout) { // Render right away
  6783. render(this);
  6784. } else { // Schedule
  6785. var self = this;
  6786. this._renderTimer = setTimeout(function() {
  6787. render(self);
  6788. self._renderTimer = null;
  6789. }, timeout);
  6790. }
  6791. }
  6792. };
  6793. /**
  6794. * Starts rendering of the text layer.
  6795. *
  6796. * @param {TextLayerRenderParameters} renderParameters
  6797. * @returns {TextLayerRenderTask}
  6798. */
  6799. function renderTextLayer(renderParameters) {
  6800. var task = new TextLayerRenderTask(renderParameters.textContent,
  6801. renderParameters.container,
  6802. renderParameters.viewport,
  6803. renderParameters.textDivs);
  6804. task._render(renderParameters.timeout);
  6805. return task;
  6806. }
  6807. return renderTextLayer;
  6808. })();
  6809. PDFJS.renderTextLayer = renderTextLayer;
  6810. var SVG_DEFAULTS = {
  6811. fontStyle: 'normal',
  6812. fontWeight: 'normal',
  6813. fillColor: '#000000'
  6814. };
  6815. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  6816. var PNG_HEADER =
  6817. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  6818. var CHUNK_WRAPPER_SIZE = 12;
  6819. var crcTable = new Int32Array(256);
  6820. for (var i = 0; i < 256; i++) {
  6821. var c = i;
  6822. for (var h = 0; h < 8; h++) {
  6823. if (c & 1) {
  6824. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  6825. } else {
  6826. c = (c >> 1) & 0x7fffffff;
  6827. }
  6828. }
  6829. crcTable[i] = c;
  6830. }
  6831. function crc32(data, start, end) {
  6832. var crc = -1;
  6833. for (var i = start; i < end; i++) {
  6834. var a = (crc ^ data[i]) & 0xff;
  6835. var b = crcTable[a];
  6836. crc = (crc >>> 8) ^ b;
  6837. }
  6838. return crc ^ -1;
  6839. }
  6840. function writePngChunk(type, body, data, offset) {
  6841. var p = offset;
  6842. var len = body.length;
  6843. data[p] = len >> 24 & 0xff;
  6844. data[p + 1] = len >> 16 & 0xff;
  6845. data[p + 2] = len >> 8 & 0xff;
  6846. data[p + 3] = len & 0xff;
  6847. p += 4;
  6848. data[p] = type.charCodeAt(0) & 0xff;
  6849. data[p + 1] = type.charCodeAt(1) & 0xff;
  6850. data[p + 2] = type.charCodeAt(2) & 0xff;
  6851. data[p + 3] = type.charCodeAt(3) & 0xff;
  6852. p += 4;
  6853. data.set(body, p);
  6854. p += body.length;
  6855. var crc = crc32(data, offset + 4, p);
  6856. data[p] = crc >> 24 & 0xff;
  6857. data[p + 1] = crc >> 16 & 0xff;
  6858. data[p + 2] = crc >> 8 & 0xff;
  6859. data[p + 3] = crc & 0xff;
  6860. }
  6861. function adler32(data, start, end) {
  6862. var a = 1;
  6863. var b = 0;
  6864. for (var i = start; i < end; ++i) {
  6865. a = (a + (data[i] & 0xff)) % 65521;
  6866. b = (b + a) % 65521;
  6867. }
  6868. return (b << 16) | a;
  6869. }
  6870. function encode(imgData, kind) {
  6871. var width = imgData.width;
  6872. var height = imgData.height;
  6873. var bitDepth, colorType, lineSize;
  6874. var bytes = imgData.data;
  6875. switch (kind) {
  6876. case ImageKind.GRAYSCALE_1BPP:
  6877. colorType = 0;
  6878. bitDepth = 1;
  6879. lineSize = (width + 7) >> 3;
  6880. break;
  6881. case ImageKind.RGB_24BPP:
  6882. colorType = 2;
  6883. bitDepth = 8;
  6884. lineSize = width * 3;
  6885. break;
  6886. case ImageKind.RGBA_32BPP:
  6887. colorType = 6;
  6888. bitDepth = 8;
  6889. lineSize = width * 4;
  6890. break;
  6891. default:
  6892. throw new Error('invalid format');
  6893. }
  6894. // prefix every row with predictor 0
  6895. var literals = new Uint8Array((1 + lineSize) * height);
  6896. var offsetLiterals = 0, offsetBytes = 0;
  6897. var y, i;
  6898. for (y = 0; y < height; ++y) {
  6899. literals[offsetLiterals++] = 0; // no prediction
  6900. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  6901. offsetLiterals);
  6902. offsetBytes += lineSize;
  6903. offsetLiterals += lineSize;
  6904. }
  6905. if (kind === ImageKind.GRAYSCALE_1BPP) {
  6906. // inverting for B/W
  6907. offsetLiterals = 0;
  6908. for (y = 0; y < height; y++) {
  6909. offsetLiterals++; // skipping predictor
  6910. for (i = 0; i < lineSize; i++) {
  6911. literals[offsetLiterals++] ^= 0xFF;
  6912. }
  6913. }
  6914. }
  6915. var ihdr = new Uint8Array([
  6916. width >> 24 & 0xff,
  6917. width >> 16 & 0xff,
  6918. width >> 8 & 0xff,
  6919. width & 0xff,
  6920. height >> 24 & 0xff,
  6921. height >> 16 & 0xff,
  6922. height >> 8 & 0xff,
  6923. height & 0xff,
  6924. bitDepth, // bit depth
  6925. colorType, // color type
  6926. 0x00, // compression method
  6927. 0x00, // filter method
  6928. 0x00 // interlace method
  6929. ]);
  6930. var len = literals.length;
  6931. var maxBlockLength = 0xFFFF;
  6932. var deflateBlocks = Math.ceil(len / maxBlockLength);
  6933. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  6934. var pi = 0;
  6935. idat[pi++] = 0x78; // compression method and flags
  6936. idat[pi++] = 0x9c; // flags
  6937. var pos = 0;
  6938. while (len > maxBlockLength) {
  6939. // writing non-final DEFLATE blocks type 0 and length of 65535
  6940. idat[pi++] = 0x00;
  6941. idat[pi++] = 0xff;
  6942. idat[pi++] = 0xff;
  6943. idat[pi++] = 0x00;
  6944. idat[pi++] = 0x00;
  6945. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  6946. pi += maxBlockLength;
  6947. pos += maxBlockLength;
  6948. len -= maxBlockLength;
  6949. }
  6950. // writing non-final DEFLATE blocks type 0
  6951. idat[pi++] = 0x01;
  6952. idat[pi++] = len & 0xff;
  6953. idat[pi++] = len >> 8 & 0xff;
  6954. idat[pi++] = (~len & 0xffff) & 0xff;
  6955. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  6956. idat.set(literals.subarray(pos), pi);
  6957. pi += literals.length - pos;
  6958. var adler = adler32(literals, 0, literals.length); // checksum
  6959. idat[pi++] = adler >> 24 & 0xff;
  6960. idat[pi++] = adler >> 16 & 0xff;
  6961. idat[pi++] = adler >> 8 & 0xff;
  6962. idat[pi++] = adler & 0xff;
  6963. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  6964. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  6965. ihdr.length + idat.length;
  6966. var data = new Uint8Array(pngLength);
  6967. var offset = 0;
  6968. data.set(PNG_HEADER, offset);
  6969. offset += PNG_HEADER.length;
  6970. writePngChunk('IHDR', ihdr, data, offset);
  6971. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6972. writePngChunk('IDATA', idat, data, offset);
  6973. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6974. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6975. return PDFJS.createObjectURL(data, 'image/png');
  6976. }
  6977. return function convertImgDataToPng(imgData) {
  6978. var kind = (imgData.kind === undefined ?
  6979. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6980. return encode(imgData, kind);
  6981. };
  6982. })();
  6983. var SVGExtraState = (function SVGExtraStateClosure() {
  6984. function SVGExtraState() {
  6985. this.fontSizeScale = 1;
  6986. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6987. this.fontSize = 0;
  6988. this.textMatrix = IDENTITY_MATRIX;
  6989. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6990. this.leading = 0;
  6991. // Current point (in user coordinates)
  6992. this.x = 0;
  6993. this.y = 0;
  6994. // Start of text line (in text coordinates)
  6995. this.lineX = 0;
  6996. this.lineY = 0;
  6997. // Character and word spacing
  6998. this.charSpacing = 0;
  6999. this.wordSpacing = 0;
  7000. this.textHScale = 1;
  7001. this.textRise = 0;
  7002. // Default foreground and background colors
  7003. this.fillColor = SVG_DEFAULTS.fillColor;
  7004. this.strokeColor = '#000000';
  7005. this.fillAlpha = 1;
  7006. this.strokeAlpha = 1;
  7007. this.lineWidth = 1;
  7008. this.lineJoin = '';
  7009. this.lineCap = '';
  7010. this.miterLimit = 0;
  7011. this.dashArray = [];
  7012. this.dashPhase = 0;
  7013. this.dependencies = [];
  7014. // Clipping
  7015. this.clipId = '';
  7016. this.pendingClip = false;
  7017. this.maskId = '';
  7018. }
  7019. SVGExtraState.prototype = {
  7020. clone: function SVGExtraState_clone() {
  7021. return Object.create(this);
  7022. },
  7023. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  7024. this.x = x;
  7025. this.y = y;
  7026. }
  7027. };
  7028. return SVGExtraState;
  7029. })();
  7030. var SVGGraphics = (function SVGGraphicsClosure() {
  7031. function createScratchSVG(width, height) {
  7032. var NS = 'http://www.w3.org/2000/svg';
  7033. var svg = document.createElementNS(NS, 'svg:svg');
  7034. svg.setAttributeNS(null, 'version', '1.1');
  7035. svg.setAttributeNS(null, 'width', width + 'px');
  7036. svg.setAttributeNS(null, 'height', height + 'px');
  7037. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  7038. return svg;
  7039. }
  7040. function opListToTree(opList) {
  7041. var opTree = [];
  7042. var tmp = [];
  7043. var opListLen = opList.length;
  7044. for (var x = 0; x < opListLen; x++) {
  7045. if (opList[x].fn === 'save') {
  7046. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  7047. tmp.push(opTree);
  7048. opTree = opTree[opTree.length - 1].items;
  7049. continue;
  7050. }
  7051. if(opList[x].fn === 'restore') {
  7052. opTree = tmp.pop();
  7053. } else {
  7054. opTree.push(opList[x]);
  7055. }
  7056. }
  7057. return opTree;
  7058. }
  7059. /**
  7060. * Formats float number.
  7061. * @param value {number} number to format.
  7062. * @returns {string}
  7063. */
  7064. function pf(value) {
  7065. if (value === (value | 0)) { // integer number
  7066. return value.toString();
  7067. }
  7068. var s = value.toFixed(10);
  7069. var i = s.length - 1;
  7070. if (s[i] !== '0') {
  7071. return s;
  7072. }
  7073. // removing trailing zeros
  7074. do {
  7075. i--;
  7076. } while (s[i] === '0');
  7077. return s.substr(0, s[i] === '.' ? i : i + 1);
  7078. }
  7079. /**
  7080. * Formats transform matrix. The standard rotation, scale and translate
  7081. * matrices are replaced by their shorter forms, and for identity matrix
  7082. * returns empty string to save the memory.
  7083. * @param m {Array} matrix to format.
  7084. * @returns {string}
  7085. */
  7086. function pm(m) {
  7087. if (m[4] === 0 && m[5] === 0) {
  7088. if (m[1] === 0 && m[2] === 0) {
  7089. if (m[0] === 1 && m[3] === 1) {
  7090. return '';
  7091. }
  7092. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  7093. }
  7094. if (m[0] === m[3] && m[1] === -m[2]) {
  7095. var a = Math.acos(m[0]) * 180 / Math.PI;
  7096. return 'rotate(' + pf(a) + ')';
  7097. }
  7098. } else {
  7099. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  7100. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  7101. }
  7102. }
  7103. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  7104. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  7105. }
  7106. function SVGGraphics(commonObjs, objs) {
  7107. this.current = new SVGExtraState();
  7108. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  7109. this.transformStack = [];
  7110. this.extraStack = [];
  7111. this.commonObjs = commonObjs;
  7112. this.objs = objs;
  7113. this.pendingEOFill = false;
  7114. this.embedFonts = false;
  7115. this.embeddedFonts = {};
  7116. this.cssStyle = null;
  7117. }
  7118. var NS = 'http://www.w3.org/2000/svg';
  7119. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  7120. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  7121. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  7122. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  7123. var clipCount = 0;
  7124. var maskCount = 0;
  7125. SVGGraphics.prototype = {
  7126. save: function SVGGraphics_save() {
  7127. this.transformStack.push(this.transformMatrix);
  7128. var old = this.current;
  7129. this.extraStack.push(old);
  7130. this.current = old.clone();
  7131. },
  7132. restore: function SVGGraphics_restore() {
  7133. this.transformMatrix = this.transformStack.pop();
  7134. this.current = this.extraStack.pop();
  7135. this.tgrp = document.createElementNS(NS, 'svg:g');
  7136. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7137. this.pgrp.appendChild(this.tgrp);
  7138. },
  7139. group: function SVGGraphics_group(items) {
  7140. this.save();
  7141. this.executeOpTree(items);
  7142. this.restore();
  7143. },
  7144. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  7145. var fnArray = operatorList.fnArray;
  7146. var fnArrayLen = fnArray.length;
  7147. var argsArray = operatorList.argsArray;
  7148. var self = this;
  7149. for (var i = 0; i < fnArrayLen; i++) {
  7150. if (OPS.dependency === fnArray[i]) {
  7151. var deps = argsArray[i];
  7152. for (var n = 0, nn = deps.length; n < nn; n++) {
  7153. var obj = deps[n];
  7154. var common = obj.substring(0, 2) === 'g_';
  7155. var promise;
  7156. if (common) {
  7157. promise = new Promise(function(resolve) {
  7158. self.commonObjs.get(obj, resolve);
  7159. });
  7160. } else {
  7161. promise = new Promise(function(resolve) {
  7162. self.objs.get(obj, resolve);
  7163. });
  7164. }
  7165. this.current.dependencies.push(promise);
  7166. }
  7167. }
  7168. }
  7169. return Promise.all(this.current.dependencies);
  7170. },
  7171. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  7172. var transformMatrix = [a, b, c, d, e, f];
  7173. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  7174. transformMatrix);
  7175. this.tgrp = document.createElementNS(NS, 'svg:g');
  7176. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7177. },
  7178. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  7179. this.svg = createScratchSVG(viewport.width, viewport.height);
  7180. this.viewport = viewport;
  7181. return this.loadDependencies(operatorList).then(function () {
  7182. this.transformMatrix = IDENTITY_MATRIX;
  7183. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  7184. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  7185. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  7186. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7187. this.defs = document.createElementNS(NS, 'svg:defs');
  7188. this.pgrp.appendChild(this.defs);
  7189. this.pgrp.appendChild(this.tgrp);
  7190. this.svg.appendChild(this.pgrp);
  7191. var opTree = this.convertOpList(operatorList);
  7192. this.executeOpTree(opTree);
  7193. return this.svg;
  7194. }.bind(this));
  7195. },
  7196. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  7197. var argsArray = operatorList.argsArray;
  7198. var fnArray = operatorList.fnArray;
  7199. var fnArrayLen = fnArray.length;
  7200. var REVOPS = [];
  7201. var opList = [];
  7202. for (var op in OPS) {
  7203. REVOPS[OPS[op]] = op;
  7204. }
  7205. for (var x = 0; x < fnArrayLen; x++) {
  7206. var fnId = fnArray[x];
  7207. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  7208. }
  7209. return opListToTree(opList);
  7210. },
  7211. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  7212. var opTreeLen = opTree.length;
  7213. for(var x = 0; x < opTreeLen; x++) {
  7214. var fn = opTree[x].fn;
  7215. var fnId = opTree[x].fnId;
  7216. var args = opTree[x].args;
  7217. switch (fnId | 0) {
  7218. case OPS.beginText:
  7219. this.beginText();
  7220. break;
  7221. case OPS.setLeading:
  7222. this.setLeading(args);
  7223. break;
  7224. case OPS.setLeadingMoveText:
  7225. this.setLeadingMoveText(args[0], args[1]);
  7226. break;
  7227. case OPS.setFont:
  7228. this.setFont(args);
  7229. break;
  7230. case OPS.showText:
  7231. this.showText(args[0]);
  7232. break;
  7233. case OPS.showSpacedText:
  7234. this.showText(args[0]);
  7235. break;
  7236. case OPS.endText:
  7237. this.endText();
  7238. break;
  7239. case OPS.moveText:
  7240. this.moveText(args[0], args[1]);
  7241. break;
  7242. case OPS.setCharSpacing:
  7243. this.setCharSpacing(args[0]);
  7244. break;
  7245. case OPS.setWordSpacing:
  7246. this.setWordSpacing(args[0]);
  7247. break;
  7248. case OPS.setHScale:
  7249. this.setHScale(args[0]);
  7250. break;
  7251. case OPS.setTextMatrix:
  7252. this.setTextMatrix(args[0], args[1], args[2],
  7253. args[3], args[4], args[5]);
  7254. break;
  7255. case OPS.setLineWidth:
  7256. this.setLineWidth(args[0]);
  7257. break;
  7258. case OPS.setLineJoin:
  7259. this.setLineJoin(args[0]);
  7260. break;
  7261. case OPS.setLineCap:
  7262. this.setLineCap(args[0]);
  7263. break;
  7264. case OPS.setMiterLimit:
  7265. this.setMiterLimit(args[0]);
  7266. break;
  7267. case OPS.setFillRGBColor:
  7268. this.setFillRGBColor(args[0], args[1], args[2]);
  7269. break;
  7270. case OPS.setStrokeRGBColor:
  7271. this.setStrokeRGBColor(args[0], args[1], args[2]);
  7272. break;
  7273. case OPS.setDash:
  7274. this.setDash(args[0], args[1]);
  7275. break;
  7276. case OPS.setGState:
  7277. this.setGState(args[0]);
  7278. break;
  7279. case OPS.fill:
  7280. this.fill();
  7281. break;
  7282. case OPS.eoFill:
  7283. this.eoFill();
  7284. break;
  7285. case OPS.stroke:
  7286. this.stroke();
  7287. break;
  7288. case OPS.fillStroke:
  7289. this.fillStroke();
  7290. break;
  7291. case OPS.eoFillStroke:
  7292. this.eoFillStroke();
  7293. break;
  7294. case OPS.clip:
  7295. this.clip('nonzero');
  7296. break;
  7297. case OPS.eoClip:
  7298. this.clip('evenodd');
  7299. break;
  7300. case OPS.paintSolidColorImageMask:
  7301. this.paintSolidColorImageMask();
  7302. break;
  7303. case OPS.paintJpegXObject:
  7304. this.paintJpegXObject(args[0], args[1], args[2]);
  7305. break;
  7306. case OPS.paintImageXObject:
  7307. this.paintImageXObject(args[0]);
  7308. break;
  7309. case OPS.paintInlineImageXObject:
  7310. this.paintInlineImageXObject(args[0]);
  7311. break;
  7312. case OPS.paintImageMaskXObject:
  7313. this.paintImageMaskXObject(args[0]);
  7314. break;
  7315. case OPS.paintFormXObjectBegin:
  7316. this.paintFormXObjectBegin(args[0], args[1]);
  7317. break;
  7318. case OPS.paintFormXObjectEnd:
  7319. this.paintFormXObjectEnd();
  7320. break;
  7321. case OPS.closePath:
  7322. this.closePath();
  7323. break;
  7324. case OPS.closeStroke:
  7325. this.closeStroke();
  7326. break;
  7327. case OPS.closeFillStroke:
  7328. this.closeFillStroke();
  7329. break;
  7330. case OPS.nextLine:
  7331. this.nextLine();
  7332. break;
  7333. case OPS.transform:
  7334. this.transform(args[0], args[1], args[2], args[3],
  7335. args[4], args[5]);
  7336. break;
  7337. case OPS.constructPath:
  7338. this.constructPath(args[0], args[1]);
  7339. break;
  7340. case OPS.endPath:
  7341. this.endPath();
  7342. break;
  7343. case 92:
  7344. this.group(opTree[x].items);
  7345. break;
  7346. default:
  7347. warn('Unimplemented method '+ fn);
  7348. break;
  7349. }
  7350. }
  7351. },
  7352. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  7353. this.current.wordSpacing = wordSpacing;
  7354. },
  7355. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  7356. this.current.charSpacing = charSpacing;
  7357. },
  7358. nextLine: function SVGGraphics_nextLine() {
  7359. this.moveText(0, this.current.leading);
  7360. },
  7361. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  7362. var current = this.current;
  7363. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  7364. this.current.x = this.current.lineX = 0;
  7365. this.current.y = this.current.lineY = 0;
  7366. current.xcoords = [];
  7367. current.tspan = document.createElementNS(NS, 'svg:tspan');
  7368. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  7369. current.tspan.setAttributeNS(null, 'font-size',
  7370. pf(current.fontSize) + 'px');
  7371. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  7372. current.txtElement = document.createElementNS(NS, 'svg:text');
  7373. current.txtElement.appendChild(current.tspan);
  7374. },
  7375. beginText: function SVGGraphics_beginText() {
  7376. this.current.x = this.current.lineX = 0;
  7377. this.current.y = this.current.lineY = 0;
  7378. this.current.textMatrix = IDENTITY_MATRIX;
  7379. this.current.lineMatrix = IDENTITY_MATRIX;
  7380. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  7381. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  7382. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  7383. this.current.xcoords = [];
  7384. },
  7385. moveText: function SVGGraphics_moveText(x, y) {
  7386. var current = this.current;
  7387. this.current.x = this.current.lineX += x;
  7388. this.current.y = this.current.lineY += y;
  7389. current.xcoords = [];
  7390. current.tspan = document.createElementNS(NS, 'svg:tspan');
  7391. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  7392. current.tspan.setAttributeNS(null, 'font-size',
  7393. pf(current.fontSize) + 'px');
  7394. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  7395. },
  7396. showText: function SVGGraphics_showText(glyphs) {
  7397. var current = this.current;
  7398. var font = current.font;
  7399. var fontSize = current.fontSize;
  7400. if (fontSize === 0) {
  7401. return;
  7402. }
  7403. var charSpacing = current.charSpacing;
  7404. var wordSpacing = current.wordSpacing;
  7405. var fontDirection = current.fontDirection;
  7406. var textHScale = current.textHScale * fontDirection;
  7407. var glyphsLength = glyphs.length;
  7408. var vertical = font.vertical;
  7409. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7410. var x = 0, i;
  7411. for (i = 0; i < glyphsLength; ++i) {
  7412. var glyph = glyphs[i];
  7413. if (glyph === null) {
  7414. // word break
  7415. x += fontDirection * wordSpacing;
  7416. continue;
  7417. } else if (isNum(glyph)) {
  7418. x += -glyph * fontSize * 0.001;
  7419. continue;
  7420. }
  7421. current.xcoords.push(current.x + x * textHScale);
  7422. var width = glyph.width;
  7423. var character = glyph.fontChar;
  7424. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  7425. x += charWidth;
  7426. current.tspan.textContent += character;
  7427. }
  7428. if (vertical) {
  7429. current.y -= x * textHScale;
  7430. } else {
  7431. current.x += x * textHScale;
  7432. }
  7433. current.tspan.setAttributeNS(null, 'x',
  7434. current.xcoords.map(pf).join(' '));
  7435. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  7436. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  7437. current.tspan.setAttributeNS(null, 'font-size',
  7438. pf(current.fontSize) + 'px');
  7439. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  7440. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  7441. }
  7442. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  7443. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  7444. }
  7445. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  7446. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  7447. }
  7448. current.txtElement.setAttributeNS(null, 'transform',
  7449. pm(current.textMatrix) +
  7450. ' scale(1, -1)' );
  7451. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  7452. current.txtElement.appendChild(current.tspan);
  7453. current.txtgrp.appendChild(current.txtElement);
  7454. this.tgrp.appendChild(current.txtElement);
  7455. },
  7456. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  7457. this.setLeading(-y);
  7458. this.moveText(x, y);
  7459. },
  7460. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  7461. if (!this.cssStyle) {
  7462. this.cssStyle = document.createElementNS(NS, 'svg:style');
  7463. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  7464. this.defs.appendChild(this.cssStyle);
  7465. }
  7466. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  7467. this.cssStyle.textContent +=
  7468. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  7469. ' src: url(' + url + '); }\n';
  7470. },
  7471. setFont: function SVGGraphics_setFont(details) {
  7472. var current = this.current;
  7473. var fontObj = this.commonObjs.get(details[0]);
  7474. var size = details[1];
  7475. this.current.font = fontObj;
  7476. if (this.embedFonts && fontObj.data &&
  7477. !this.embeddedFonts[fontObj.loadedName]) {
  7478. this.addFontStyle(fontObj);
  7479. this.embeddedFonts[fontObj.loadedName] = fontObj;
  7480. }
  7481. current.fontMatrix = (fontObj.fontMatrix ?
  7482. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7483. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  7484. (fontObj.bold ? 'bold' : 'normal');
  7485. var italic = fontObj.italic ? 'italic' : 'normal';
  7486. if (size < 0) {
  7487. size = -size;
  7488. current.fontDirection = -1;
  7489. } else {
  7490. current.fontDirection = 1;
  7491. }
  7492. current.fontSize = size;
  7493. current.fontFamily = fontObj.loadedName;
  7494. current.fontWeight = bold;
  7495. current.fontStyle = italic;
  7496. current.tspan = document.createElementNS(NS, 'svg:tspan');
  7497. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  7498. current.xcoords = [];
  7499. },
  7500. endText: function SVGGraphics_endText() {
  7501. if (this.current.pendingClip) {
  7502. this.cgrp.appendChild(this.tgrp);
  7503. this.pgrp.appendChild(this.cgrp);
  7504. } else {
  7505. this.pgrp.appendChild(this.tgrp);
  7506. }
  7507. this.tgrp = document.createElementNS(NS, 'svg:g');
  7508. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7509. },
  7510. // Path properties
  7511. setLineWidth: function SVGGraphics_setLineWidth(width) {
  7512. this.current.lineWidth = width;
  7513. },
  7514. setLineCap: function SVGGraphics_setLineCap(style) {
  7515. this.current.lineCap = LINE_CAP_STYLES[style];
  7516. },
  7517. setLineJoin: function SVGGraphics_setLineJoin(style) {
  7518. this.current.lineJoin = LINE_JOIN_STYLES[style];
  7519. },
  7520. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  7521. this.current.miterLimit = limit;
  7522. },
  7523. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  7524. var color = Util.makeCssRgb(r, g, b);
  7525. this.current.strokeColor = color;
  7526. },
  7527. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  7528. var color = Util.makeCssRgb(r, g, b);
  7529. this.current.fillColor = color;
  7530. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  7531. this.current.xcoords = [];
  7532. },
  7533. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  7534. this.current.dashArray = dashArray;
  7535. this.current.dashPhase = dashPhase;
  7536. },
  7537. constructPath: function SVGGraphics_constructPath(ops, args) {
  7538. var current = this.current;
  7539. var x = current.x, y = current.y;
  7540. current.path = document.createElementNS(NS, 'svg:path');
  7541. var d = [];
  7542. var opLength = ops.length;
  7543. for (var i = 0, j = 0; i < opLength; i++) {
  7544. switch (ops[i] | 0) {
  7545. case OPS.rectangle:
  7546. x = args[j++];
  7547. y = args[j++];
  7548. var width = args[j++];
  7549. var height = args[j++];
  7550. var xw = x + width;
  7551. var yh = y + height;
  7552. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  7553. 'L', pf(x), pf(yh), 'Z');
  7554. break;
  7555. case OPS.moveTo:
  7556. x = args[j++];
  7557. y = args[j++];
  7558. d.push('M', pf(x), pf(y));
  7559. break;
  7560. case OPS.lineTo:
  7561. x = args[j++];
  7562. y = args[j++];
  7563. d.push('L', pf(x) , pf(y));
  7564. break;
  7565. case OPS.curveTo:
  7566. x = args[j + 4];
  7567. y = args[j + 5];
  7568. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  7569. pf(args[j + 3]), pf(x), pf(y));
  7570. j += 6;
  7571. break;
  7572. case OPS.curveTo2:
  7573. x = args[j + 2];
  7574. y = args[j + 3];
  7575. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  7576. pf(args[j + 2]), pf(args[j + 3]));
  7577. j += 4;
  7578. break;
  7579. case OPS.curveTo3:
  7580. x = args[j + 2];
  7581. y = args[j + 3];
  7582. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  7583. pf(x), pf(y));
  7584. j += 4;
  7585. break;
  7586. case OPS.closePath:
  7587. d.push('Z');
  7588. break;
  7589. }
  7590. }
  7591. current.path.setAttributeNS(null, 'd', d.join(' '));
  7592. current.path.setAttributeNS(null, 'stroke-miterlimit',
  7593. pf(current.miterLimit));
  7594. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  7595. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  7596. current.path.setAttributeNS(null, 'stroke-width',
  7597. pf(current.lineWidth) + 'px');
  7598. current.path.setAttributeNS(null, 'stroke-dasharray',
  7599. current.dashArray.map(pf).join(' '));
  7600. current.path.setAttributeNS(null, 'stroke-dashoffset',
  7601. pf(current.dashPhase) + 'px');
  7602. current.path.setAttributeNS(null, 'fill', 'none');
  7603. this.tgrp.appendChild(current.path);
  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. // Saving a reference in current.element so that it can be addressed
  7611. // in 'fill' and 'stroke'
  7612. current.element = current.path;
  7613. current.setCurrentPoint(x, y);
  7614. },
  7615. endPath: function SVGGraphics_endPath() {
  7616. var current = this.current;
  7617. if (current.pendingClip) {
  7618. this.cgrp.appendChild(this.tgrp);
  7619. this.pgrp.appendChild(this.cgrp);
  7620. } else {
  7621. this.pgrp.appendChild(this.tgrp);
  7622. }
  7623. this.tgrp = document.createElementNS(NS, 'svg:g');
  7624. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7625. },
  7626. clip: function SVGGraphics_clip(type) {
  7627. var current = this.current;
  7628. // Add current path to clipping path
  7629. current.clipId = 'clippath' + clipCount;
  7630. clipCount++;
  7631. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  7632. this.clippath.setAttributeNS(null, 'id', current.clipId);
  7633. var clipElement = current.element.cloneNode();
  7634. if (type === 'evenodd') {
  7635. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  7636. } else {
  7637. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  7638. }
  7639. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  7640. this.clippath.appendChild(clipElement);
  7641. this.defs.appendChild(this.clippath);
  7642. // Create a new group with that attribute
  7643. current.pendingClip = true;
  7644. this.cgrp = document.createElementNS(NS, 'svg:g');
  7645. this.cgrp.setAttributeNS(null, 'clip-path',
  7646. 'url(#' + current.clipId + ')');
  7647. this.pgrp.appendChild(this.cgrp);
  7648. },
  7649. closePath: function SVGGraphics_closePath() {
  7650. var current = this.current;
  7651. var d = current.path.getAttributeNS(null, 'd');
  7652. d += 'Z';
  7653. current.path.setAttributeNS(null, 'd', d);
  7654. },
  7655. setLeading: function SVGGraphics_setLeading(leading) {
  7656. this.current.leading = -leading;
  7657. },
  7658. setTextRise: function SVGGraphics_setTextRise(textRise) {
  7659. this.current.textRise = textRise;
  7660. },
  7661. setHScale: function SVGGraphics_setHScale(scale) {
  7662. this.current.textHScale = scale / 100;
  7663. },
  7664. setGState: function SVGGraphics_setGState(states) {
  7665. for (var i = 0, ii = states.length; i < ii; i++) {
  7666. var state = states[i];
  7667. var key = state[0];
  7668. var value = state[1];
  7669. switch (key) {
  7670. case 'LW':
  7671. this.setLineWidth(value);
  7672. break;
  7673. case 'LC':
  7674. this.setLineCap(value);
  7675. break;
  7676. case 'LJ':
  7677. this.setLineJoin(value);
  7678. break;
  7679. case 'ML':
  7680. this.setMiterLimit(value);
  7681. break;
  7682. case 'D':
  7683. this.setDash(value[0], value[1]);
  7684. break;
  7685. case 'RI':
  7686. break;
  7687. case 'FL':
  7688. break;
  7689. case 'Font':
  7690. this.setFont(value);
  7691. break;
  7692. case 'CA':
  7693. break;
  7694. case 'ca':
  7695. break;
  7696. case 'BM':
  7697. break;
  7698. case 'SMask':
  7699. break;
  7700. }
  7701. }
  7702. },
  7703. fill: function SVGGraphics_fill() {
  7704. var current = this.current;
  7705. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7706. },
  7707. stroke: function SVGGraphics_stroke() {
  7708. var current = this.current;
  7709. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  7710. current.element.setAttributeNS(null, 'fill', 'none');
  7711. },
  7712. eoFill: function SVGGraphics_eoFill() {
  7713. var current = this.current;
  7714. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7715. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7716. },
  7717. fillStroke: function SVGGraphics_fillStroke() {
  7718. // Order is important since stroke wants fill to be none.
  7719. // First stroke, then if fill needed, it will be overwritten.
  7720. this.stroke();
  7721. this.fill();
  7722. },
  7723. eoFillStroke: function SVGGraphics_eoFillStroke() {
  7724. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7725. this.fillStroke();
  7726. },
  7727. closeStroke: function SVGGraphics_closeStroke() {
  7728. this.closePath();
  7729. this.stroke();
  7730. },
  7731. closeFillStroke: function SVGGraphics_closeFillStroke() {
  7732. this.closePath();
  7733. this.fillStroke();
  7734. },
  7735. paintSolidColorImageMask:
  7736. function SVGGraphics_paintSolidColorImageMask() {
  7737. var current = this.current;
  7738. var rect = document.createElementNS(NS, 'svg:rect');
  7739. rect.setAttributeNS(null, 'x', '0');
  7740. rect.setAttributeNS(null, 'y', '0');
  7741. rect.setAttributeNS(null, 'width', '1px');
  7742. rect.setAttributeNS(null, 'height', '1px');
  7743. rect.setAttributeNS(null, 'fill', current.fillColor);
  7744. this.tgrp.appendChild(rect);
  7745. },
  7746. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  7747. var current = this.current;
  7748. var imgObj = this.objs.get(objId);
  7749. var imgEl = document.createElementNS(NS, 'svg:image');
  7750. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  7751. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  7752. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  7753. imgEl.setAttributeNS(null, 'x', '0');
  7754. imgEl.setAttributeNS(null, 'y', pf(-h));
  7755. imgEl.setAttributeNS(null, 'transform',
  7756. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  7757. this.tgrp.appendChild(imgEl);
  7758. if (current.pendingClip) {
  7759. this.cgrp.appendChild(this.tgrp);
  7760. this.pgrp.appendChild(this.cgrp);
  7761. } else {
  7762. this.pgrp.appendChild(this.tgrp);
  7763. }
  7764. },
  7765. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  7766. var imgData = this.objs.get(objId);
  7767. if (!imgData) {
  7768. warn('Dependent image isn\'t ready yet');
  7769. return;
  7770. }
  7771. this.paintInlineImageXObject(imgData);
  7772. },
  7773. paintInlineImageXObject:
  7774. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  7775. var current = this.current;
  7776. var width = imgData.width;
  7777. var height = imgData.height;
  7778. var imgSrc = convertImgDataToPng(imgData);
  7779. var cliprect = document.createElementNS(NS, 'svg:rect');
  7780. cliprect.setAttributeNS(null, 'x', '0');
  7781. cliprect.setAttributeNS(null, 'y', '0');
  7782. cliprect.setAttributeNS(null, 'width', pf(width));
  7783. cliprect.setAttributeNS(null, 'height', pf(height));
  7784. current.element = cliprect;
  7785. this.clip('nonzero');
  7786. var imgEl = document.createElementNS(NS, 'svg:image');
  7787. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  7788. imgEl.setAttributeNS(null, 'x', '0');
  7789. imgEl.setAttributeNS(null, 'y', pf(-height));
  7790. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  7791. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  7792. imgEl.setAttributeNS(null, 'transform',
  7793. 'scale(' + pf(1 / width) + ' ' +
  7794. pf(-1 / height) + ')');
  7795. if (mask) {
  7796. mask.appendChild(imgEl);
  7797. } else {
  7798. this.tgrp.appendChild(imgEl);
  7799. }
  7800. if (current.pendingClip) {
  7801. this.cgrp.appendChild(this.tgrp);
  7802. this.pgrp.appendChild(this.cgrp);
  7803. } else {
  7804. this.pgrp.appendChild(this.tgrp);
  7805. }
  7806. },
  7807. paintImageMaskXObject:
  7808. function SVGGraphics_paintImageMaskXObject(imgData) {
  7809. var current = this.current;
  7810. var width = imgData.width;
  7811. var height = imgData.height;
  7812. var fillColor = current.fillColor;
  7813. current.maskId = 'mask' + maskCount++;
  7814. var mask = document.createElementNS(NS, 'svg:mask');
  7815. mask.setAttributeNS(null, 'id', current.maskId);
  7816. var rect = document.createElementNS(NS, 'svg:rect');
  7817. rect.setAttributeNS(null, 'x', '0');
  7818. rect.setAttributeNS(null, 'y', '0');
  7819. rect.setAttributeNS(null, 'width', pf(width));
  7820. rect.setAttributeNS(null, 'height', pf(height));
  7821. rect.setAttributeNS(null, 'fill', fillColor);
  7822. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  7823. this.defs.appendChild(mask);
  7824. this.tgrp.appendChild(rect);
  7825. this.paintInlineImageXObject(imgData, mask);
  7826. },
  7827. paintFormXObjectBegin:
  7828. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  7829. this.save();
  7830. if (isArray(matrix) && matrix.length === 6) {
  7831. this.transform(matrix[0], matrix[1], matrix[2],
  7832. matrix[3], matrix[4], matrix[5]);
  7833. }
  7834. if (isArray(bbox) && bbox.length === 4) {
  7835. var width = bbox[2] - bbox[0];
  7836. var height = bbox[3] - bbox[1];
  7837. var cliprect = document.createElementNS(NS, 'svg:rect');
  7838. cliprect.setAttributeNS(null, 'x', bbox[0]);
  7839. cliprect.setAttributeNS(null, 'y', bbox[1]);
  7840. cliprect.setAttributeNS(null, 'width', pf(width));
  7841. cliprect.setAttributeNS(null, 'height', pf(height));
  7842. this.current.element = cliprect;
  7843. this.clip('nonzero');
  7844. this.endPath();
  7845. }
  7846. },
  7847. paintFormXObjectEnd:
  7848. function SVGGraphics_paintFormXObjectEnd() {
  7849. this.restore();
  7850. }
  7851. };
  7852. return SVGGraphics;
  7853. })();
  7854. PDFJS.SVGGraphics = SVGGraphics;
  7855. }).call((typeof window === 'undefined') ? this : window);
  7856. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  7857. // workerSrc is not set -- using last script url to define default location
  7858. PDFJS.workerSrc = (function () {
  7859. 'use strict';
  7860. var pdfJsSrc = document.currentScript.src;
  7861. return pdfJsSrc && pdfJsSrc.replace(/\.js$/i, '.worker.js');
  7862. })();
  7863. }