pdf.js 273 KB

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