pdf.js 263 KB

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