pdf.js 244 KB

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