2
0

pdf.js 253 KB

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