pdf.js 332 KB

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