pdf.js 327 KB

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