pdf.js 365 KB

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