pdf.js 346 KB

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