pdf.js 346 KB

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