pdf.js 248 KB

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