pdf.js 362 KB

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