pdf.js 257 KB

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