pdf.js 257 KB

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