pdf.js 283 KB

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