pdf.js 328 KB

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