pdf.js 333 KB

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