pdf.js 255 KB

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