pdf.js 280 KB

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