2
0

pdf.js 291 KB

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