pdf.js 421 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569
  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. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/build/pdf', ['exports'], factory);
  19. } else if (typeof exports !== 'undefined') {
  20. factory(exports);
  21. } else {
  22. factory(root['pdfjsDistBuildPdf'] = {});
  23. }
  24. }(this, function (exports) {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. var pdfjsVersion = '1.6.239';
  28. var pdfjsBuild = 'f209030';
  29. var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  30. var pdfjsLibs = {};
  31. (function pdfjsWrapper() {
  32. (function (root, factory) {
  33. factory(root.pdfjsSharedUtil = {});
  34. }(this, function (exports) {
  35. var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
  36. var FONT_IDENTITY_MATRIX = [
  37. 0.001,
  38. 0,
  39. 0,
  40. 0.001,
  41. 0,
  42. 0
  43. ];
  44. var TextRenderingMode = {
  45. FILL: 0,
  46. STROKE: 1,
  47. FILL_STROKE: 2,
  48. INVISIBLE: 3,
  49. FILL_ADD_TO_PATH: 4,
  50. STROKE_ADD_TO_PATH: 5,
  51. FILL_STROKE_ADD_TO_PATH: 6,
  52. ADD_TO_PATH: 7,
  53. FILL_STROKE_MASK: 3,
  54. ADD_TO_PATH_FLAG: 4
  55. };
  56. var ImageKind = {
  57. GRAYSCALE_1BPP: 1,
  58. RGB_24BPP: 2,
  59. RGBA_32BPP: 3
  60. };
  61. var AnnotationType = {
  62. TEXT: 1,
  63. LINK: 2,
  64. FREETEXT: 3,
  65. LINE: 4,
  66. SQUARE: 5,
  67. CIRCLE: 6,
  68. POLYGON: 7,
  69. POLYLINE: 8,
  70. HIGHLIGHT: 9,
  71. UNDERLINE: 10,
  72. SQUIGGLY: 11,
  73. STRIKEOUT: 12,
  74. STAMP: 13,
  75. CARET: 14,
  76. INK: 15,
  77. POPUP: 16,
  78. FILEATTACHMENT: 17,
  79. SOUND: 18,
  80. MOVIE: 19,
  81. WIDGET: 20,
  82. SCREEN: 21,
  83. PRINTERMARK: 22,
  84. TRAPNET: 23,
  85. WATERMARK: 24,
  86. THREED: 25,
  87. REDACT: 26
  88. };
  89. var AnnotationFlag = {
  90. INVISIBLE: 0x01,
  91. HIDDEN: 0x02,
  92. PRINT: 0x04,
  93. NOZOOM: 0x08,
  94. NOROTATE: 0x10,
  95. NOVIEW: 0x20,
  96. READONLY: 0x40,
  97. LOCKED: 0x80,
  98. TOGGLENOVIEW: 0x100,
  99. LOCKEDCONTENTS: 0x200
  100. };
  101. var AnnotationFieldFlag = {
  102. READONLY: 0x0000001,
  103. REQUIRED: 0x0000002,
  104. NOEXPORT: 0x0000004,
  105. MULTILINE: 0x0001000,
  106. PASSWORD: 0x0002000,
  107. NOTOGGLETOOFF: 0x0004000,
  108. RADIO: 0x0008000,
  109. PUSHBUTTON: 0x0010000,
  110. COMBO: 0x0020000,
  111. EDIT: 0x0040000,
  112. SORT: 0x0080000,
  113. FILESELECT: 0x0100000,
  114. MULTISELECT: 0x0200000,
  115. DONOTSPELLCHECK: 0x0400000,
  116. DONOTSCROLL: 0x0800000,
  117. COMB: 0x1000000,
  118. RICHTEXT: 0x2000000,
  119. RADIOSINUNISON: 0x2000000,
  120. COMMITONSELCHANGE: 0x4000000
  121. };
  122. var AnnotationBorderStyleType = {
  123. SOLID: 1,
  124. DASHED: 2,
  125. BEVELED: 3,
  126. INSET: 4,
  127. UNDERLINE: 5
  128. };
  129. var StreamType = {
  130. UNKNOWN: 0,
  131. FLATE: 1,
  132. LZW: 2,
  133. DCT: 3,
  134. JPX: 4,
  135. JBIG: 5,
  136. A85: 6,
  137. AHX: 7,
  138. CCF: 8,
  139. RL: 9
  140. };
  141. var FontType = {
  142. UNKNOWN: 0,
  143. TYPE1: 1,
  144. TYPE1C: 2,
  145. CIDFONTTYPE0: 3,
  146. CIDFONTTYPE0C: 4,
  147. TRUETYPE: 5,
  148. CIDFONTTYPE2: 6,
  149. TYPE3: 7,
  150. OPENTYPE: 8,
  151. TYPE0: 9,
  152. MMTYPE1: 10
  153. };
  154. var VERBOSITY_LEVELS = {
  155. errors: 0,
  156. warnings: 1,
  157. infos: 5
  158. };
  159. // All the possible operations for an operator list.
  160. var OPS = {
  161. // Intentionally start from 1 so it is easy to spot bad operators that will be
  162. // 0's.
  163. dependency: 1,
  164. setLineWidth: 2,
  165. setLineCap: 3,
  166. setLineJoin: 4,
  167. setMiterLimit: 5,
  168. setDash: 6,
  169. setRenderingIntent: 7,
  170. setFlatness: 8,
  171. setGState: 9,
  172. save: 10,
  173. restore: 11,
  174. transform: 12,
  175. moveTo: 13,
  176. lineTo: 14,
  177. curveTo: 15,
  178. curveTo2: 16,
  179. curveTo3: 17,
  180. closePath: 18,
  181. rectangle: 19,
  182. stroke: 20,
  183. closeStroke: 21,
  184. fill: 22,
  185. eoFill: 23,
  186. fillStroke: 24,
  187. eoFillStroke: 25,
  188. closeFillStroke: 26,
  189. closeEOFillStroke: 27,
  190. endPath: 28,
  191. clip: 29,
  192. eoClip: 30,
  193. beginText: 31,
  194. endText: 32,
  195. setCharSpacing: 33,
  196. setWordSpacing: 34,
  197. setHScale: 35,
  198. setLeading: 36,
  199. setFont: 37,
  200. setTextRenderingMode: 38,
  201. setTextRise: 39,
  202. moveText: 40,
  203. setLeadingMoveText: 41,
  204. setTextMatrix: 42,
  205. nextLine: 43,
  206. showText: 44,
  207. showSpacedText: 45,
  208. nextLineShowText: 46,
  209. nextLineSetSpacingShowText: 47,
  210. setCharWidth: 48,
  211. setCharWidthAndBounds: 49,
  212. setStrokeColorSpace: 50,
  213. setFillColorSpace: 51,
  214. setStrokeColor: 52,
  215. setStrokeColorN: 53,
  216. setFillColor: 54,
  217. setFillColorN: 55,
  218. setStrokeGray: 56,
  219. setFillGray: 57,
  220. setStrokeRGBColor: 58,
  221. setFillRGBColor: 59,
  222. setStrokeCMYKColor: 60,
  223. setFillCMYKColor: 61,
  224. shadingFill: 62,
  225. beginInlineImage: 63,
  226. beginImageData: 64,
  227. endInlineImage: 65,
  228. paintXObject: 66,
  229. markPoint: 67,
  230. markPointProps: 68,
  231. beginMarkedContent: 69,
  232. beginMarkedContentProps: 70,
  233. endMarkedContent: 71,
  234. beginCompat: 72,
  235. endCompat: 73,
  236. paintFormXObjectBegin: 74,
  237. paintFormXObjectEnd: 75,
  238. beginGroup: 76,
  239. endGroup: 77,
  240. beginAnnotations: 78,
  241. endAnnotations: 79,
  242. beginAnnotation: 80,
  243. endAnnotation: 81,
  244. paintJpegXObject: 82,
  245. paintImageMaskXObject: 83,
  246. paintImageMaskXObjectGroup: 84,
  247. paintImageXObject: 85,
  248. paintInlineImageXObject: 86,
  249. paintInlineImageXObjectGroup: 87,
  250. paintImageXObjectRepeat: 88,
  251. paintImageMaskXObjectRepeat: 89,
  252. paintSolidColorImageMask: 90,
  253. constructPath: 91
  254. };
  255. var verbosity = VERBOSITY_LEVELS.warnings;
  256. function setVerbosityLevel(level) {
  257. verbosity = level;
  258. }
  259. function getVerbosityLevel() {
  260. return verbosity;
  261. }
  262. // A notice for devs. These are good for things that are helpful to devs, such
  263. // as warning that Workers were disabled, which is important to devs but not
  264. // end users.
  265. function info(msg) {
  266. if (verbosity >= VERBOSITY_LEVELS.infos) {
  267. console.log('Info: ' + msg);
  268. }
  269. }
  270. // Non-fatal warnings.
  271. function warn(msg) {
  272. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  273. console.log('Warning: ' + msg);
  274. }
  275. }
  276. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  277. function deprecated(details) {
  278. console.log('Deprecated API usage: ' + details);
  279. }
  280. // Fatal errors that should trigger the fallback UI and halt execution by
  281. // throwing an exception.
  282. function error(msg) {
  283. if (verbosity >= VERBOSITY_LEVELS.errors) {
  284. console.log('Error: ' + msg);
  285. console.log(backtrace());
  286. }
  287. throw new Error(msg);
  288. }
  289. function backtrace() {
  290. try {
  291. throw new Error();
  292. } catch (e) {
  293. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  294. }
  295. }
  296. function assert(cond, msg) {
  297. if (!cond) {
  298. error(msg);
  299. }
  300. }
  301. var UNSUPPORTED_FEATURES = {
  302. unknown: 'unknown',
  303. forms: 'forms',
  304. javaScript: 'javaScript',
  305. smask: 'smask',
  306. shadingPattern: 'shadingPattern',
  307. font: 'font'
  308. };
  309. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  310. function isSameOrigin(baseUrl, otherUrl) {
  311. try {
  312. var base = new URL(baseUrl);
  313. if (!base.origin || base.origin === 'null') {
  314. return false;
  315. }
  316. } // non-HTTP url
  317. catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  324. function isValidUrl(url, allowRelative) {
  325. if (!url || typeof url !== 'string') {
  326. return false;
  327. }
  328. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  329. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  330. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  331. if (!protocol) {
  332. return allowRelative;
  333. }
  334. protocol = protocol[0].toLowerCase();
  335. switch (protocol) {
  336. case 'http':
  337. case 'https':
  338. case 'ftp':
  339. case 'mailto':
  340. case 'tel':
  341. return true;
  342. default:
  343. return false;
  344. }
  345. }
  346. function shadow(obj, prop, value) {
  347. Object.defineProperty(obj, prop, {
  348. value: value,
  349. enumerable: true,
  350. configurable: true,
  351. writable: false
  352. });
  353. return value;
  354. }
  355. function getLookupTableFactory(initializer) {
  356. var lookup;
  357. return function () {
  358. if (initializer) {
  359. lookup = Object.create(null);
  360. initializer(lookup);
  361. initializer = null;
  362. }
  363. return lookup;
  364. };
  365. }
  366. var PasswordResponses = {
  367. NEED_PASSWORD: 1,
  368. INCORRECT_PASSWORD: 2
  369. };
  370. var PasswordException = function PasswordExceptionClosure() {
  371. function PasswordException(msg, code) {
  372. this.name = 'PasswordException';
  373. this.message = msg;
  374. this.code = code;
  375. }
  376. PasswordException.prototype = new Error();
  377. PasswordException.constructor = PasswordException;
  378. return PasswordException;
  379. }();
  380. var UnknownErrorException = function UnknownErrorExceptionClosure() {
  381. function UnknownErrorException(msg, details) {
  382. this.name = 'UnknownErrorException';
  383. this.message = msg;
  384. this.details = details;
  385. }
  386. UnknownErrorException.prototype = new Error();
  387. UnknownErrorException.constructor = UnknownErrorException;
  388. return UnknownErrorException;
  389. }();
  390. var InvalidPDFException = function InvalidPDFExceptionClosure() {
  391. function InvalidPDFException(msg) {
  392. this.name = 'InvalidPDFException';
  393. this.message = msg;
  394. }
  395. InvalidPDFException.prototype = new Error();
  396. InvalidPDFException.constructor = InvalidPDFException;
  397. return InvalidPDFException;
  398. }();
  399. var MissingPDFException = function MissingPDFExceptionClosure() {
  400. function MissingPDFException(msg) {
  401. this.name = 'MissingPDFException';
  402. this.message = msg;
  403. }
  404. MissingPDFException.prototype = new Error();
  405. MissingPDFException.constructor = MissingPDFException;
  406. return MissingPDFException;
  407. }();
  408. var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
  409. function UnexpectedResponseException(msg, status) {
  410. this.name = 'UnexpectedResponseException';
  411. this.message = msg;
  412. this.status = status;
  413. }
  414. UnexpectedResponseException.prototype = new Error();
  415. UnexpectedResponseException.constructor = UnexpectedResponseException;
  416. return UnexpectedResponseException;
  417. }();
  418. var NotImplementedException = function NotImplementedExceptionClosure() {
  419. function NotImplementedException(msg) {
  420. this.message = msg;
  421. }
  422. NotImplementedException.prototype = new Error();
  423. NotImplementedException.prototype.name = 'NotImplementedException';
  424. NotImplementedException.constructor = NotImplementedException;
  425. return NotImplementedException;
  426. }();
  427. var MissingDataException = function MissingDataExceptionClosure() {
  428. function MissingDataException(begin, end) {
  429. this.begin = begin;
  430. this.end = end;
  431. this.message = 'Missing data [' + begin + ', ' + end + ')';
  432. }
  433. MissingDataException.prototype = new Error();
  434. MissingDataException.prototype.name = 'MissingDataException';
  435. MissingDataException.constructor = MissingDataException;
  436. return MissingDataException;
  437. }();
  438. var XRefParseException = function XRefParseExceptionClosure() {
  439. function XRefParseException(msg) {
  440. this.message = msg;
  441. }
  442. XRefParseException.prototype = new Error();
  443. XRefParseException.prototype.name = 'XRefParseException';
  444. XRefParseException.constructor = XRefParseException;
  445. return XRefParseException;
  446. }();
  447. var NullCharactersRegExp = /\x00/g;
  448. function removeNullCharacters(str) {
  449. if (typeof str !== 'string') {
  450. warn('The argument for removeNullCharacters must be a string.');
  451. return str;
  452. }
  453. return str.replace(NullCharactersRegExp, '');
  454. }
  455. function bytesToString(bytes) {
  456. assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
  457. var length = bytes.length;
  458. var MAX_ARGUMENT_COUNT = 8192;
  459. if (length < MAX_ARGUMENT_COUNT) {
  460. return String.fromCharCode.apply(null, bytes);
  461. }
  462. var strBuf = [];
  463. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  464. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  465. var chunk = bytes.subarray(i, chunkEnd);
  466. strBuf.push(String.fromCharCode.apply(null, chunk));
  467. }
  468. return strBuf.join('');
  469. }
  470. function stringToBytes(str) {
  471. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  472. var length = str.length;
  473. var bytes = new Uint8Array(length);
  474. for (var i = 0; i < length; ++i) {
  475. bytes[i] = str.charCodeAt(i) & 0xFF;
  476. }
  477. return bytes;
  478. }
  479. /**
  480. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  481. * @param {Array|Uint8Array|string} arr
  482. * @returns {number}
  483. */
  484. function arrayByteLength(arr) {
  485. if (arr.length !== undefined) {
  486. return arr.length;
  487. }
  488. assert(arr.byteLength !== undefined);
  489. return arr.byteLength;
  490. }
  491. /**
  492. * Combines array items (arrays) into single Uint8Array object.
  493. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  494. * @returns {Uint8Array}
  495. */
  496. function arraysToBytes(arr) {
  497. // Shortcut: if first and only item is Uint8Array, return it.
  498. if (arr.length === 1 && arr[0] instanceof Uint8Array) {
  499. return arr[0];
  500. }
  501. var resultLength = 0;
  502. var i, ii = arr.length;
  503. var item, itemLength;
  504. for (i = 0; i < ii; i++) {
  505. item = arr[i];
  506. itemLength = arrayByteLength(item);
  507. resultLength += itemLength;
  508. }
  509. var pos = 0;
  510. var data = new Uint8Array(resultLength);
  511. for (i = 0; i < ii; i++) {
  512. item = arr[i];
  513. if (!(item instanceof Uint8Array)) {
  514. if (typeof item === 'string') {
  515. item = stringToBytes(item);
  516. } else {
  517. item = new Uint8Array(item);
  518. }
  519. }
  520. itemLength = item.byteLength;
  521. data.set(item, pos);
  522. pos += itemLength;
  523. }
  524. return data;
  525. }
  526. function string32(value) {
  527. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  528. }
  529. function log2(x) {
  530. var n = 1, i = 0;
  531. while (x > n) {
  532. n <<= 1;
  533. i++;
  534. }
  535. return i;
  536. }
  537. function readInt8(data, start) {
  538. return data[start] << 24 >> 24;
  539. }
  540. function readUint16(data, offset) {
  541. return data[offset] << 8 | data[offset + 1];
  542. }
  543. function readUint32(data, offset) {
  544. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  545. }
  546. // Lazy test the endianness of the platform
  547. // NOTE: This will be 'true' for simulated TypedArrays
  548. function isLittleEndian() {
  549. var buffer8 = new Uint8Array(2);
  550. buffer8[0] = 1;
  551. var buffer16 = new Uint16Array(buffer8.buffer);
  552. return buffer16[0] === 1;
  553. }
  554. // Checks if it's possible to eval JS expressions.
  555. function isEvalSupported() {
  556. try {
  557. new Function('');
  558. return true;
  559. } catch (e) {
  560. return false;
  561. }
  562. }
  563. var Uint32ArrayView = function Uint32ArrayViewClosure() {
  564. function Uint32ArrayView(buffer, length) {
  565. this.buffer = buffer;
  566. this.byteLength = buffer.length;
  567. this.length = length === undefined ? this.byteLength >> 2 : length;
  568. ensureUint32ArrayViewProps(this.length);
  569. }
  570. Uint32ArrayView.prototype = Object.create(null);
  571. var uint32ArrayViewSetters = 0;
  572. function createUint32ArrayProp(index) {
  573. return {
  574. get: function () {
  575. var buffer = this.buffer, offset = index << 2;
  576. return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
  577. },
  578. set: function (value) {
  579. var buffer = this.buffer, offset = index << 2;
  580. buffer[offset] = value & 255;
  581. buffer[offset + 1] = value >> 8 & 255;
  582. buffer[offset + 2] = value >> 16 & 255;
  583. buffer[offset + 3] = value >>> 24 & 255;
  584. }
  585. };
  586. }
  587. function ensureUint32ArrayViewProps(length) {
  588. while (uint32ArrayViewSetters < length) {
  589. Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
  590. uint32ArrayViewSetters++;
  591. }
  592. }
  593. return Uint32ArrayView;
  594. }();
  595. exports.Uint32ArrayView = Uint32ArrayView;
  596. var IDENTITY_MATRIX = [
  597. 1,
  598. 0,
  599. 0,
  600. 1,
  601. 0,
  602. 0
  603. ];
  604. var Util = function UtilClosure() {
  605. function Util() {
  606. }
  607. var rgbBuf = [
  608. 'rgb(',
  609. 0,
  610. ',',
  611. 0,
  612. ',',
  613. 0,
  614. ')'
  615. ];
  616. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  617. // creating many intermediate strings.
  618. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  619. rgbBuf[1] = r;
  620. rgbBuf[3] = g;
  621. rgbBuf[5] = b;
  622. return rgbBuf.join('');
  623. };
  624. // Concatenates two transformation matrices together and returns the result.
  625. Util.transform = function Util_transform(m1, m2) {
  626. return [
  627. m1[0] * m2[0] + m1[2] * m2[1],
  628. m1[1] * m2[0] + m1[3] * m2[1],
  629. m1[0] * m2[2] + m1[2] * m2[3],
  630. m1[1] * m2[2] + m1[3] * m2[3],
  631. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  632. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  633. ];
  634. };
  635. // For 2d affine transforms
  636. Util.applyTransform = function Util_applyTransform(p, m) {
  637. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  638. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  639. return [
  640. xt,
  641. yt
  642. ];
  643. };
  644. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  645. var d = m[0] * m[3] - m[1] * m[2];
  646. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  647. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  648. return [
  649. xt,
  650. yt
  651. ];
  652. };
  653. // Applies the transform to the rectangle and finds the minimum axially
  654. // aligned bounding box.
  655. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
  656. var p1 = Util.applyTransform(r, m);
  657. var p2 = Util.applyTransform(r.slice(2, 4), m);
  658. var p3 = Util.applyTransform([
  659. r[0],
  660. r[3]
  661. ], m);
  662. var p4 = Util.applyTransform([
  663. r[2],
  664. r[1]
  665. ], m);
  666. return [
  667. Math.min(p1[0], p2[0], p3[0], p4[0]),
  668. Math.min(p1[1], p2[1], p3[1], p4[1]),
  669. Math.max(p1[0], p2[0], p3[0], p4[0]),
  670. Math.max(p1[1], p2[1], p3[1], p4[1])
  671. ];
  672. };
  673. Util.inverseTransform = function Util_inverseTransform(m) {
  674. var d = m[0] * m[3] - m[1] * m[2];
  675. return [
  676. m[3] / d,
  677. -m[1] / d,
  678. -m[2] / d,
  679. m[0] / d,
  680. (m[2] * m[5] - m[4] * m[3]) / d,
  681. (m[4] * m[1] - m[5] * m[0]) / d
  682. ];
  683. };
  684. // Apply a generic 3d matrix M on a 3-vector v:
  685. // | a b c | | X |
  686. // | d e f | x | Y |
  687. // | g h i | | Z |
  688. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  689. // with v as [X,Y,Z]
  690. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  691. return [
  692. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  693. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  694. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  695. ];
  696. };
  697. // This calculation uses Singular Value Decomposition.
  698. // The SVD can be represented with formula A = USV. We are interested in the
  699. // matrix S here because it represents the scale values.
  700. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
  701. var transpose = [
  702. m[0],
  703. m[2],
  704. m[1],
  705. m[3]
  706. ];
  707. // Multiply matrix m with its transpose.
  708. var a = m[0] * transpose[0] + m[1] * transpose[2];
  709. var b = m[0] * transpose[1] + m[1] * transpose[3];
  710. var c = m[2] * transpose[0] + m[3] * transpose[2];
  711. var d = m[2] * transpose[1] + m[3] * transpose[3];
  712. // Solve the second degree polynomial to get roots.
  713. var first = (a + d) / 2;
  714. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  715. var sx = first + second || 1;
  716. var sy = first - second || 1;
  717. // Scale values are the square roots of the eigenvalues.
  718. return [
  719. Math.sqrt(sx),
  720. Math.sqrt(sy)
  721. ];
  722. };
  723. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  724. // For coordinate systems whose origin lies in the bottom-left, this
  725. // means normalization to (BL,TR) ordering. For systems with origin in the
  726. // top-left, this means (TL,BR) ordering.
  727. Util.normalizeRect = function Util_normalizeRect(rect) {
  728. var r = rect.slice(0);
  729. // clone rect
  730. if (rect[0] > rect[2]) {
  731. r[0] = rect[2];
  732. r[2] = rect[0];
  733. }
  734. if (rect[1] > rect[3]) {
  735. r[1] = rect[3];
  736. r[3] = rect[1];
  737. }
  738. return r;
  739. };
  740. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  741. // intersection of rect1 and rect2. If no intersection, returns 'false'
  742. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  743. Util.intersect = function Util_intersect(rect1, rect2) {
  744. function compare(a, b) {
  745. return a - b;
  746. }
  747. // Order points along the axes
  748. var orderedX = [
  749. rect1[0],
  750. rect1[2],
  751. rect2[0],
  752. rect2[2]
  753. ].sort(compare), orderedY = [
  754. rect1[1],
  755. rect1[3],
  756. rect2[1],
  757. rect2[3]
  758. ].sort(compare), result = [];
  759. rect1 = Util.normalizeRect(rect1);
  760. rect2 = Util.normalizeRect(rect2);
  761. // X: first and second points belong to different rectangles?
  762. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  763. // Intersection must be between second and third points
  764. result[0] = orderedX[1];
  765. result[2] = orderedX[2];
  766. } else {
  767. return false;
  768. }
  769. // Y: first and second points belong to different rectangles?
  770. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  771. // Intersection must be between second and third points
  772. result[1] = orderedY[1];
  773. result[3] = orderedY[2];
  774. } else {
  775. return false;
  776. }
  777. return result;
  778. };
  779. Util.sign = function Util_sign(num) {
  780. return num < 0 ? -1 : 1;
  781. };
  782. var ROMAN_NUMBER_MAP = [
  783. '',
  784. 'C',
  785. 'CC',
  786. 'CCC',
  787. 'CD',
  788. 'D',
  789. 'DC',
  790. 'DCC',
  791. 'DCCC',
  792. 'CM',
  793. '',
  794. 'X',
  795. 'XX',
  796. 'XXX',
  797. 'XL',
  798. 'L',
  799. 'LX',
  800. 'LXX',
  801. 'LXXX',
  802. 'XC',
  803. '',
  804. 'I',
  805. 'II',
  806. 'III',
  807. 'IV',
  808. 'V',
  809. 'VI',
  810. 'VII',
  811. 'VIII',
  812. 'IX'
  813. ];
  814. /**
  815. * Converts positive integers to (upper case) Roman numerals.
  816. * @param {integer} number - The number that should be converted.
  817. * @param {boolean} lowerCase - Indicates if the result should be converted
  818. * to lower case letters. The default is false.
  819. * @return {string} The resulting Roman number.
  820. */
  821. Util.toRoman = function Util_toRoman(number, lowerCase) {
  822. assert(isInt(number) && number > 0, 'The number should be a positive integer.');
  823. var pos, romanBuf = [];
  824. // Thousands
  825. while (number >= 1000) {
  826. number -= 1000;
  827. romanBuf.push('M');
  828. }
  829. // Hundreds
  830. pos = number / 100 | 0;
  831. number %= 100;
  832. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  833. // Tens
  834. pos = number / 10 | 0;
  835. number %= 10;
  836. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  837. // Ones
  838. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  839. var romanStr = romanBuf.join('');
  840. return lowerCase ? romanStr.toLowerCase() : romanStr;
  841. };
  842. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  843. Array.prototype.push.apply(arr1, arr2);
  844. };
  845. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  846. Array.prototype.unshift.apply(arr1, arr2);
  847. };
  848. Util.extendObj = function extendObj(obj1, obj2) {
  849. for (var key in obj2) {
  850. obj1[key] = obj2[key];
  851. }
  852. };
  853. Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
  854. while (dict && !dict.has(name)) {
  855. dict = dict.get('Parent');
  856. }
  857. if (!dict) {
  858. return null;
  859. }
  860. return getArray ? dict.getArray(name) : dict.get(name);
  861. };
  862. Util.inherit = function Util_inherit(sub, base, prototype) {
  863. sub.prototype = Object.create(base.prototype);
  864. sub.prototype.constructor = sub;
  865. for (var prop in prototype) {
  866. sub.prototype[prop] = prototype[prop];
  867. }
  868. };
  869. Util.loadScript = function Util_loadScript(src, callback) {
  870. var script = document.createElement('script');
  871. var loaded = false;
  872. script.setAttribute('src', src);
  873. if (callback) {
  874. script.onload = function () {
  875. if (!loaded) {
  876. callback();
  877. }
  878. loaded = true;
  879. };
  880. }
  881. document.getElementsByTagName('head')[0].appendChild(script);
  882. };
  883. return Util;
  884. }();
  885. /**
  886. * PDF page viewport created based on scale, rotation and offset.
  887. * @class
  888. * @alias PageViewport
  889. */
  890. var PageViewport = function PageViewportClosure() {
  891. /**
  892. * @constructor
  893. * @private
  894. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  895. * @param scale {number} scale of the viewport.
  896. * @param rotation {number} rotations of the viewport in degrees.
  897. * @param offsetX {number} offset X
  898. * @param offsetY {number} offset Y
  899. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  900. */
  901. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  902. this.viewBox = viewBox;
  903. this.scale = scale;
  904. this.rotation = rotation;
  905. this.offsetX = offsetX;
  906. this.offsetY = offsetY;
  907. // creating transform to convert pdf coordinate system to the normal
  908. // canvas like coordinates taking in account scale and rotation
  909. var centerX = (viewBox[2] + viewBox[0]) / 2;
  910. var centerY = (viewBox[3] + viewBox[1]) / 2;
  911. var rotateA, rotateB, rotateC, rotateD;
  912. rotation = rotation % 360;
  913. rotation = rotation < 0 ? rotation + 360 : rotation;
  914. switch (rotation) {
  915. case 180:
  916. rotateA = -1;
  917. rotateB = 0;
  918. rotateC = 0;
  919. rotateD = 1;
  920. break;
  921. case 90:
  922. rotateA = 0;
  923. rotateB = 1;
  924. rotateC = 1;
  925. rotateD = 0;
  926. break;
  927. case 270:
  928. rotateA = 0;
  929. rotateB = -1;
  930. rotateC = -1;
  931. rotateD = 0;
  932. break;
  933. //case 0:
  934. default:
  935. rotateA = 1;
  936. rotateB = 0;
  937. rotateC = 0;
  938. rotateD = -1;
  939. break;
  940. }
  941. if (dontFlip) {
  942. rotateC = -rotateC;
  943. rotateD = -rotateD;
  944. }
  945. var offsetCanvasX, offsetCanvasY;
  946. var width, height;
  947. if (rotateA === 0) {
  948. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  949. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  950. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  951. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  952. } else {
  953. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  954. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  955. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  956. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  957. }
  958. // creating transform for the following operations:
  959. // translate(-centerX, -centerY), rotate and flip vertically,
  960. // scale, and translate(offsetCanvasX, offsetCanvasY)
  961. this.transform = [
  962. rotateA * scale,
  963. rotateB * scale,
  964. rotateC * scale,
  965. rotateD * scale,
  966. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  967. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  968. ];
  969. this.width = width;
  970. this.height = height;
  971. this.fontScale = scale;
  972. }
  973. PageViewport.prototype = /** @lends PageViewport.prototype */
  974. {
  975. /**
  976. * Clones viewport with additional properties.
  977. * @param args {Object} (optional) If specified, may contain the 'scale' or
  978. * 'rotation' properties to override the corresponding properties in
  979. * the cloned viewport.
  980. * @returns {PageViewport} Cloned viewport.
  981. */
  982. clone: function PageViewPort_clone(args) {
  983. args = args || {};
  984. var scale = 'scale' in args ? args.scale : this.scale;
  985. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  986. return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
  987. },
  988. /**
  989. * Converts PDF point to the viewport coordinates. For examples, useful for
  990. * converting PDF location into canvas pixel coordinates.
  991. * @param x {number} X coordinate.
  992. * @param y {number} Y coordinate.
  993. * @returns {Object} Object that contains 'x' and 'y' properties of the
  994. * point in the viewport coordinate space.
  995. * @see {@link convertToPdfPoint}
  996. * @see {@link convertToViewportRectangle}
  997. */
  998. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  999. return Util.applyTransform([
  1000. x,
  1001. y
  1002. ], this.transform);
  1003. },
  1004. /**
  1005. * Converts PDF rectangle to the viewport coordinates.
  1006. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  1007. * @returns {Array} Contains corresponding coordinates of the rectangle
  1008. * in the viewport coordinate space.
  1009. * @see {@link convertToViewportPoint}
  1010. */
  1011. convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
  1012. var tl = Util.applyTransform([
  1013. rect[0],
  1014. rect[1]
  1015. ], this.transform);
  1016. var br = Util.applyTransform([
  1017. rect[2],
  1018. rect[3]
  1019. ], this.transform);
  1020. return [
  1021. tl[0],
  1022. tl[1],
  1023. br[0],
  1024. br[1]
  1025. ];
  1026. },
  1027. /**
  1028. * Converts viewport coordinates to the PDF location. For examples, useful
  1029. * for converting canvas pixel location into PDF one.
  1030. * @param x {number} X coordinate.
  1031. * @param y {number} Y coordinate.
  1032. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1033. * point in the PDF coordinate space.
  1034. * @see {@link convertToViewportPoint}
  1035. */
  1036. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  1037. return Util.applyInverseTransform([
  1038. x,
  1039. y
  1040. ], this.transform);
  1041. }
  1042. };
  1043. return PageViewport;
  1044. }();
  1045. var PDFStringTranslateTable = [
  1046. 0,
  1047. 0,
  1048. 0,
  1049. 0,
  1050. 0,
  1051. 0,
  1052. 0,
  1053. 0,
  1054. 0,
  1055. 0,
  1056. 0,
  1057. 0,
  1058. 0,
  1059. 0,
  1060. 0,
  1061. 0,
  1062. 0,
  1063. 0,
  1064. 0,
  1065. 0,
  1066. 0,
  1067. 0,
  1068. 0,
  1069. 0,
  1070. 0x2D8,
  1071. 0x2C7,
  1072. 0x2C6,
  1073. 0x2D9,
  1074. 0x2DD,
  1075. 0x2DB,
  1076. 0x2DA,
  1077. 0x2DC,
  1078. 0,
  1079. 0,
  1080. 0,
  1081. 0,
  1082. 0,
  1083. 0,
  1084. 0,
  1085. 0,
  1086. 0,
  1087. 0,
  1088. 0,
  1089. 0,
  1090. 0,
  1091. 0,
  1092. 0,
  1093. 0,
  1094. 0,
  1095. 0,
  1096. 0,
  1097. 0,
  1098. 0,
  1099. 0,
  1100. 0,
  1101. 0,
  1102. 0,
  1103. 0,
  1104. 0,
  1105. 0,
  1106. 0,
  1107. 0,
  1108. 0,
  1109. 0,
  1110. 0,
  1111. 0,
  1112. 0,
  1113. 0,
  1114. 0,
  1115. 0,
  1116. 0,
  1117. 0,
  1118. 0,
  1119. 0,
  1120. 0,
  1121. 0,
  1122. 0,
  1123. 0,
  1124. 0,
  1125. 0,
  1126. 0,
  1127. 0,
  1128. 0,
  1129. 0,
  1130. 0,
  1131. 0,
  1132. 0,
  1133. 0,
  1134. 0,
  1135. 0,
  1136. 0,
  1137. 0,
  1138. 0,
  1139. 0,
  1140. 0,
  1141. 0,
  1142. 0,
  1143. 0,
  1144. 0,
  1145. 0,
  1146. 0,
  1147. 0,
  1148. 0,
  1149. 0,
  1150. 0,
  1151. 0,
  1152. 0,
  1153. 0,
  1154. 0,
  1155. 0,
  1156. 0,
  1157. 0,
  1158. 0,
  1159. 0,
  1160. 0,
  1161. 0,
  1162. 0,
  1163. 0,
  1164. 0,
  1165. 0,
  1166. 0,
  1167. 0,
  1168. 0,
  1169. 0,
  1170. 0,
  1171. 0,
  1172. 0,
  1173. 0,
  1174. 0x2022,
  1175. 0x2020,
  1176. 0x2021,
  1177. 0x2026,
  1178. 0x2014,
  1179. 0x2013,
  1180. 0x192,
  1181. 0x2044,
  1182. 0x2039,
  1183. 0x203A,
  1184. 0x2212,
  1185. 0x2030,
  1186. 0x201E,
  1187. 0x201C,
  1188. 0x201D,
  1189. 0x2018,
  1190. 0x2019,
  1191. 0x201A,
  1192. 0x2122,
  1193. 0xFB01,
  1194. 0xFB02,
  1195. 0x141,
  1196. 0x152,
  1197. 0x160,
  1198. 0x178,
  1199. 0x17D,
  1200. 0x131,
  1201. 0x142,
  1202. 0x153,
  1203. 0x161,
  1204. 0x17E,
  1205. 0,
  1206. 0x20AC
  1207. ];
  1208. function stringToPDFString(str) {
  1209. var i, n = str.length, strBuf = [];
  1210. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1211. // UTF16BE BOM
  1212. for (i = 2; i < n; i += 2) {
  1213. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1214. }
  1215. } else {
  1216. for (i = 0; i < n; ++i) {
  1217. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1218. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1219. }
  1220. }
  1221. return strBuf.join('');
  1222. }
  1223. function stringToUTF8String(str) {
  1224. return decodeURIComponent(escape(str));
  1225. }
  1226. function utf8StringToString(str) {
  1227. return unescape(encodeURIComponent(str));
  1228. }
  1229. function isEmptyObj(obj) {
  1230. for (var key in obj) {
  1231. return false;
  1232. }
  1233. return true;
  1234. }
  1235. function isBool(v) {
  1236. return typeof v === 'boolean';
  1237. }
  1238. function isInt(v) {
  1239. return typeof v === 'number' && (v | 0) === v;
  1240. }
  1241. function isNum(v) {
  1242. return typeof v === 'number';
  1243. }
  1244. function isString(v) {
  1245. return typeof v === 'string';
  1246. }
  1247. function isArray(v) {
  1248. return v instanceof Array;
  1249. }
  1250. function isArrayBuffer(v) {
  1251. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1252. }
  1253. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1254. function isSpace(ch) {
  1255. return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
  1256. }
  1257. /**
  1258. * Promise Capability object.
  1259. *
  1260. * @typedef {Object} PromiseCapability
  1261. * @property {Promise} promise - A promise object.
  1262. * @property {function} resolve - Fulfills the promise.
  1263. * @property {function} reject - Rejects the promise.
  1264. */
  1265. /**
  1266. * Creates a promise capability object.
  1267. * @alias createPromiseCapability
  1268. *
  1269. * @return {PromiseCapability} A capability object contains:
  1270. * - a Promise, resolve and reject methods.
  1271. */
  1272. function createPromiseCapability() {
  1273. var capability = {};
  1274. capability.promise = new Promise(function (resolve, reject) {
  1275. capability.resolve = resolve;
  1276. capability.reject = reject;
  1277. });
  1278. return capability;
  1279. }
  1280. /**
  1281. * Polyfill for Promises:
  1282. * The following promise implementation tries to generally implement the
  1283. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1284. * - There currently isn't a separate deferred and promise object.
  1285. * - Unhandled rejections eventually show an error if they aren't handled.
  1286. *
  1287. * Based off of the work in:
  1288. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1289. */
  1290. (function PromiseClosure() {
  1291. if (globalScope.Promise) {
  1292. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1293. if (typeof globalScope.Promise.all !== 'function') {
  1294. globalScope.Promise.all = function (iterable) {
  1295. var count = 0, results = [], resolve, reject;
  1296. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1297. resolve = resolve_;
  1298. reject = reject_;
  1299. });
  1300. iterable.forEach(function (p, i) {
  1301. count++;
  1302. p.then(function (result) {
  1303. results[i] = result;
  1304. count--;
  1305. if (count === 0) {
  1306. resolve(results);
  1307. }
  1308. }, reject);
  1309. });
  1310. if (count === 0) {
  1311. resolve(results);
  1312. }
  1313. return promise;
  1314. };
  1315. }
  1316. if (typeof globalScope.Promise.resolve !== 'function') {
  1317. globalScope.Promise.resolve = function (value) {
  1318. return new globalScope.Promise(function (resolve) {
  1319. resolve(value);
  1320. });
  1321. };
  1322. }
  1323. if (typeof globalScope.Promise.reject !== 'function') {
  1324. globalScope.Promise.reject = function (reason) {
  1325. return new globalScope.Promise(function (resolve, reject) {
  1326. reject(reason);
  1327. });
  1328. };
  1329. }
  1330. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1331. globalScope.Promise.prototype.catch = function (onReject) {
  1332. return globalScope.Promise.prototype.then(undefined, onReject);
  1333. };
  1334. }
  1335. return;
  1336. }
  1337. var STATUS_PENDING = 0;
  1338. var STATUS_RESOLVED = 1;
  1339. var STATUS_REJECTED = 2;
  1340. // In an attempt to avoid silent exceptions, unhandled rejections are
  1341. // tracked and if they aren't handled in a certain amount of time an
  1342. // error is logged.
  1343. var REJECTION_TIMEOUT = 500;
  1344. var HandlerManager = {
  1345. handlers: [],
  1346. running: false,
  1347. unhandledRejections: [],
  1348. pendingRejectionCheck: false,
  1349. scheduleHandlers: function scheduleHandlers(promise) {
  1350. if (promise._status === STATUS_PENDING) {
  1351. return;
  1352. }
  1353. this.handlers = this.handlers.concat(promise._handlers);
  1354. promise._handlers = [];
  1355. if (this.running) {
  1356. return;
  1357. }
  1358. this.running = true;
  1359. setTimeout(this.runHandlers.bind(this), 0);
  1360. },
  1361. runHandlers: function runHandlers() {
  1362. var RUN_TIMEOUT = 1;
  1363. // ms
  1364. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1365. while (this.handlers.length > 0) {
  1366. var handler = this.handlers.shift();
  1367. var nextStatus = handler.thisPromise._status;
  1368. var nextValue = handler.thisPromise._value;
  1369. try {
  1370. if (nextStatus === STATUS_RESOLVED) {
  1371. if (typeof handler.onResolve === 'function') {
  1372. nextValue = handler.onResolve(nextValue);
  1373. }
  1374. } else if (typeof handler.onReject === 'function') {
  1375. nextValue = handler.onReject(nextValue);
  1376. nextStatus = STATUS_RESOLVED;
  1377. if (handler.thisPromise._unhandledRejection) {
  1378. this.removeUnhandeledRejection(handler.thisPromise);
  1379. }
  1380. }
  1381. } catch (ex) {
  1382. nextStatus = STATUS_REJECTED;
  1383. nextValue = ex;
  1384. }
  1385. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1386. if (Date.now() >= timeoutAt) {
  1387. break;
  1388. }
  1389. }
  1390. if (this.handlers.length > 0) {
  1391. setTimeout(this.runHandlers.bind(this), 0);
  1392. return;
  1393. }
  1394. this.running = false;
  1395. },
  1396. addUnhandledRejection: function addUnhandledRejection(promise) {
  1397. this.unhandledRejections.push({
  1398. promise: promise,
  1399. time: Date.now()
  1400. });
  1401. this.scheduleRejectionCheck();
  1402. },
  1403. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1404. promise._unhandledRejection = false;
  1405. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1406. if (this.unhandledRejections[i].promise === promise) {
  1407. this.unhandledRejections.splice(i);
  1408. i--;
  1409. }
  1410. }
  1411. },
  1412. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1413. if (this.pendingRejectionCheck) {
  1414. return;
  1415. }
  1416. this.pendingRejectionCheck = true;
  1417. setTimeout(function rejectionCheck() {
  1418. this.pendingRejectionCheck = false;
  1419. var now = Date.now();
  1420. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1421. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1422. var unhandled = this.unhandledRejections[i].promise._value;
  1423. var msg = 'Unhandled rejection: ' + unhandled;
  1424. if (unhandled.stack) {
  1425. msg += '\n' + unhandled.stack;
  1426. }
  1427. warn(msg);
  1428. this.unhandledRejections.splice(i);
  1429. i--;
  1430. }
  1431. }
  1432. if (this.unhandledRejections.length) {
  1433. this.scheduleRejectionCheck();
  1434. }
  1435. }.bind(this), REJECTION_TIMEOUT);
  1436. }
  1437. };
  1438. var Promise = function Promise(resolver) {
  1439. this._status = STATUS_PENDING;
  1440. this._handlers = [];
  1441. try {
  1442. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1443. } catch (e) {
  1444. this._reject(e);
  1445. }
  1446. };
  1447. /**
  1448. * Builds a promise that is resolved when all the passed in promises are
  1449. * resolved.
  1450. * @param {array} promises array of data and/or promises to wait for.
  1451. * @return {Promise} New dependent promise.
  1452. */
  1453. Promise.all = function Promise_all(promises) {
  1454. var resolveAll, rejectAll;
  1455. var deferred = new Promise(function (resolve, reject) {
  1456. resolveAll = resolve;
  1457. rejectAll = reject;
  1458. });
  1459. var unresolved = promises.length;
  1460. var results = [];
  1461. if (unresolved === 0) {
  1462. resolveAll(results);
  1463. return deferred;
  1464. }
  1465. function reject(reason) {
  1466. if (deferred._status === STATUS_REJECTED) {
  1467. return;
  1468. }
  1469. results = [];
  1470. rejectAll(reason);
  1471. }
  1472. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1473. var promise = promises[i];
  1474. var resolve = function (i) {
  1475. return function (value) {
  1476. if (deferred._status === STATUS_REJECTED) {
  1477. return;
  1478. }
  1479. results[i] = value;
  1480. unresolved--;
  1481. if (unresolved === 0) {
  1482. resolveAll(results);
  1483. }
  1484. };
  1485. }(i);
  1486. if (Promise.isPromise(promise)) {
  1487. promise.then(resolve, reject);
  1488. } else {
  1489. resolve(promise);
  1490. }
  1491. }
  1492. return deferred;
  1493. };
  1494. /**
  1495. * Checks if the value is likely a promise (has a 'then' function).
  1496. * @return {boolean} true if value is thenable
  1497. */
  1498. Promise.isPromise = function Promise_isPromise(value) {
  1499. return value && typeof value.then === 'function';
  1500. };
  1501. /**
  1502. * Creates resolved promise
  1503. * @param value resolve value
  1504. * @returns {Promise}
  1505. */
  1506. Promise.resolve = function Promise_resolve(value) {
  1507. return new Promise(function (resolve) {
  1508. resolve(value);
  1509. });
  1510. };
  1511. /**
  1512. * Creates rejected promise
  1513. * @param reason rejection value
  1514. * @returns {Promise}
  1515. */
  1516. Promise.reject = function Promise_reject(reason) {
  1517. return new Promise(function (resolve, reject) {
  1518. reject(reason);
  1519. });
  1520. };
  1521. Promise.prototype = {
  1522. _status: null,
  1523. _value: null,
  1524. _handlers: null,
  1525. _unhandledRejection: null,
  1526. _updateStatus: function Promise__updateStatus(status, value) {
  1527. if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) {
  1528. return;
  1529. }
  1530. if (status === STATUS_RESOLVED && Promise.isPromise(value)) {
  1531. value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED));
  1532. return;
  1533. }
  1534. this._status = status;
  1535. this._value = value;
  1536. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1537. this._unhandledRejection = true;
  1538. HandlerManager.addUnhandledRejection(this);
  1539. }
  1540. HandlerManager.scheduleHandlers(this);
  1541. },
  1542. _resolve: function Promise_resolve(value) {
  1543. this._updateStatus(STATUS_RESOLVED, value);
  1544. },
  1545. _reject: function Promise_reject(reason) {
  1546. this._updateStatus(STATUS_REJECTED, reason);
  1547. },
  1548. then: function Promise_then(onResolve, onReject) {
  1549. var nextPromise = new Promise(function (resolve, reject) {
  1550. this.resolve = resolve;
  1551. this.reject = reject;
  1552. });
  1553. this._handlers.push({
  1554. thisPromise: this,
  1555. onResolve: onResolve,
  1556. onReject: onReject,
  1557. nextPromise: nextPromise
  1558. });
  1559. HandlerManager.scheduleHandlers(this);
  1560. return nextPromise;
  1561. },
  1562. catch: function Promise_catch(onReject) {
  1563. return this.then(undefined, onReject);
  1564. }
  1565. };
  1566. globalScope.Promise = Promise;
  1567. }());
  1568. (function WeakMapClosure() {
  1569. if (globalScope.WeakMap) {
  1570. return;
  1571. }
  1572. var id = 0;
  1573. function WeakMap() {
  1574. this.id = '$weakmap' + id++;
  1575. }
  1576. WeakMap.prototype = {
  1577. has: function (obj) {
  1578. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1579. },
  1580. get: function (obj, defaultValue) {
  1581. return this.has(obj) ? obj[this.id] : defaultValue;
  1582. },
  1583. set: function (obj, value) {
  1584. Object.defineProperty(obj, this.id, {
  1585. value: value,
  1586. enumerable: false,
  1587. configurable: true
  1588. });
  1589. },
  1590. delete: function (obj) {
  1591. delete obj[this.id];
  1592. }
  1593. };
  1594. globalScope.WeakMap = WeakMap;
  1595. }());
  1596. var StatTimer = function StatTimerClosure() {
  1597. function rpad(str, pad, length) {
  1598. while (str.length < length) {
  1599. str += pad;
  1600. }
  1601. return str;
  1602. }
  1603. function StatTimer() {
  1604. this.started = Object.create(null);
  1605. this.times = [];
  1606. this.enabled = true;
  1607. }
  1608. StatTimer.prototype = {
  1609. time: function StatTimer_time(name) {
  1610. if (!this.enabled) {
  1611. return;
  1612. }
  1613. if (name in this.started) {
  1614. warn('Timer is already running for ' + name);
  1615. }
  1616. this.started[name] = Date.now();
  1617. },
  1618. timeEnd: function StatTimer_timeEnd(name) {
  1619. if (!this.enabled) {
  1620. return;
  1621. }
  1622. if (!(name in this.started)) {
  1623. warn('Timer has not been started for ' + name);
  1624. }
  1625. this.times.push({
  1626. 'name': name,
  1627. 'start': this.started[name],
  1628. 'end': Date.now()
  1629. });
  1630. // Remove timer from started so it can be called again.
  1631. delete this.started[name];
  1632. },
  1633. toString: function StatTimer_toString() {
  1634. var i, ii;
  1635. var times = this.times;
  1636. var out = '';
  1637. // Find the longest name for padding purposes.
  1638. var longest = 0;
  1639. for (i = 0, ii = times.length; i < ii; ++i) {
  1640. var name = times[i]['name'];
  1641. if (name.length > longest) {
  1642. longest = name.length;
  1643. }
  1644. }
  1645. for (i = 0, ii = times.length; i < ii; ++i) {
  1646. var span = times[i];
  1647. var duration = span.end - span.start;
  1648. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1649. }
  1650. return out;
  1651. }
  1652. };
  1653. return StatTimer;
  1654. }();
  1655. var createBlob = function createBlob(data, contentType) {
  1656. if (typeof Blob !== 'undefined') {
  1657. return new Blob([data], { type: contentType });
  1658. }
  1659. warn('The "Blob" constructor is not supported.');
  1660. };
  1661. var createObjectURL = function createObjectURLClosure() {
  1662. // Blob/createObjectURL is not available, falling back to data schema.
  1663. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1664. return function createObjectURL(data, contentType, forceDataSchema) {
  1665. if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
  1666. var blob = createBlob(data, contentType);
  1667. return URL.createObjectURL(blob);
  1668. }
  1669. var buffer = 'data:' + contentType + ';base64,';
  1670. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1671. var b1 = data[i] & 0xFF;
  1672. var b2 = data[i + 1] & 0xFF;
  1673. var b3 = data[i + 2] & 0xFF;
  1674. var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4;
  1675. var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
  1676. var d4 = i + 2 < ii ? b3 & 0x3F : 64;
  1677. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1678. }
  1679. return buffer;
  1680. };
  1681. }();
  1682. function MessageHandler(sourceName, targetName, comObj) {
  1683. this.sourceName = sourceName;
  1684. this.targetName = targetName;
  1685. this.comObj = comObj;
  1686. this.callbackIndex = 1;
  1687. this.postMessageTransfers = true;
  1688. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1689. var ah = this.actionHandler = Object.create(null);
  1690. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1691. var data = event.data;
  1692. if (data.targetName !== this.sourceName) {
  1693. return;
  1694. }
  1695. if (data.isReply) {
  1696. var callbackId = data.callbackId;
  1697. if (data.callbackId in callbacksCapabilities) {
  1698. var callback = callbacksCapabilities[callbackId];
  1699. delete callbacksCapabilities[callbackId];
  1700. if ('error' in data) {
  1701. callback.reject(data.error);
  1702. } else {
  1703. callback.resolve(data.data);
  1704. }
  1705. } else {
  1706. error('Cannot resolve callback ' + callbackId);
  1707. }
  1708. } else if (data.action in ah) {
  1709. var action = ah[data.action];
  1710. if (data.callbackId) {
  1711. var sourceName = this.sourceName;
  1712. var targetName = data.sourceName;
  1713. Promise.resolve().then(function () {
  1714. return action[0].call(action[1], data.data);
  1715. }).then(function (result) {
  1716. comObj.postMessage({
  1717. sourceName: sourceName,
  1718. targetName: targetName,
  1719. isReply: true,
  1720. callbackId: data.callbackId,
  1721. data: result
  1722. });
  1723. }, function (reason) {
  1724. if (reason instanceof Error) {
  1725. // Serialize error to avoid "DataCloneError"
  1726. reason = reason + '';
  1727. }
  1728. comObj.postMessage({
  1729. sourceName: sourceName,
  1730. targetName: targetName,
  1731. isReply: true,
  1732. callbackId: data.callbackId,
  1733. error: reason
  1734. });
  1735. });
  1736. } else {
  1737. action[0].call(action[1], data.data);
  1738. }
  1739. } else {
  1740. error('Unknown action from worker: ' + data.action);
  1741. }
  1742. }.bind(this);
  1743. comObj.addEventListener('message', this._onComObjOnMessage);
  1744. }
  1745. MessageHandler.prototype = {
  1746. on: function messageHandlerOn(actionName, handler, scope) {
  1747. var ah = this.actionHandler;
  1748. if (ah[actionName]) {
  1749. error('There is already an actionName called "' + actionName + '"');
  1750. }
  1751. ah[actionName] = [
  1752. handler,
  1753. scope
  1754. ];
  1755. },
  1756. /**
  1757. * Sends a message to the comObj to invoke the action with the supplied data.
  1758. * @param {String} actionName Action to call.
  1759. * @param {JSON} data JSON data to send.
  1760. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1761. */
  1762. send: function messageHandlerSend(actionName, data, transfers) {
  1763. var message = {
  1764. sourceName: this.sourceName,
  1765. targetName: this.targetName,
  1766. action: actionName,
  1767. data: data
  1768. };
  1769. this.postMessage(message, transfers);
  1770. },
  1771. /**
  1772. * Sends a message to the comObj to invoke the action with the supplied data.
  1773. * Expects that other side will callback with the response.
  1774. * @param {String} actionName Action to call.
  1775. * @param {JSON} data JSON data to send.
  1776. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1777. * @returns {Promise} Promise to be resolved with response data.
  1778. */
  1779. sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
  1780. var callbackId = this.callbackIndex++;
  1781. var message = {
  1782. sourceName: this.sourceName,
  1783. targetName: this.targetName,
  1784. action: actionName,
  1785. data: data,
  1786. callbackId: callbackId
  1787. };
  1788. var capability = createPromiseCapability();
  1789. this.callbacksCapabilities[callbackId] = capability;
  1790. try {
  1791. this.postMessage(message, transfers);
  1792. } catch (e) {
  1793. capability.reject(e);
  1794. }
  1795. return capability.promise;
  1796. },
  1797. /**
  1798. * Sends raw message to the comObj.
  1799. * @private
  1800. * @param message {Object} Raw message.
  1801. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1802. */
  1803. postMessage: function (message, transfers) {
  1804. if (transfers && this.postMessageTransfers) {
  1805. this.comObj.postMessage(message, transfers);
  1806. } else {
  1807. this.comObj.postMessage(message);
  1808. }
  1809. },
  1810. destroy: function () {
  1811. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1812. }
  1813. };
  1814. function loadJpegStream(id, imageUrl, objs) {
  1815. var img = new Image();
  1816. img.onload = function loadJpegStream_onloadClosure() {
  1817. objs.resolve(id, img);
  1818. };
  1819. img.onerror = function loadJpegStream_onerrorClosure() {
  1820. objs.resolve(id, null);
  1821. warn('Error during JPEG image loading');
  1822. };
  1823. img.src = imageUrl;
  1824. }
  1825. // Polyfill from https://github.com/Polymer/URL
  1826. /* Any copyright is dedicated to the Public Domain.
  1827. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1828. (function checkURLConstructor(scope) {
  1829. // feature detect for URL constructor
  1830. var hasWorkingUrl = false;
  1831. try {
  1832. if (typeof URL === 'function' && typeof URL.prototype === 'object' && 'origin' in URL.prototype) {
  1833. var u = new URL('b', 'http://a');
  1834. u.pathname = 'c%20d';
  1835. hasWorkingUrl = u.href === 'http://a/c%20d';
  1836. }
  1837. } catch (e) {
  1838. }
  1839. if (hasWorkingUrl) {
  1840. return;
  1841. }
  1842. var relative = Object.create(null);
  1843. relative['ftp'] = 21;
  1844. relative['file'] = 0;
  1845. relative['gopher'] = 70;
  1846. relative['http'] = 80;
  1847. relative['https'] = 443;
  1848. relative['ws'] = 80;
  1849. relative['wss'] = 443;
  1850. var relativePathDotMapping = Object.create(null);
  1851. relativePathDotMapping['%2e'] = '.';
  1852. relativePathDotMapping['.%2e'] = '..';
  1853. relativePathDotMapping['%2e.'] = '..';
  1854. relativePathDotMapping['%2e%2e'] = '..';
  1855. function isRelativeScheme(scheme) {
  1856. return relative[scheme] !== undefined;
  1857. }
  1858. function invalid() {
  1859. clear.call(this);
  1860. this._isInvalid = true;
  1861. }
  1862. function IDNAToASCII(h) {
  1863. if ('' === h) {
  1864. invalid.call(this);
  1865. }
  1866. // XXX
  1867. return h.toLowerCase();
  1868. }
  1869. function percentEscape(c) {
  1870. var unicode = c.charCodeAt(0);
  1871. if (unicode > 0x20 && unicode < 0x7F && // " # < > ? `
  1872. [
  1873. 0x22,
  1874. 0x23,
  1875. 0x3C,
  1876. 0x3E,
  1877. 0x3F,
  1878. 0x60
  1879. ].indexOf(unicode) === -1) {
  1880. return c;
  1881. }
  1882. return encodeURIComponent(c);
  1883. }
  1884. function percentEscapeQuery(c) {
  1885. // XXX This actually needs to encode c using encoding and then
  1886. // convert the bytes one-by-one.
  1887. var unicode = c.charCodeAt(0);
  1888. if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?')
  1889. [
  1890. 0x22,
  1891. 0x23,
  1892. 0x3C,
  1893. 0x3E,
  1894. 0x60
  1895. ].indexOf(unicode) === -1) {
  1896. return c;
  1897. }
  1898. return encodeURIComponent(c);
  1899. }
  1900. var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1901. function parse(input, stateOverride, base) {
  1902. function err(message) {
  1903. errors.push(message);
  1904. }
  1905. var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = [];
  1906. loop:
  1907. while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
  1908. var c = input[cursor];
  1909. switch (state) {
  1910. case 'scheme start':
  1911. if (c && ALPHA.test(c)) {
  1912. buffer += c.toLowerCase();
  1913. // ASCII-safe
  1914. state = 'scheme';
  1915. } else if (!stateOverride) {
  1916. buffer = '';
  1917. state = 'no scheme';
  1918. continue;
  1919. } else {
  1920. err('Invalid scheme.');
  1921. break loop;
  1922. }
  1923. break;
  1924. case 'scheme':
  1925. if (c && ALPHANUMERIC.test(c)) {
  1926. buffer += c.toLowerCase();
  1927. } else // ASCII-safe
  1928. if (':' === c) {
  1929. this._scheme = buffer;
  1930. buffer = '';
  1931. if (stateOverride) {
  1932. break loop;
  1933. }
  1934. if (isRelativeScheme(this._scheme)) {
  1935. this._isRelative = true;
  1936. }
  1937. if ('file' === this._scheme) {
  1938. state = 'relative';
  1939. } else if (this._isRelative && base && base._scheme === this._scheme) {
  1940. state = 'relative or authority';
  1941. } else if (this._isRelative) {
  1942. state = 'authority first slash';
  1943. } else {
  1944. state = 'scheme data';
  1945. }
  1946. } else if (!stateOverride) {
  1947. buffer = '';
  1948. cursor = 0;
  1949. state = 'no scheme';
  1950. continue;
  1951. } else if (EOF === c) {
  1952. break loop;
  1953. } else {
  1954. err('Code point not allowed in scheme: ' + c);
  1955. break loop;
  1956. }
  1957. break;
  1958. case 'scheme data':
  1959. if ('?' === c) {
  1960. this._query = '?';
  1961. state = 'query';
  1962. } else if ('#' === c) {
  1963. this._fragment = '#';
  1964. state = 'fragment';
  1965. } else {
  1966. // XXX error handling
  1967. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1968. this._schemeData += percentEscape(c);
  1969. }
  1970. }
  1971. break;
  1972. case 'no scheme':
  1973. if (!base || !isRelativeScheme(base._scheme)) {
  1974. err('Missing scheme.');
  1975. invalid.call(this);
  1976. } else {
  1977. state = 'relative';
  1978. continue;
  1979. }
  1980. break;
  1981. case 'relative or authority':
  1982. if ('/' === c && '/' === input[cursor + 1]) {
  1983. state = 'authority ignore slashes';
  1984. } else {
  1985. err('Expected /, got: ' + c);
  1986. state = 'relative';
  1987. continue;
  1988. }
  1989. break;
  1990. case 'relative':
  1991. this._isRelative = true;
  1992. if ('file' !== this._scheme) {
  1993. this._scheme = base._scheme;
  1994. }
  1995. if (EOF === c) {
  1996. this._host = base._host;
  1997. this._port = base._port;
  1998. this._path = base._path.slice();
  1999. this._query = base._query;
  2000. this._username = base._username;
  2001. this._password = base._password;
  2002. break loop;
  2003. } else if ('/' === c || '\\' === c) {
  2004. if ('\\' === c) {
  2005. err('\\ is an invalid code point.');
  2006. }
  2007. state = 'relative slash';
  2008. } else if ('?' === c) {
  2009. this._host = base._host;
  2010. this._port = base._port;
  2011. this._path = base._path.slice();
  2012. this._query = '?';
  2013. this._username = base._username;
  2014. this._password = base._password;
  2015. state = 'query';
  2016. } else if ('#' === c) {
  2017. this._host = base._host;
  2018. this._port = base._port;
  2019. this._path = base._path.slice();
  2020. this._query = base._query;
  2021. this._fragment = '#';
  2022. this._username = base._username;
  2023. this._password = base._password;
  2024. state = 'fragment';
  2025. } else {
  2026. var nextC = input[cursor + 1];
  2027. var nextNextC = input[cursor + 2];
  2028. if ('file' !== this._scheme || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC) {
  2029. this._host = base._host;
  2030. this._port = base._port;
  2031. this._username = base._username;
  2032. this._password = base._password;
  2033. this._path = base._path.slice();
  2034. this._path.pop();
  2035. }
  2036. state = 'relative path';
  2037. continue;
  2038. }
  2039. break;
  2040. case 'relative slash':
  2041. if ('/' === c || '\\' === c) {
  2042. if ('\\' === c) {
  2043. err('\\ is an invalid code point.');
  2044. }
  2045. if ('file' === this._scheme) {
  2046. state = 'file host';
  2047. } else {
  2048. state = 'authority ignore slashes';
  2049. }
  2050. } else {
  2051. if ('file' !== this._scheme) {
  2052. this._host = base._host;
  2053. this._port = base._port;
  2054. this._username = base._username;
  2055. this._password = base._password;
  2056. }
  2057. state = 'relative path';
  2058. continue;
  2059. }
  2060. break;
  2061. case 'authority first slash':
  2062. if ('/' === c) {
  2063. state = 'authority second slash';
  2064. } else {
  2065. err('Expected \'/\', got: ' + c);
  2066. state = 'authority ignore slashes';
  2067. continue;
  2068. }
  2069. break;
  2070. case 'authority second slash':
  2071. state = 'authority ignore slashes';
  2072. if ('/' !== c) {
  2073. err('Expected \'/\', got: ' + c);
  2074. continue;
  2075. }
  2076. break;
  2077. case 'authority ignore slashes':
  2078. if ('/' !== c && '\\' !== c) {
  2079. state = 'authority';
  2080. continue;
  2081. } else {
  2082. err('Expected authority, got: ' + c);
  2083. }
  2084. break;
  2085. case 'authority':
  2086. if ('@' === c) {
  2087. if (seenAt) {
  2088. err('@ already seen.');
  2089. buffer += '%40';
  2090. }
  2091. seenAt = true;
  2092. for (var i = 0; i < buffer.length; i++) {
  2093. var cp = buffer[i];
  2094. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  2095. err('Invalid whitespace in authority.');
  2096. continue;
  2097. }
  2098. // XXX check URL code points
  2099. if (':' === cp && null === this._password) {
  2100. this._password = '';
  2101. continue;
  2102. }
  2103. var tempC = percentEscape(cp);
  2104. if (null !== this._password) {
  2105. this._password += tempC;
  2106. } else {
  2107. this._username += tempC;
  2108. }
  2109. }
  2110. buffer = '';
  2111. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2112. cursor -= buffer.length;
  2113. buffer = '';
  2114. state = 'host';
  2115. continue;
  2116. } else {
  2117. buffer += c;
  2118. }
  2119. break;
  2120. case 'file host':
  2121. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2122. if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
  2123. state = 'relative path';
  2124. } else if (buffer.length === 0) {
  2125. state = 'relative path start';
  2126. } else {
  2127. this._host = IDNAToASCII.call(this, buffer);
  2128. buffer = '';
  2129. state = 'relative path start';
  2130. }
  2131. continue;
  2132. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2133. err('Invalid whitespace in file host.');
  2134. } else {
  2135. buffer += c;
  2136. }
  2137. break;
  2138. case 'host':
  2139. case 'hostname':
  2140. if (':' === c && !seenBracket) {
  2141. // XXX host parsing
  2142. this._host = IDNAToASCII.call(this, buffer);
  2143. buffer = '';
  2144. state = 'port';
  2145. if ('hostname' === stateOverride) {
  2146. break loop;
  2147. }
  2148. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2149. this._host = IDNAToASCII.call(this, buffer);
  2150. buffer = '';
  2151. state = 'relative path start';
  2152. if (stateOverride) {
  2153. break loop;
  2154. }
  2155. continue;
  2156. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2157. if ('[' === c) {
  2158. seenBracket = true;
  2159. } else if (']' === c) {
  2160. seenBracket = false;
  2161. }
  2162. buffer += c;
  2163. } else {
  2164. err('Invalid code point in host/hostname: ' + c);
  2165. }
  2166. break;
  2167. case 'port':
  2168. if (/[0-9]/.test(c)) {
  2169. buffer += c;
  2170. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) {
  2171. if ('' !== buffer) {
  2172. var temp = parseInt(buffer, 10);
  2173. if (temp !== relative[this._scheme]) {
  2174. this._port = temp + '';
  2175. }
  2176. buffer = '';
  2177. }
  2178. if (stateOverride) {
  2179. break loop;
  2180. }
  2181. state = 'relative path start';
  2182. continue;
  2183. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2184. err('Invalid code point in port: ' + c);
  2185. } else {
  2186. invalid.call(this);
  2187. }
  2188. break;
  2189. case 'relative path start':
  2190. if ('\\' === c) {
  2191. err('\'\\\' not allowed in path.');
  2192. }
  2193. state = 'relative path';
  2194. if ('/' !== c && '\\' !== c) {
  2195. continue;
  2196. }
  2197. break;
  2198. case 'relative path':
  2199. if (EOF === c || '/' === c || '\\' === c || !stateOverride && ('?' === c || '#' === c)) {
  2200. if ('\\' === c) {
  2201. err('\\ not allowed in relative path.');
  2202. }
  2203. var tmp;
  2204. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  2205. buffer = tmp;
  2206. }
  2207. if ('..' === buffer) {
  2208. this._path.pop();
  2209. if ('/' !== c && '\\' !== c) {
  2210. this._path.push('');
  2211. }
  2212. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  2213. this._path.push('');
  2214. } else if ('.' !== buffer) {
  2215. if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
  2216. buffer = buffer[0] + ':';
  2217. }
  2218. this._path.push(buffer);
  2219. }
  2220. buffer = '';
  2221. if ('?' === c) {
  2222. this._query = '?';
  2223. state = 'query';
  2224. } else if ('#' === c) {
  2225. this._fragment = '#';
  2226. state = 'fragment';
  2227. }
  2228. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2229. buffer += percentEscape(c);
  2230. }
  2231. break;
  2232. case 'query':
  2233. if (!stateOverride && '#' === c) {
  2234. this._fragment = '#';
  2235. state = 'fragment';
  2236. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2237. this._query += percentEscapeQuery(c);
  2238. }
  2239. break;
  2240. case 'fragment':
  2241. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2242. this._fragment += c;
  2243. }
  2244. break;
  2245. }
  2246. cursor++;
  2247. }
  2248. }
  2249. function clear() {
  2250. this._scheme = '';
  2251. this._schemeData = '';
  2252. this._username = '';
  2253. this._password = null;
  2254. this._host = '';
  2255. this._port = '';
  2256. this._path = [];
  2257. this._query = '';
  2258. this._fragment = '';
  2259. this._isInvalid = false;
  2260. this._isRelative = false;
  2261. }
  2262. // Does not process domain names or IP addresses.
  2263. // Does not handle encoding for the query parameter.
  2264. function JURL(url, base)
  2265. /* , encoding */
  2266. {
  2267. if (base !== undefined && !(base instanceof JURL)) {
  2268. base = new JURL(String(base));
  2269. }
  2270. this._url = url;
  2271. clear.call(this);
  2272. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2273. // encoding = encoding || 'utf-8'
  2274. parse.call(this, input, null, base);
  2275. }
  2276. JURL.prototype = {
  2277. toString: function () {
  2278. return this.href;
  2279. },
  2280. get href() {
  2281. if (this._isInvalid) {
  2282. return this._url;
  2283. }
  2284. var authority = '';
  2285. if ('' !== this._username || null !== this._password) {
  2286. authority = this._username + (null !== this._password ? ':' + this._password : '') + '@';
  2287. }
  2288. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  2289. },
  2290. set href(href) {
  2291. clear.call(this);
  2292. parse.call(this, href);
  2293. },
  2294. get protocol() {
  2295. return this._scheme + ':';
  2296. },
  2297. set protocol(protocol) {
  2298. if (this._isInvalid) {
  2299. return;
  2300. }
  2301. parse.call(this, protocol + ':', 'scheme start');
  2302. },
  2303. get host() {
  2304. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  2305. },
  2306. set host(host) {
  2307. if (this._isInvalid || !this._isRelative) {
  2308. return;
  2309. }
  2310. parse.call(this, host, 'host');
  2311. },
  2312. get hostname() {
  2313. return this._host;
  2314. },
  2315. set hostname(hostname) {
  2316. if (this._isInvalid || !this._isRelative) {
  2317. return;
  2318. }
  2319. parse.call(this, hostname, 'hostname');
  2320. },
  2321. get port() {
  2322. return this._port;
  2323. },
  2324. set port(port) {
  2325. if (this._isInvalid || !this._isRelative) {
  2326. return;
  2327. }
  2328. parse.call(this, port, 'port');
  2329. },
  2330. get pathname() {
  2331. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  2332. },
  2333. set pathname(pathname) {
  2334. if (this._isInvalid || !this._isRelative) {
  2335. return;
  2336. }
  2337. this._path = [];
  2338. parse.call(this, pathname, 'relative path start');
  2339. },
  2340. get search() {
  2341. return this._isInvalid || !this._query || '?' === this._query ? '' : this._query;
  2342. },
  2343. set search(search) {
  2344. if (this._isInvalid || !this._isRelative) {
  2345. return;
  2346. }
  2347. this._query = '?';
  2348. if ('?' === search[0]) {
  2349. search = search.slice(1);
  2350. }
  2351. parse.call(this, search, 'query');
  2352. },
  2353. get hash() {
  2354. return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment;
  2355. },
  2356. set hash(hash) {
  2357. if (this._isInvalid) {
  2358. return;
  2359. }
  2360. this._fragment = '#';
  2361. if ('#' === hash[0]) {
  2362. hash = hash.slice(1);
  2363. }
  2364. parse.call(this, hash, 'fragment');
  2365. },
  2366. get origin() {
  2367. var host;
  2368. if (this._isInvalid || !this._scheme) {
  2369. return '';
  2370. }
  2371. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2372. // Gecko throws error for "data://"
  2373. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2374. // Gecko returns String("") for file: mailto:
  2375. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2376. switch (this._scheme) {
  2377. case 'data':
  2378. case 'file':
  2379. case 'javascript':
  2380. case 'mailto':
  2381. return 'null';
  2382. }
  2383. host = this.host;
  2384. if (!host) {
  2385. return '';
  2386. }
  2387. return this._scheme + '://' + host;
  2388. }
  2389. };
  2390. // Copy over the static methods
  2391. var OriginalURL = scope.URL;
  2392. if (OriginalURL) {
  2393. JURL.createObjectURL = function (blob) {
  2394. // IE extension allows a second optional options argument.
  2395. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2396. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2397. };
  2398. JURL.revokeObjectURL = function (url) {
  2399. OriginalURL.revokeObjectURL(url);
  2400. };
  2401. }
  2402. scope.URL = JURL;
  2403. }(globalScope));
  2404. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2405. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2406. exports.OPS = OPS;
  2407. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2408. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2409. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2410. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2411. exports.AnnotationFlag = AnnotationFlag;
  2412. exports.AnnotationType = AnnotationType;
  2413. exports.FontType = FontType;
  2414. exports.ImageKind = ImageKind;
  2415. exports.InvalidPDFException = InvalidPDFException;
  2416. exports.MessageHandler = MessageHandler;
  2417. exports.MissingDataException = MissingDataException;
  2418. exports.MissingPDFException = MissingPDFException;
  2419. exports.NotImplementedException = NotImplementedException;
  2420. exports.PageViewport = PageViewport;
  2421. exports.PasswordException = PasswordException;
  2422. exports.PasswordResponses = PasswordResponses;
  2423. exports.StatTimer = StatTimer;
  2424. exports.StreamType = StreamType;
  2425. exports.TextRenderingMode = TextRenderingMode;
  2426. exports.UnexpectedResponseException = UnexpectedResponseException;
  2427. exports.UnknownErrorException = UnknownErrorException;
  2428. exports.Util = Util;
  2429. exports.XRefParseException = XRefParseException;
  2430. exports.arrayByteLength = arrayByteLength;
  2431. exports.arraysToBytes = arraysToBytes;
  2432. exports.assert = assert;
  2433. exports.bytesToString = bytesToString;
  2434. exports.createBlob = createBlob;
  2435. exports.createPromiseCapability = createPromiseCapability;
  2436. exports.createObjectURL = createObjectURL;
  2437. exports.deprecated = deprecated;
  2438. exports.error = error;
  2439. exports.getLookupTableFactory = getLookupTableFactory;
  2440. exports.getVerbosityLevel = getVerbosityLevel;
  2441. exports.globalScope = globalScope;
  2442. exports.info = info;
  2443. exports.isArray = isArray;
  2444. exports.isArrayBuffer = isArrayBuffer;
  2445. exports.isBool = isBool;
  2446. exports.isEmptyObj = isEmptyObj;
  2447. exports.isInt = isInt;
  2448. exports.isNum = isNum;
  2449. exports.isString = isString;
  2450. exports.isSpace = isSpace;
  2451. exports.isSameOrigin = isSameOrigin;
  2452. exports.isValidUrl = isValidUrl;
  2453. exports.isLittleEndian = isLittleEndian;
  2454. exports.isEvalSupported = isEvalSupported;
  2455. exports.loadJpegStream = loadJpegStream;
  2456. exports.log2 = log2;
  2457. exports.readInt8 = readInt8;
  2458. exports.readUint16 = readUint16;
  2459. exports.readUint32 = readUint32;
  2460. exports.removeNullCharacters = removeNullCharacters;
  2461. exports.setVerbosityLevel = setVerbosityLevel;
  2462. exports.shadow = shadow;
  2463. exports.string32 = string32;
  2464. exports.stringToBytes = stringToBytes;
  2465. exports.stringToPDFString = stringToPDFString;
  2466. exports.stringToUTF8String = stringToUTF8String;
  2467. exports.utf8StringToString = utf8StringToString;
  2468. exports.warn = warn;
  2469. }));
  2470. (function (root, factory) {
  2471. factory(root.pdfjsDisplayDOMUtils = {}, root.pdfjsSharedUtil);
  2472. }(this, function (exports, sharedUtil) {
  2473. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2474. var warn = sharedUtil.warn;
  2475. /**
  2476. * Optimised CSS custom property getter/setter.
  2477. * @class
  2478. */
  2479. var CustomStyle = function CustomStyleClosure() {
  2480. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2481. // animate-css-transforms-firefox-webkit.html
  2482. // in some versions of IE9 it is critical that ms appear in this list
  2483. // before Moz
  2484. var prefixes = [
  2485. 'ms',
  2486. 'Moz',
  2487. 'Webkit',
  2488. 'O'
  2489. ];
  2490. var _cache = Object.create(null);
  2491. function CustomStyle() {
  2492. }
  2493. CustomStyle.getProp = function get(propName, element) {
  2494. // check cache only when no element is given
  2495. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2496. return _cache[propName];
  2497. }
  2498. element = element || document.documentElement;
  2499. var style = element.style, prefixed, uPropName;
  2500. // test standard property first
  2501. if (typeof style[propName] === 'string') {
  2502. return _cache[propName] = propName;
  2503. }
  2504. // capitalize
  2505. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2506. // test vendor specific properties
  2507. for (var i = 0, l = prefixes.length; i < l; i++) {
  2508. prefixed = prefixes[i] + uPropName;
  2509. if (typeof style[prefixed] === 'string') {
  2510. return _cache[propName] = prefixed;
  2511. }
  2512. }
  2513. //if all fails then set to undefined
  2514. return _cache[propName] = 'undefined';
  2515. };
  2516. CustomStyle.setProp = function set(propName, element, str) {
  2517. var prop = this.getProp(propName);
  2518. if (prop !== 'undefined') {
  2519. element.style[prop] = str;
  2520. }
  2521. };
  2522. return CustomStyle;
  2523. }();
  2524. var hasCanvasTypedArrays;
  2525. hasCanvasTypedArrays = function hasCanvasTypedArrays() {
  2526. var canvas = document.createElement('canvas');
  2527. canvas.width = canvas.height = 1;
  2528. var ctx = canvas.getContext('2d');
  2529. var imageData = ctx.createImageData(1, 1);
  2530. return typeof imageData.data.buffer !== 'undefined';
  2531. };
  2532. var LinkTarget = {
  2533. NONE: 0,
  2534. // Default value.
  2535. SELF: 1,
  2536. BLANK: 2,
  2537. PARENT: 3,
  2538. TOP: 4
  2539. };
  2540. var LinkTargetStringMap = [
  2541. '',
  2542. '_self',
  2543. '_blank',
  2544. '_parent',
  2545. '_top'
  2546. ];
  2547. /**
  2548. * @typedef ExternalLinkParameters
  2549. * @typedef {Object} ExternalLinkParameters
  2550. * @property {string} url - An absolute URL.
  2551. * @property {LinkTarget} target - The link target.
  2552. * @property {string} rel - The link relationship.
  2553. */
  2554. /**
  2555. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2556. * @param {HTMLLinkElement} link - The link element.
  2557. * @param {ExternalLinkParameters} params
  2558. */
  2559. function addLinkAttributes(link, params) {
  2560. var url = params && params.url;
  2561. link.href = link.title = url ? removeNullCharacters(url) : '';
  2562. if (url) {
  2563. var target = params.target;
  2564. if (typeof target === 'undefined') {
  2565. target = getDefaultSetting('externalLinkTarget');
  2566. }
  2567. link.target = LinkTargetStringMap[target];
  2568. var rel = params.rel;
  2569. if (typeof rel === 'undefined') {
  2570. rel = getDefaultSetting('externalLinkRel');
  2571. }
  2572. link.rel = rel;
  2573. }
  2574. }
  2575. // Gets the file name from a given URL.
  2576. function getFilenameFromUrl(url) {
  2577. var anchor = url.indexOf('#');
  2578. var query = url.indexOf('?');
  2579. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  2580. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2581. }
  2582. function getDefaultSetting(id) {
  2583. // The list of the settings and their default is maintained for backward
  2584. // compatibility and shall not be extended or modified. See also global.js.
  2585. var globalSettings = sharedUtil.globalScope.PDFJS;
  2586. switch (id) {
  2587. case 'pdfBug':
  2588. return globalSettings ? globalSettings.pdfBug : false;
  2589. case 'disableAutoFetch':
  2590. return globalSettings ? globalSettings.disableAutoFetch : false;
  2591. case 'disableStream':
  2592. return globalSettings ? globalSettings.disableStream : false;
  2593. case 'disableRange':
  2594. return globalSettings ? globalSettings.disableRange : false;
  2595. case 'disableFontFace':
  2596. return globalSettings ? globalSettings.disableFontFace : false;
  2597. case 'disableCreateObjectURL':
  2598. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2599. case 'disableWebGL':
  2600. return globalSettings ? globalSettings.disableWebGL : true;
  2601. case 'cMapUrl':
  2602. return globalSettings ? globalSettings.cMapUrl : null;
  2603. case 'cMapPacked':
  2604. return globalSettings ? globalSettings.cMapPacked : false;
  2605. case 'postMessageTransfers':
  2606. return globalSettings ? globalSettings.postMessageTransfers : true;
  2607. case 'workerSrc':
  2608. return globalSettings ? globalSettings.workerSrc : null;
  2609. case 'disableWorker':
  2610. return globalSettings ? globalSettings.disableWorker : false;
  2611. case 'maxImageSize':
  2612. return globalSettings ? globalSettings.maxImageSize : -1;
  2613. case 'imageResourcesPath':
  2614. return globalSettings ? globalSettings.imageResourcesPath : '';
  2615. case 'isEvalSupported':
  2616. return globalSettings ? globalSettings.isEvalSupported : true;
  2617. case 'externalLinkTarget':
  2618. if (!globalSettings) {
  2619. return LinkTarget.NONE;
  2620. }
  2621. switch (globalSettings.externalLinkTarget) {
  2622. case LinkTarget.NONE:
  2623. case LinkTarget.SELF:
  2624. case LinkTarget.BLANK:
  2625. case LinkTarget.PARENT:
  2626. case LinkTarget.TOP:
  2627. return globalSettings.externalLinkTarget;
  2628. }
  2629. warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  2630. // Reset the external link target, to suppress further warnings.
  2631. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2632. return LinkTarget.NONE;
  2633. case 'externalLinkRel':
  2634. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2635. case 'enableStats':
  2636. return !!(globalSettings && globalSettings.enableStats);
  2637. default:
  2638. throw new Error('Unknown default setting: ' + id);
  2639. }
  2640. }
  2641. function isExternalLinkTargetSet() {
  2642. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2643. switch (externalLinkTarget) {
  2644. case LinkTarget.NONE:
  2645. return false;
  2646. case LinkTarget.SELF:
  2647. case LinkTarget.BLANK:
  2648. case LinkTarget.PARENT:
  2649. case LinkTarget.TOP:
  2650. return true;
  2651. }
  2652. }
  2653. exports.CustomStyle = CustomStyle;
  2654. exports.addLinkAttributes = addLinkAttributes;
  2655. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2656. exports.getFilenameFromUrl = getFilenameFromUrl;
  2657. exports.LinkTarget = LinkTarget;
  2658. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2659. exports.getDefaultSetting = getDefaultSetting;
  2660. }));
  2661. (function (root, factory) {
  2662. factory(root.pdfjsDisplayFontLoader = {}, root.pdfjsSharedUtil);
  2663. }(this, function (exports, sharedUtil) {
  2664. var assert = sharedUtil.assert;
  2665. var bytesToString = sharedUtil.bytesToString;
  2666. var string32 = sharedUtil.string32;
  2667. var shadow = sharedUtil.shadow;
  2668. var warn = sharedUtil.warn;
  2669. function FontLoader(docId) {
  2670. this.docId = docId;
  2671. this.styleElement = null;
  2672. this.nativeFontFaces = [];
  2673. this.loadTestFontId = 0;
  2674. this.loadingContext = {
  2675. requests: [],
  2676. nextRequestId: 0
  2677. };
  2678. }
  2679. FontLoader.prototype = {
  2680. insertRule: function fontLoaderInsertRule(rule) {
  2681. var styleElement = this.styleElement;
  2682. if (!styleElement) {
  2683. styleElement = this.styleElement = document.createElement('style');
  2684. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2685. document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
  2686. }
  2687. var styleSheet = styleElement.sheet;
  2688. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2689. },
  2690. clear: function fontLoaderClear() {
  2691. var styleElement = this.styleElement;
  2692. if (styleElement) {
  2693. styleElement.parentNode.removeChild(styleElement);
  2694. styleElement = this.styleElement = null;
  2695. }
  2696. this.nativeFontFaces.forEach(function (nativeFontFace) {
  2697. document.fonts.delete(nativeFontFace);
  2698. });
  2699. this.nativeFontFaces.length = 0;
  2700. }
  2701. };
  2702. var getLoadTestFont = function () {
  2703. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2704. // height.
  2705. return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==');
  2706. };
  2707. Object.defineProperty(FontLoader.prototype, 'loadTestFont', {
  2708. get: function () {
  2709. return shadow(this, 'loadTestFont', getLoadTestFont());
  2710. },
  2711. configurable: true
  2712. });
  2713. FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) {
  2714. this.nativeFontFaces.push(nativeFontFace);
  2715. document.fonts.add(nativeFontFace);
  2716. };
  2717. FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) {
  2718. var rules = [];
  2719. var fontsToLoad = [];
  2720. var fontLoadPromises = [];
  2721. var getNativeFontPromise = function (nativeFontFace) {
  2722. // Return a promise that is always fulfilled, even when the font fails to
  2723. // load.
  2724. return nativeFontFace.loaded.catch(function (e) {
  2725. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2726. });
  2727. };
  2728. // Firefox Font Loading API does not work with mozPrintCallback --
  2729. // disabling it in this case.
  2730. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported;
  2731. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2732. var font = fonts[i];
  2733. // Add the font to the DOM only once or skip if the font
  2734. // is already loaded.
  2735. if (font.attached || font.loading === false) {
  2736. continue;
  2737. }
  2738. font.attached = true;
  2739. if (isFontLoadingAPISupported) {
  2740. var nativeFontFace = font.createNativeFontFace();
  2741. if (nativeFontFace) {
  2742. this.addNativeFontFace(nativeFontFace);
  2743. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2744. }
  2745. } else {
  2746. var rule = font.createFontFaceRule();
  2747. if (rule) {
  2748. this.insertRule(rule);
  2749. rules.push(rule);
  2750. fontsToLoad.push(font);
  2751. }
  2752. }
  2753. }
  2754. var request = this.queueLoadingCallback(callback);
  2755. if (isFontLoadingAPISupported) {
  2756. Promise.all(fontLoadPromises).then(function () {
  2757. request.complete();
  2758. });
  2759. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2760. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2761. } else {
  2762. request.complete();
  2763. }
  2764. };
  2765. FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) {
  2766. function LoadLoader_completeRequest() {
  2767. assert(!request.end, 'completeRequest() cannot be called twice');
  2768. request.end = Date.now();
  2769. // sending all completed requests in order how they were queued
  2770. while (context.requests.length > 0 && context.requests[0].end) {
  2771. var otherRequest = context.requests.shift();
  2772. setTimeout(otherRequest.callback, 0);
  2773. }
  2774. }
  2775. var context = this.loadingContext;
  2776. var requestId = 'pdfjs-font-loading-' + context.nextRequestId++;
  2777. var request = {
  2778. id: requestId,
  2779. complete: LoadLoader_completeRequest,
  2780. callback: callback,
  2781. started: Date.now()
  2782. };
  2783. context.requests.push(request);
  2784. return request;
  2785. };
  2786. FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) {
  2787. /** Hack begin */
  2788. // There's currently no event when a font has finished downloading so the
  2789. // following code is a dirty hack to 'guess' when a font is
  2790. // ready. It's assumed fonts are loaded in order, so add a known test
  2791. // font after the desired fonts and then test for the loading of that
  2792. // test font.
  2793. function int32(data, offset) {
  2794. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  2795. }
  2796. function spliceString(s, offset, remove, insert) {
  2797. var chunk1 = s.substr(0, offset);
  2798. var chunk2 = s.substr(offset + remove);
  2799. return chunk1 + insert + chunk2;
  2800. }
  2801. var i, ii;
  2802. var canvas = document.createElement('canvas');
  2803. canvas.width = 1;
  2804. canvas.height = 1;
  2805. var ctx = canvas.getContext('2d');
  2806. var called = 0;
  2807. function isFontReady(name, callback) {
  2808. called++;
  2809. // With setTimeout clamping this gives the font ~100ms to load.
  2810. if (called > 30) {
  2811. warn('Load test font never loaded.');
  2812. callback();
  2813. return;
  2814. }
  2815. ctx.font = '30px ' + name;
  2816. ctx.fillText('.', 0, 20);
  2817. var imageData = ctx.getImageData(0, 0, 1, 1);
  2818. if (imageData.data[3] > 0) {
  2819. callback();
  2820. return;
  2821. }
  2822. setTimeout(isFontReady.bind(null, name, callback));
  2823. }
  2824. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2825. // Chromium seems to cache fonts based on a hash of the actual font data,
  2826. // so the font must be modified for each load test else it will appear to
  2827. // be loaded already.
  2828. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2829. // font by splitting it in chunks before hand and padding the font id.
  2830. var data = this.loadTestFont;
  2831. var COMMENT_OFFSET = 976;
  2832. // has to be on 4 byte boundary (for checksum)
  2833. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  2834. // CFF checksum is important for IE, adjusting it
  2835. var CFF_CHECKSUM_OFFSET = 16;
  2836. var XXXX_VALUE = 0x58585858;
  2837. // the "comment" filled with 'X'
  2838. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2839. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2840. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  2841. }
  2842. if (i < loadTestFontId.length) {
  2843. // align to 4 bytes boundary
  2844. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
  2845. }
  2846. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2847. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2848. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}';
  2849. this.insertRule(rule);
  2850. var names = [];
  2851. for (i = 0, ii = fonts.length; i < ii; i++) {
  2852. names.push(fonts[i].loadedName);
  2853. }
  2854. names.push(loadTestFontId);
  2855. var div = document.createElement('div');
  2856. div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
  2857. for (i = 0, ii = names.length; i < ii; ++i) {
  2858. var span = document.createElement('span');
  2859. span.textContent = 'Hi';
  2860. span.style.fontFamily = names[i];
  2861. div.appendChild(span);
  2862. }
  2863. document.body.appendChild(div);
  2864. isFontReady(loadTestFontId, function () {
  2865. document.body.removeChild(div);
  2866. request.complete();
  2867. });
  2868. };
  2869. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts;
  2870. var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() {
  2871. if (typeof navigator === 'undefined') {
  2872. // node.js - we can pretend sync font loading is supported.
  2873. return true;
  2874. }
  2875. var supported = false;
  2876. // User agent string sniffing is bad, but there is no reliable way to tell
  2877. // if font is fully loaded and ready to be used with canvas.
  2878. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2879. if (m && m[1] >= 14) {
  2880. supported = true;
  2881. }
  2882. // TODO other browsers
  2883. return supported;
  2884. };
  2885. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2886. get: function () {
  2887. return shadow(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported());
  2888. },
  2889. enumerable: true,
  2890. configurable: true
  2891. });
  2892. var IsEvalSupportedCached = {
  2893. get value() {
  2894. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2895. }
  2896. };
  2897. var FontFaceObject = function FontFaceObjectClosure() {
  2898. function FontFaceObject(translatedData, options) {
  2899. this.compiledGlyphs = Object.create(null);
  2900. // importing translated data
  2901. for (var i in translatedData) {
  2902. this[i] = translatedData[i];
  2903. }
  2904. this.options = options;
  2905. }
  2906. FontFaceObject.prototype = {
  2907. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2908. if (!this.data) {
  2909. return null;
  2910. }
  2911. if (this.options.disableFontFace) {
  2912. this.disableFontFace = true;
  2913. return null;
  2914. }
  2915. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2916. if (this.options.fontRegistry) {
  2917. this.options.fontRegistry.registerFont(this);
  2918. }
  2919. return nativeFontFace;
  2920. },
  2921. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2922. if (!this.data) {
  2923. return null;
  2924. }
  2925. if (this.options.disableFontFace) {
  2926. this.disableFontFace = true;
  2927. return null;
  2928. }
  2929. var data = bytesToString(new Uint8Array(this.data));
  2930. var fontName = this.loadedName;
  2931. // Add the font-face rule to the document
  2932. var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');';
  2933. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2934. if (this.options.fontRegistry) {
  2935. this.options.fontRegistry.registerFont(this, url);
  2936. }
  2937. return rule;
  2938. },
  2939. getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) {
  2940. if (!(character in this.compiledGlyphs)) {
  2941. var cmds = objs.get(this.loadedName + '_path_' + character);
  2942. var current, i, len;
  2943. // If we can, compile cmds into JS for MAXIMUM SPEED
  2944. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2945. var args, js = '';
  2946. for (i = 0, len = cmds.length; i < len; i++) {
  2947. current = cmds[i];
  2948. if (current.args !== undefined) {
  2949. args = current.args.join(',');
  2950. } else {
  2951. args = '';
  2952. }
  2953. js += 'c.' + current.cmd + '(' + args + ');\n';
  2954. }
  2955. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2956. } else {
  2957. // But fall back on using Function.prototype.apply() if we're
  2958. // blocked from using eval() for whatever reason (like CSP policies)
  2959. this.compiledGlyphs[character] = function (c, size) {
  2960. for (i = 0, len = cmds.length; i < len; i++) {
  2961. current = cmds[i];
  2962. if (current.cmd === 'scale') {
  2963. current.args = [
  2964. size,
  2965. -size
  2966. ];
  2967. }
  2968. c[current.cmd].apply(c, current.args);
  2969. }
  2970. };
  2971. }
  2972. }
  2973. return this.compiledGlyphs[character];
  2974. }
  2975. };
  2976. return FontFaceObject;
  2977. }();
  2978. exports.FontFaceObject = FontFaceObject;
  2979. exports.FontLoader = FontLoader;
  2980. }));
  2981. (function (root, factory) {
  2982. factory(root.pdfjsDisplayMetadata = {}, root.pdfjsSharedUtil);
  2983. }(this, function (exports, sharedUtil) {
  2984. var error = sharedUtil.error;
  2985. function fixMetadata(meta) {
  2986. return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
  2987. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
  2988. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2989. });
  2990. var chars = '';
  2991. for (var i = 0; i < bytes.length; i += 2) {
  2992. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2993. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2994. }
  2995. return '>' + chars;
  2996. });
  2997. }
  2998. function Metadata(meta) {
  2999. if (typeof meta === 'string') {
  3000. // Ghostscript produces invalid metadata
  3001. meta = fixMetadata(meta);
  3002. var parser = new DOMParser();
  3003. meta = parser.parseFromString(meta, 'application/xml');
  3004. } else if (!(meta instanceof Document)) {
  3005. error('Metadata: Invalid metadata object');
  3006. }
  3007. this.metaDocument = meta;
  3008. this.metadata = Object.create(null);
  3009. this.parse();
  3010. }
  3011. Metadata.prototype = {
  3012. parse: function Metadata_parse() {
  3013. var doc = this.metaDocument;
  3014. var rdf = doc.documentElement;
  3015. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3016. // Wrapped in <xmpmeta>
  3017. rdf = rdf.firstChild;
  3018. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3019. rdf = rdf.nextSibling;
  3020. }
  3021. }
  3022. var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
  3023. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3024. return;
  3025. }
  3026. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3027. for (i = 0, length = children.length; i < length; i++) {
  3028. desc = children[i];
  3029. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3030. continue;
  3031. }
  3032. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3033. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3034. entry = desc.childNodes[ii];
  3035. name = entry.nodeName.toLowerCase();
  3036. this.metadata[name] = entry.textContent.trim();
  3037. }
  3038. }
  3039. }
  3040. },
  3041. get: function Metadata_get(name) {
  3042. return this.metadata[name] || null;
  3043. },
  3044. has: function Metadata_has(name) {
  3045. return typeof this.metadata[name] !== 'undefined';
  3046. }
  3047. };
  3048. exports.Metadata = Metadata;
  3049. }));
  3050. (function (root, factory) {
  3051. factory(root.pdfjsDisplaySVG = {}, root.pdfjsSharedUtil);
  3052. }(this, function (exports, sharedUtil) {
  3053. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3054. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3055. var ImageKind = sharedUtil.ImageKind;
  3056. var OPS = sharedUtil.OPS;
  3057. var Util = sharedUtil.Util;
  3058. var isNum = sharedUtil.isNum;
  3059. var isArray = sharedUtil.isArray;
  3060. var warn = sharedUtil.warn;
  3061. var createObjectURL = sharedUtil.createObjectURL;
  3062. var SVG_DEFAULTS = {
  3063. fontStyle: 'normal',
  3064. fontWeight: 'normal',
  3065. fillColor: '#000000'
  3066. };
  3067. var convertImgDataToPng = function convertImgDataToPngClosure() {
  3068. var PNG_HEADER = new Uint8Array([
  3069. 0x89,
  3070. 0x50,
  3071. 0x4e,
  3072. 0x47,
  3073. 0x0d,
  3074. 0x0a,
  3075. 0x1a,
  3076. 0x0a
  3077. ]);
  3078. var CHUNK_WRAPPER_SIZE = 12;
  3079. var crcTable = new Int32Array(256);
  3080. for (var i = 0; i < 256; i++) {
  3081. var c = i;
  3082. for (var h = 0; h < 8; h++) {
  3083. if (c & 1) {
  3084. c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
  3085. } else {
  3086. c = c >> 1 & 0x7fffffff;
  3087. }
  3088. }
  3089. crcTable[i] = c;
  3090. }
  3091. function crc32(data, start, end) {
  3092. var crc = -1;
  3093. for (var i = start; i < end; i++) {
  3094. var a = (crc ^ data[i]) & 0xff;
  3095. var b = crcTable[a];
  3096. crc = crc >>> 8 ^ b;
  3097. }
  3098. return crc ^ -1;
  3099. }
  3100. function writePngChunk(type, body, data, offset) {
  3101. var p = offset;
  3102. var len = body.length;
  3103. data[p] = len >> 24 & 0xff;
  3104. data[p + 1] = len >> 16 & 0xff;
  3105. data[p + 2] = len >> 8 & 0xff;
  3106. data[p + 3] = len & 0xff;
  3107. p += 4;
  3108. data[p] = type.charCodeAt(0) & 0xff;
  3109. data[p + 1] = type.charCodeAt(1) & 0xff;
  3110. data[p + 2] = type.charCodeAt(2) & 0xff;
  3111. data[p + 3] = type.charCodeAt(3) & 0xff;
  3112. p += 4;
  3113. data.set(body, p);
  3114. p += body.length;
  3115. var crc = crc32(data, offset + 4, p);
  3116. data[p] = crc >> 24 & 0xff;
  3117. data[p + 1] = crc >> 16 & 0xff;
  3118. data[p + 2] = crc >> 8 & 0xff;
  3119. data[p + 3] = crc & 0xff;
  3120. }
  3121. function adler32(data, start, end) {
  3122. var a = 1;
  3123. var b = 0;
  3124. for (var i = start; i < end; ++i) {
  3125. a = (a + (data[i] & 0xff)) % 65521;
  3126. b = (b + a) % 65521;
  3127. }
  3128. return b << 16 | a;
  3129. }
  3130. function encode(imgData, kind, forceDataSchema) {
  3131. var width = imgData.width;
  3132. var height = imgData.height;
  3133. var bitDepth, colorType, lineSize;
  3134. var bytes = imgData.data;
  3135. switch (kind) {
  3136. case ImageKind.GRAYSCALE_1BPP:
  3137. colorType = 0;
  3138. bitDepth = 1;
  3139. lineSize = width + 7 >> 3;
  3140. break;
  3141. case ImageKind.RGB_24BPP:
  3142. colorType = 2;
  3143. bitDepth = 8;
  3144. lineSize = width * 3;
  3145. break;
  3146. case ImageKind.RGBA_32BPP:
  3147. colorType = 6;
  3148. bitDepth = 8;
  3149. lineSize = width * 4;
  3150. break;
  3151. default:
  3152. throw new Error('invalid format');
  3153. }
  3154. // prefix every row with predictor 0
  3155. var literals = new Uint8Array((1 + lineSize) * height);
  3156. var offsetLiterals = 0, offsetBytes = 0;
  3157. var y, i;
  3158. for (y = 0; y < height; ++y) {
  3159. literals[offsetLiterals++] = 0;
  3160. // no prediction
  3161. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  3162. offsetBytes += lineSize;
  3163. offsetLiterals += lineSize;
  3164. }
  3165. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3166. // inverting for B/W
  3167. offsetLiterals = 0;
  3168. for (y = 0; y < height; y++) {
  3169. offsetLiterals++;
  3170. // skipping predictor
  3171. for (i = 0; i < lineSize; i++) {
  3172. literals[offsetLiterals++] ^= 0xFF;
  3173. }
  3174. }
  3175. }
  3176. var ihdr = new Uint8Array([
  3177. width >> 24 & 0xff,
  3178. width >> 16 & 0xff,
  3179. width >> 8 & 0xff,
  3180. width & 0xff,
  3181. height >> 24 & 0xff,
  3182. height >> 16 & 0xff,
  3183. height >> 8 & 0xff,
  3184. height & 0xff,
  3185. bitDepth,
  3186. // bit depth
  3187. colorType,
  3188. // color type
  3189. 0x00,
  3190. // compression method
  3191. 0x00,
  3192. // filter method
  3193. 0x00
  3194. ]);
  3195. // interlace method
  3196. var len = literals.length;
  3197. var maxBlockLength = 0xFFFF;
  3198. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3199. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3200. var pi = 0;
  3201. idat[pi++] = 0x78;
  3202. // compression method and flags
  3203. idat[pi++] = 0x9c;
  3204. // flags
  3205. var pos = 0;
  3206. while (len > maxBlockLength) {
  3207. // writing non-final DEFLATE blocks type 0 and length of 65535
  3208. idat[pi++] = 0x00;
  3209. idat[pi++] = 0xff;
  3210. idat[pi++] = 0xff;
  3211. idat[pi++] = 0x00;
  3212. idat[pi++] = 0x00;
  3213. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3214. pi += maxBlockLength;
  3215. pos += maxBlockLength;
  3216. len -= maxBlockLength;
  3217. }
  3218. // writing non-final DEFLATE blocks type 0
  3219. idat[pi++] = 0x01;
  3220. idat[pi++] = len & 0xff;
  3221. idat[pi++] = len >> 8 & 0xff;
  3222. idat[pi++] = ~len & 0xffff & 0xff;
  3223. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3224. idat.set(literals.subarray(pos), pi);
  3225. pi += literals.length - pos;
  3226. var adler = adler32(literals, 0, literals.length);
  3227. // checksum
  3228. idat[pi++] = adler >> 24 & 0xff;
  3229. idat[pi++] = adler >> 16 & 0xff;
  3230. idat[pi++] = adler >> 8 & 0xff;
  3231. idat[pi++] = adler & 0xff;
  3232. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3233. var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  3234. var data = new Uint8Array(pngLength);
  3235. var offset = 0;
  3236. data.set(PNG_HEADER, offset);
  3237. offset += PNG_HEADER.length;
  3238. writePngChunk('IHDR', ihdr, data, offset);
  3239. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3240. writePngChunk('IDATA', idat, data, offset);
  3241. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3242. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3243. return createObjectURL(data, 'image/png', forceDataSchema);
  3244. }
  3245. return function convertImgDataToPng(imgData, forceDataSchema) {
  3246. var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
  3247. return encode(imgData, kind, forceDataSchema);
  3248. };
  3249. }();
  3250. var SVGExtraState = function SVGExtraStateClosure() {
  3251. function SVGExtraState() {
  3252. this.fontSizeScale = 1;
  3253. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3254. this.fontSize = 0;
  3255. this.textMatrix = IDENTITY_MATRIX;
  3256. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3257. this.leading = 0;
  3258. // Current point (in user coordinates)
  3259. this.x = 0;
  3260. this.y = 0;
  3261. // Start of text line (in text coordinates)
  3262. this.lineX = 0;
  3263. this.lineY = 0;
  3264. // Character and word spacing
  3265. this.charSpacing = 0;
  3266. this.wordSpacing = 0;
  3267. this.textHScale = 1;
  3268. this.textRise = 0;
  3269. // Default foreground and background colors
  3270. this.fillColor = SVG_DEFAULTS.fillColor;
  3271. this.strokeColor = '#000000';
  3272. this.fillAlpha = 1;
  3273. this.strokeAlpha = 1;
  3274. this.lineWidth = 1;
  3275. this.lineJoin = '';
  3276. this.lineCap = '';
  3277. this.miterLimit = 0;
  3278. this.dashArray = [];
  3279. this.dashPhase = 0;
  3280. this.dependencies = [];
  3281. // Clipping
  3282. this.clipId = '';
  3283. this.pendingClip = false;
  3284. this.maskId = '';
  3285. }
  3286. SVGExtraState.prototype = {
  3287. clone: function SVGExtraState_clone() {
  3288. return Object.create(this);
  3289. },
  3290. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3291. this.x = x;
  3292. this.y = y;
  3293. }
  3294. };
  3295. return SVGExtraState;
  3296. }();
  3297. var SVGGraphics = function SVGGraphicsClosure() {
  3298. function createScratchSVG(width, height) {
  3299. var NS = 'http://www.w3.org/2000/svg';
  3300. var svg = document.createElementNS(NS, 'svg:svg');
  3301. svg.setAttributeNS(null, 'version', '1.1');
  3302. svg.setAttributeNS(null, 'width', width + 'px');
  3303. svg.setAttributeNS(null, 'height', height + 'px');
  3304. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3305. return svg;
  3306. }
  3307. function opListToTree(opList) {
  3308. var opTree = [];
  3309. var tmp = [];
  3310. var opListLen = opList.length;
  3311. for (var x = 0; x < opListLen; x++) {
  3312. if (opList[x].fn === 'save') {
  3313. opTree.push({
  3314. 'fnId': 92,
  3315. 'fn': 'group',
  3316. 'items': []
  3317. });
  3318. tmp.push(opTree);
  3319. opTree = opTree[opTree.length - 1].items;
  3320. continue;
  3321. }
  3322. if (opList[x].fn === 'restore') {
  3323. opTree = tmp.pop();
  3324. } else {
  3325. opTree.push(opList[x]);
  3326. }
  3327. }
  3328. return opTree;
  3329. }
  3330. /**
  3331. * Formats float number.
  3332. * @param value {number} number to format.
  3333. * @returns {string}
  3334. */
  3335. function pf(value) {
  3336. if (value === (value | 0)) {
  3337. // integer number
  3338. return value.toString();
  3339. }
  3340. var s = value.toFixed(10);
  3341. var i = s.length - 1;
  3342. if (s[i] !== '0') {
  3343. return s;
  3344. }
  3345. // removing trailing zeros
  3346. do {
  3347. i--;
  3348. } while (s[i] === '0');
  3349. return s.substr(0, s[i] === '.' ? i : i + 1);
  3350. }
  3351. /**
  3352. * Formats transform matrix. The standard rotation, scale and translate
  3353. * matrices are replaced by their shorter forms, and for identity matrix
  3354. * returns empty string to save the memory.
  3355. * @param m {Array} matrix to format.
  3356. * @returns {string}
  3357. */
  3358. function pm(m) {
  3359. if (m[4] === 0 && m[5] === 0) {
  3360. if (m[1] === 0 && m[2] === 0) {
  3361. if (m[0] === 1 && m[3] === 1) {
  3362. return '';
  3363. }
  3364. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3365. }
  3366. if (m[0] === m[3] && m[1] === -m[2]) {
  3367. var a = Math.acos(m[0]) * 180 / Math.PI;
  3368. return 'rotate(' + pf(a) + ')';
  3369. }
  3370. } else {
  3371. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3372. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3373. }
  3374. }
  3375. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3376. }
  3377. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3378. this.current = new SVGExtraState();
  3379. this.transformMatrix = IDENTITY_MATRIX;
  3380. // Graphics state matrix
  3381. this.transformStack = [];
  3382. this.extraStack = [];
  3383. this.commonObjs = commonObjs;
  3384. this.objs = objs;
  3385. this.pendingEOFill = false;
  3386. this.embedFonts = false;
  3387. this.embeddedFonts = Object.create(null);
  3388. this.cssStyle = null;
  3389. this.forceDataSchema = !!forceDataSchema;
  3390. }
  3391. var NS = 'http://www.w3.org/2000/svg';
  3392. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3393. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3394. var LINE_CAP_STYLES = [
  3395. 'butt',
  3396. 'round',
  3397. 'square'
  3398. ];
  3399. var LINE_JOIN_STYLES = [
  3400. 'miter',
  3401. 'round',
  3402. 'bevel'
  3403. ];
  3404. var clipCount = 0;
  3405. var maskCount = 0;
  3406. SVGGraphics.prototype = {
  3407. save: function SVGGraphics_save() {
  3408. this.transformStack.push(this.transformMatrix);
  3409. var old = this.current;
  3410. this.extraStack.push(old);
  3411. this.current = old.clone();
  3412. },
  3413. restore: function SVGGraphics_restore() {
  3414. this.transformMatrix = this.transformStack.pop();
  3415. this.current = this.extraStack.pop();
  3416. this.tgrp = document.createElementNS(NS, 'svg:g');
  3417. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3418. this.pgrp.appendChild(this.tgrp);
  3419. },
  3420. group: function SVGGraphics_group(items) {
  3421. this.save();
  3422. this.executeOpTree(items);
  3423. this.restore();
  3424. },
  3425. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3426. var fnArray = operatorList.fnArray;
  3427. var fnArrayLen = fnArray.length;
  3428. var argsArray = operatorList.argsArray;
  3429. var self = this;
  3430. for (var i = 0; i < fnArrayLen; i++) {
  3431. if (OPS.dependency === fnArray[i]) {
  3432. var deps = argsArray[i];
  3433. for (var n = 0, nn = deps.length; n < nn; n++) {
  3434. var obj = deps[n];
  3435. var common = obj.substring(0, 2) === 'g_';
  3436. var promise;
  3437. if (common) {
  3438. promise = new Promise(function (resolve) {
  3439. self.commonObjs.get(obj, resolve);
  3440. });
  3441. } else {
  3442. promise = new Promise(function (resolve) {
  3443. self.objs.get(obj, resolve);
  3444. });
  3445. }
  3446. this.current.dependencies.push(promise);
  3447. }
  3448. }
  3449. }
  3450. return Promise.all(this.current.dependencies);
  3451. },
  3452. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3453. var transformMatrix = [
  3454. a,
  3455. b,
  3456. c,
  3457. d,
  3458. e,
  3459. f
  3460. ];
  3461. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3462. this.tgrp = document.createElementNS(NS, 'svg:g');
  3463. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3464. },
  3465. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3466. this.svg = createScratchSVG(viewport.width, viewport.height);
  3467. this.viewport = viewport;
  3468. return this.loadDependencies(operatorList).then(function () {
  3469. this.transformMatrix = IDENTITY_MATRIX;
  3470. this.pgrp = document.createElementNS(NS, 'svg:g');
  3471. // Parent group
  3472. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3473. this.tgrp = document.createElementNS(NS, 'svg:g');
  3474. // Transform group
  3475. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3476. this.defs = document.createElementNS(NS, 'svg:defs');
  3477. this.pgrp.appendChild(this.defs);
  3478. this.pgrp.appendChild(this.tgrp);
  3479. this.svg.appendChild(this.pgrp);
  3480. var opTree = this.convertOpList(operatorList);
  3481. this.executeOpTree(opTree);
  3482. return this.svg;
  3483. }.bind(this));
  3484. },
  3485. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3486. var argsArray = operatorList.argsArray;
  3487. var fnArray = operatorList.fnArray;
  3488. var fnArrayLen = fnArray.length;
  3489. var REVOPS = [];
  3490. var opList = [];
  3491. for (var op in OPS) {
  3492. REVOPS[OPS[op]] = op;
  3493. }
  3494. for (var x = 0; x < fnArrayLen; x++) {
  3495. var fnId = fnArray[x];
  3496. opList.push({
  3497. 'fnId': fnId,
  3498. 'fn': REVOPS[fnId],
  3499. 'args': argsArray[x]
  3500. });
  3501. }
  3502. return opListToTree(opList);
  3503. },
  3504. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3505. var opTreeLen = opTree.length;
  3506. for (var x = 0; x < opTreeLen; x++) {
  3507. var fn = opTree[x].fn;
  3508. var fnId = opTree[x].fnId;
  3509. var args = opTree[x].args;
  3510. switch (fnId | 0) {
  3511. case OPS.beginText:
  3512. this.beginText();
  3513. break;
  3514. case OPS.setLeading:
  3515. this.setLeading(args);
  3516. break;
  3517. case OPS.setLeadingMoveText:
  3518. this.setLeadingMoveText(args[0], args[1]);
  3519. break;
  3520. case OPS.setFont:
  3521. this.setFont(args);
  3522. break;
  3523. case OPS.showText:
  3524. this.showText(args[0]);
  3525. break;
  3526. case OPS.showSpacedText:
  3527. this.showText(args[0]);
  3528. break;
  3529. case OPS.endText:
  3530. this.endText();
  3531. break;
  3532. case OPS.moveText:
  3533. this.moveText(args[0], args[1]);
  3534. break;
  3535. case OPS.setCharSpacing:
  3536. this.setCharSpacing(args[0]);
  3537. break;
  3538. case OPS.setWordSpacing:
  3539. this.setWordSpacing(args[0]);
  3540. break;
  3541. case OPS.setHScale:
  3542. this.setHScale(args[0]);
  3543. break;
  3544. case OPS.setTextMatrix:
  3545. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3546. break;
  3547. case OPS.setLineWidth:
  3548. this.setLineWidth(args[0]);
  3549. break;
  3550. case OPS.setLineJoin:
  3551. this.setLineJoin(args[0]);
  3552. break;
  3553. case OPS.setLineCap:
  3554. this.setLineCap(args[0]);
  3555. break;
  3556. case OPS.setMiterLimit:
  3557. this.setMiterLimit(args[0]);
  3558. break;
  3559. case OPS.setFillRGBColor:
  3560. this.setFillRGBColor(args[0], args[1], args[2]);
  3561. break;
  3562. case OPS.setStrokeRGBColor:
  3563. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3564. break;
  3565. case OPS.setDash:
  3566. this.setDash(args[0], args[1]);
  3567. break;
  3568. case OPS.setGState:
  3569. this.setGState(args[0]);
  3570. break;
  3571. case OPS.fill:
  3572. this.fill();
  3573. break;
  3574. case OPS.eoFill:
  3575. this.eoFill();
  3576. break;
  3577. case OPS.stroke:
  3578. this.stroke();
  3579. break;
  3580. case OPS.fillStroke:
  3581. this.fillStroke();
  3582. break;
  3583. case OPS.eoFillStroke:
  3584. this.eoFillStroke();
  3585. break;
  3586. case OPS.clip:
  3587. this.clip('nonzero');
  3588. break;
  3589. case OPS.eoClip:
  3590. this.clip('evenodd');
  3591. break;
  3592. case OPS.paintSolidColorImageMask:
  3593. this.paintSolidColorImageMask();
  3594. break;
  3595. case OPS.paintJpegXObject:
  3596. this.paintJpegXObject(args[0], args[1], args[2]);
  3597. break;
  3598. case OPS.paintImageXObject:
  3599. this.paintImageXObject(args[0]);
  3600. break;
  3601. case OPS.paintInlineImageXObject:
  3602. this.paintInlineImageXObject(args[0]);
  3603. break;
  3604. case OPS.paintImageMaskXObject:
  3605. this.paintImageMaskXObject(args[0]);
  3606. break;
  3607. case OPS.paintFormXObjectBegin:
  3608. this.paintFormXObjectBegin(args[0], args[1]);
  3609. break;
  3610. case OPS.paintFormXObjectEnd:
  3611. this.paintFormXObjectEnd();
  3612. break;
  3613. case OPS.closePath:
  3614. this.closePath();
  3615. break;
  3616. case OPS.closeStroke:
  3617. this.closeStroke();
  3618. break;
  3619. case OPS.closeFillStroke:
  3620. this.closeFillStroke();
  3621. break;
  3622. case OPS.nextLine:
  3623. this.nextLine();
  3624. break;
  3625. case OPS.transform:
  3626. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3627. break;
  3628. case OPS.constructPath:
  3629. this.constructPath(args[0], args[1]);
  3630. break;
  3631. case OPS.endPath:
  3632. this.endPath();
  3633. break;
  3634. case 92:
  3635. this.group(opTree[x].items);
  3636. break;
  3637. default:
  3638. warn('Unimplemented method ' + fn);
  3639. break;
  3640. }
  3641. }
  3642. },
  3643. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3644. this.current.wordSpacing = wordSpacing;
  3645. },
  3646. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3647. this.current.charSpacing = charSpacing;
  3648. },
  3649. nextLine: function SVGGraphics_nextLine() {
  3650. this.moveText(0, this.current.leading);
  3651. },
  3652. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3653. var current = this.current;
  3654. this.current.textMatrix = this.current.lineMatrix = [
  3655. a,
  3656. b,
  3657. c,
  3658. d,
  3659. e,
  3660. f
  3661. ];
  3662. this.current.x = this.current.lineX = 0;
  3663. this.current.y = this.current.lineY = 0;
  3664. current.xcoords = [];
  3665. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3666. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3667. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3668. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3669. current.txtElement = document.createElementNS(NS, 'svg:text');
  3670. current.txtElement.appendChild(current.tspan);
  3671. },
  3672. beginText: function SVGGraphics_beginText() {
  3673. this.current.x = this.current.lineX = 0;
  3674. this.current.y = this.current.lineY = 0;
  3675. this.current.textMatrix = IDENTITY_MATRIX;
  3676. this.current.lineMatrix = IDENTITY_MATRIX;
  3677. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3678. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3679. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3680. this.current.xcoords = [];
  3681. },
  3682. moveText: function SVGGraphics_moveText(x, y) {
  3683. var current = this.current;
  3684. this.current.x = this.current.lineX += x;
  3685. this.current.y = this.current.lineY += y;
  3686. current.xcoords = [];
  3687. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3688. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3689. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3690. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3691. },
  3692. showText: function SVGGraphics_showText(glyphs) {
  3693. var current = this.current;
  3694. var font = current.font;
  3695. var fontSize = current.fontSize;
  3696. if (fontSize === 0) {
  3697. return;
  3698. }
  3699. var charSpacing = current.charSpacing;
  3700. var wordSpacing = current.wordSpacing;
  3701. var fontDirection = current.fontDirection;
  3702. var textHScale = current.textHScale * fontDirection;
  3703. var glyphsLength = glyphs.length;
  3704. var vertical = font.vertical;
  3705. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3706. var x = 0, i;
  3707. for (i = 0; i < glyphsLength; ++i) {
  3708. var glyph = glyphs[i];
  3709. if (glyph === null) {
  3710. // word break
  3711. x += fontDirection * wordSpacing;
  3712. continue;
  3713. } else if (isNum(glyph)) {
  3714. x += -glyph * fontSize * 0.001;
  3715. continue;
  3716. }
  3717. current.xcoords.push(current.x + x * textHScale);
  3718. var width = glyph.width;
  3719. var character = glyph.fontChar;
  3720. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3721. x += charWidth;
  3722. current.tspan.textContent += character;
  3723. }
  3724. if (vertical) {
  3725. current.y -= x * textHScale;
  3726. } else {
  3727. current.x += x * textHScale;
  3728. }
  3729. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3730. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3731. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3732. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3733. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3734. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3735. }
  3736. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3737. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3738. }
  3739. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3740. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3741. }
  3742. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3743. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3744. current.txtElement.appendChild(current.tspan);
  3745. current.txtgrp.appendChild(current.txtElement);
  3746. this.tgrp.appendChild(current.txtElement);
  3747. },
  3748. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3749. this.setLeading(-y);
  3750. this.moveText(x, y);
  3751. },
  3752. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3753. if (!this.cssStyle) {
  3754. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3755. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3756. this.defs.appendChild(this.cssStyle);
  3757. }
  3758. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3759. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3760. },
  3761. setFont: function SVGGraphics_setFont(details) {
  3762. var current = this.current;
  3763. var fontObj = this.commonObjs.get(details[0]);
  3764. var size = details[1];
  3765. this.current.font = fontObj;
  3766. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3767. this.addFontStyle(fontObj);
  3768. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3769. }
  3770. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3771. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3772. var italic = fontObj.italic ? 'italic' : 'normal';
  3773. if (size < 0) {
  3774. size = -size;
  3775. current.fontDirection = -1;
  3776. } else {
  3777. current.fontDirection = 1;
  3778. }
  3779. current.fontSize = size;
  3780. current.fontFamily = fontObj.loadedName;
  3781. current.fontWeight = bold;
  3782. current.fontStyle = italic;
  3783. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3784. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3785. current.xcoords = [];
  3786. },
  3787. endText: function SVGGraphics_endText() {
  3788. if (this.current.pendingClip) {
  3789. this.cgrp.appendChild(this.tgrp);
  3790. this.pgrp.appendChild(this.cgrp);
  3791. } else {
  3792. this.pgrp.appendChild(this.tgrp);
  3793. }
  3794. this.tgrp = document.createElementNS(NS, 'svg:g');
  3795. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3796. },
  3797. // Path properties
  3798. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3799. this.current.lineWidth = width;
  3800. },
  3801. setLineCap: function SVGGraphics_setLineCap(style) {
  3802. this.current.lineCap = LINE_CAP_STYLES[style];
  3803. },
  3804. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3805. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3806. },
  3807. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3808. this.current.miterLimit = limit;
  3809. },
  3810. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3811. var color = Util.makeCssRgb(r, g, b);
  3812. this.current.strokeColor = color;
  3813. },
  3814. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3815. var color = Util.makeCssRgb(r, g, b);
  3816. this.current.fillColor = color;
  3817. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3818. this.current.xcoords = [];
  3819. },
  3820. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3821. this.current.dashArray = dashArray;
  3822. this.current.dashPhase = dashPhase;
  3823. },
  3824. constructPath: function SVGGraphics_constructPath(ops, args) {
  3825. var current = this.current;
  3826. var x = current.x, y = current.y;
  3827. current.path = document.createElementNS(NS, 'svg:path');
  3828. var d = [];
  3829. var opLength = ops.length;
  3830. for (var i = 0, j = 0; i < opLength; i++) {
  3831. switch (ops[i] | 0) {
  3832. case OPS.rectangle:
  3833. x = args[j++];
  3834. y = args[j++];
  3835. var width = args[j++];
  3836. var height = args[j++];
  3837. var xw = x + width;
  3838. var yh = y + height;
  3839. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3840. break;
  3841. case OPS.moveTo:
  3842. x = args[j++];
  3843. y = args[j++];
  3844. d.push('M', pf(x), pf(y));
  3845. break;
  3846. case OPS.lineTo:
  3847. x = args[j++];
  3848. y = args[j++];
  3849. d.push('L', pf(x), pf(y));
  3850. break;
  3851. case OPS.curveTo:
  3852. x = args[j + 4];
  3853. y = args[j + 5];
  3854. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3855. j += 6;
  3856. break;
  3857. case OPS.curveTo2:
  3858. x = args[j + 2];
  3859. y = args[j + 3];
  3860. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3861. j += 4;
  3862. break;
  3863. case OPS.curveTo3:
  3864. x = args[j + 2];
  3865. y = args[j + 3];
  3866. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3867. j += 4;
  3868. break;
  3869. case OPS.closePath:
  3870. d.push('Z');
  3871. break;
  3872. }
  3873. }
  3874. current.path.setAttributeNS(null, 'd', d.join(' '));
  3875. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3876. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3877. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3878. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3879. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3880. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3881. current.path.setAttributeNS(null, 'fill', 'none');
  3882. this.tgrp.appendChild(current.path);
  3883. if (current.pendingClip) {
  3884. this.cgrp.appendChild(this.tgrp);
  3885. this.pgrp.appendChild(this.cgrp);
  3886. } else {
  3887. this.pgrp.appendChild(this.tgrp);
  3888. }
  3889. // Saving a reference in current.element so that it can be addressed
  3890. // in 'fill' and 'stroke'
  3891. current.element = current.path;
  3892. current.setCurrentPoint(x, y);
  3893. },
  3894. endPath: function SVGGraphics_endPath() {
  3895. var current = this.current;
  3896. if (current.pendingClip) {
  3897. this.cgrp.appendChild(this.tgrp);
  3898. this.pgrp.appendChild(this.cgrp);
  3899. } else {
  3900. this.pgrp.appendChild(this.tgrp);
  3901. }
  3902. this.tgrp = document.createElementNS(NS, 'svg:g');
  3903. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3904. },
  3905. clip: function SVGGraphics_clip(type) {
  3906. var current = this.current;
  3907. // Add current path to clipping path
  3908. current.clipId = 'clippath' + clipCount;
  3909. clipCount++;
  3910. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3911. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3912. var clipElement = current.element.cloneNode();
  3913. if (type === 'evenodd') {
  3914. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3915. } else {
  3916. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3917. }
  3918. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3919. this.clippath.appendChild(clipElement);
  3920. this.defs.appendChild(this.clippath);
  3921. // Create a new group with that attribute
  3922. current.pendingClip = true;
  3923. this.cgrp = document.createElementNS(NS, 'svg:g');
  3924. this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')');
  3925. this.pgrp.appendChild(this.cgrp);
  3926. },
  3927. closePath: function SVGGraphics_closePath() {
  3928. var current = this.current;
  3929. var d = current.path.getAttributeNS(null, 'd');
  3930. d += 'Z';
  3931. current.path.setAttributeNS(null, 'd', d);
  3932. },
  3933. setLeading: function SVGGraphics_setLeading(leading) {
  3934. this.current.leading = -leading;
  3935. },
  3936. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3937. this.current.textRise = textRise;
  3938. },
  3939. setHScale: function SVGGraphics_setHScale(scale) {
  3940. this.current.textHScale = scale / 100;
  3941. },
  3942. setGState: function SVGGraphics_setGState(states) {
  3943. for (var i = 0, ii = states.length; i < ii; i++) {
  3944. var state = states[i];
  3945. var key = state[0];
  3946. var value = state[1];
  3947. switch (key) {
  3948. case 'LW':
  3949. this.setLineWidth(value);
  3950. break;
  3951. case 'LC':
  3952. this.setLineCap(value);
  3953. break;
  3954. case 'LJ':
  3955. this.setLineJoin(value);
  3956. break;
  3957. case 'ML':
  3958. this.setMiterLimit(value);
  3959. break;
  3960. case 'D':
  3961. this.setDash(value[0], value[1]);
  3962. break;
  3963. case 'RI':
  3964. break;
  3965. case 'FL':
  3966. break;
  3967. case 'Font':
  3968. this.setFont(value);
  3969. break;
  3970. case 'CA':
  3971. break;
  3972. case 'ca':
  3973. break;
  3974. case 'BM':
  3975. break;
  3976. case 'SMask':
  3977. break;
  3978. }
  3979. }
  3980. },
  3981. fill: function SVGGraphics_fill() {
  3982. var current = this.current;
  3983. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3984. },
  3985. stroke: function SVGGraphics_stroke() {
  3986. var current = this.current;
  3987. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3988. current.element.setAttributeNS(null, 'fill', 'none');
  3989. },
  3990. eoFill: function SVGGraphics_eoFill() {
  3991. var current = this.current;
  3992. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3993. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3994. },
  3995. fillStroke: function SVGGraphics_fillStroke() {
  3996. // Order is important since stroke wants fill to be none.
  3997. // First stroke, then if fill needed, it will be overwritten.
  3998. this.stroke();
  3999. this.fill();
  4000. },
  4001. eoFillStroke: function SVGGraphics_eoFillStroke() {
  4002. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4003. this.fillStroke();
  4004. },
  4005. closeStroke: function SVGGraphics_closeStroke() {
  4006. this.closePath();
  4007. this.stroke();
  4008. },
  4009. closeFillStroke: function SVGGraphics_closeFillStroke() {
  4010. this.closePath();
  4011. this.fillStroke();
  4012. },
  4013. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  4014. var current = this.current;
  4015. var rect = document.createElementNS(NS, 'svg:rect');
  4016. rect.setAttributeNS(null, 'x', '0');
  4017. rect.setAttributeNS(null, 'y', '0');
  4018. rect.setAttributeNS(null, 'width', '1px');
  4019. rect.setAttributeNS(null, 'height', '1px');
  4020. rect.setAttributeNS(null, 'fill', current.fillColor);
  4021. this.tgrp.appendChild(rect);
  4022. },
  4023. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  4024. var current = this.current;
  4025. var imgObj = this.objs.get(objId);
  4026. var imgEl = document.createElementNS(NS, 'svg:image');
  4027. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  4028. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  4029. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  4030. imgEl.setAttributeNS(null, 'x', '0');
  4031. imgEl.setAttributeNS(null, 'y', pf(-h));
  4032. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  4033. this.tgrp.appendChild(imgEl);
  4034. if (current.pendingClip) {
  4035. this.cgrp.appendChild(this.tgrp);
  4036. this.pgrp.appendChild(this.cgrp);
  4037. } else {
  4038. this.pgrp.appendChild(this.tgrp);
  4039. }
  4040. },
  4041. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  4042. var imgData = this.objs.get(objId);
  4043. if (!imgData) {
  4044. warn('Dependent image isn\'t ready yet');
  4045. return;
  4046. }
  4047. this.paintInlineImageXObject(imgData);
  4048. },
  4049. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  4050. var current = this.current;
  4051. var width = imgData.width;
  4052. var height = imgData.height;
  4053. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  4054. var cliprect = document.createElementNS(NS, 'svg:rect');
  4055. cliprect.setAttributeNS(null, 'x', '0');
  4056. cliprect.setAttributeNS(null, 'y', '0');
  4057. cliprect.setAttributeNS(null, 'width', pf(width));
  4058. cliprect.setAttributeNS(null, 'height', pf(height));
  4059. current.element = cliprect;
  4060. this.clip('nonzero');
  4061. var imgEl = document.createElementNS(NS, 'svg:image');
  4062. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4063. imgEl.setAttributeNS(null, 'x', '0');
  4064. imgEl.setAttributeNS(null, 'y', pf(-height));
  4065. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4066. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4067. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  4068. if (mask) {
  4069. mask.appendChild(imgEl);
  4070. } else {
  4071. this.tgrp.appendChild(imgEl);
  4072. }
  4073. if (current.pendingClip) {
  4074. this.cgrp.appendChild(this.tgrp);
  4075. this.pgrp.appendChild(this.cgrp);
  4076. } else {
  4077. this.pgrp.appendChild(this.tgrp);
  4078. }
  4079. },
  4080. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  4081. var current = this.current;
  4082. var width = imgData.width;
  4083. var height = imgData.height;
  4084. var fillColor = current.fillColor;
  4085. current.maskId = 'mask' + maskCount++;
  4086. var mask = document.createElementNS(NS, 'svg:mask');
  4087. mask.setAttributeNS(null, 'id', current.maskId);
  4088. var rect = document.createElementNS(NS, 'svg:rect');
  4089. rect.setAttributeNS(null, 'x', '0');
  4090. rect.setAttributeNS(null, 'y', '0');
  4091. rect.setAttributeNS(null, 'width', pf(width));
  4092. rect.setAttributeNS(null, 'height', pf(height));
  4093. rect.setAttributeNS(null, 'fill', fillColor);
  4094. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  4095. this.defs.appendChild(mask);
  4096. this.tgrp.appendChild(rect);
  4097. this.paintInlineImageXObject(imgData, mask);
  4098. },
  4099. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4100. this.save();
  4101. if (isArray(matrix) && matrix.length === 6) {
  4102. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  4103. }
  4104. if (isArray(bbox) && bbox.length === 4) {
  4105. var width = bbox[2] - bbox[0];
  4106. var height = bbox[3] - bbox[1];
  4107. var cliprect = document.createElementNS(NS, 'svg:rect');
  4108. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4109. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4110. cliprect.setAttributeNS(null, 'width', pf(width));
  4111. cliprect.setAttributeNS(null, 'height', pf(height));
  4112. this.current.element = cliprect;
  4113. this.clip('nonzero');
  4114. this.endPath();
  4115. }
  4116. },
  4117. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  4118. this.restore();
  4119. }
  4120. };
  4121. return SVGGraphics;
  4122. }();
  4123. exports.SVGGraphics = SVGGraphics;
  4124. }));
  4125. (function (root, factory) {
  4126. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4127. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4128. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  4129. var AnnotationType = sharedUtil.AnnotationType;
  4130. var Util = sharedUtil.Util;
  4131. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  4132. var LinkTarget = displayDOMUtils.LinkTarget;
  4133. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  4134. var warn = sharedUtil.warn;
  4135. var CustomStyle = displayDOMUtils.CustomStyle;
  4136. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4137. /**
  4138. * @typedef {Object} AnnotationElementParameters
  4139. * @property {Object} data
  4140. * @property {HTMLDivElement} layer
  4141. * @property {PDFPage} page
  4142. * @property {PageViewport} viewport
  4143. * @property {IPDFLinkService} linkService
  4144. * @property {DownloadManager} downloadManager
  4145. * @property {string} imageResourcesPath
  4146. * @property {boolean} renderInteractiveForms
  4147. */
  4148. /**
  4149. * @class
  4150. * @alias AnnotationElementFactory
  4151. */
  4152. function AnnotationElementFactory() {
  4153. }
  4154. AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */
  4155. {
  4156. /**
  4157. * @param {AnnotationElementParameters} parameters
  4158. * @returns {AnnotationElement}
  4159. */
  4160. create: function AnnotationElementFactory_create(parameters) {
  4161. var subtype = parameters.data.annotationType;
  4162. switch (subtype) {
  4163. case AnnotationType.LINK:
  4164. return new LinkAnnotationElement(parameters);
  4165. case AnnotationType.TEXT:
  4166. return new TextAnnotationElement(parameters);
  4167. case AnnotationType.WIDGET:
  4168. var fieldType = parameters.data.fieldType;
  4169. switch (fieldType) {
  4170. case 'Tx':
  4171. return new TextWidgetAnnotationElement(parameters);
  4172. case 'Ch':
  4173. return new ChoiceWidgetAnnotationElement(parameters);
  4174. }
  4175. return new WidgetAnnotationElement(parameters);
  4176. case AnnotationType.POPUP:
  4177. return new PopupAnnotationElement(parameters);
  4178. case AnnotationType.HIGHLIGHT:
  4179. return new HighlightAnnotationElement(parameters);
  4180. case AnnotationType.UNDERLINE:
  4181. return new UnderlineAnnotationElement(parameters);
  4182. case AnnotationType.SQUIGGLY:
  4183. return new SquigglyAnnotationElement(parameters);
  4184. case AnnotationType.STRIKEOUT:
  4185. return new StrikeOutAnnotationElement(parameters);
  4186. case AnnotationType.FILEATTACHMENT:
  4187. return new FileAttachmentAnnotationElement(parameters);
  4188. default:
  4189. return new AnnotationElement(parameters);
  4190. }
  4191. }
  4192. };
  4193. /**
  4194. * @class
  4195. * @alias AnnotationElement
  4196. */
  4197. var AnnotationElement = function AnnotationElementClosure() {
  4198. function AnnotationElement(parameters, isRenderable) {
  4199. this.isRenderable = isRenderable || false;
  4200. this.data = parameters.data;
  4201. this.layer = parameters.layer;
  4202. this.page = parameters.page;
  4203. this.viewport = parameters.viewport;
  4204. this.linkService = parameters.linkService;
  4205. this.downloadManager = parameters.downloadManager;
  4206. this.imageResourcesPath = parameters.imageResourcesPath;
  4207. this.renderInteractiveForms = parameters.renderInteractiveForms;
  4208. if (isRenderable) {
  4209. this.container = this._createContainer();
  4210. }
  4211. }
  4212. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */
  4213. {
  4214. /**
  4215. * Create an empty container for the annotation's HTML element.
  4216. *
  4217. * @private
  4218. * @memberof AnnotationElement
  4219. * @returns {HTMLSectionElement}
  4220. */
  4221. _createContainer: function AnnotationElement_createContainer() {
  4222. var data = this.data, page = this.page, viewport = this.viewport;
  4223. var container = document.createElement('section');
  4224. var width = data.rect[2] - data.rect[0];
  4225. var height = data.rect[3] - data.rect[1];
  4226. container.setAttribute('data-annotation-id', data.id);
  4227. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4228. // position on subsequent calls to `_createContainer` (see issue 6804).
  4229. var rect = Util.normalizeRect([
  4230. data.rect[0],
  4231. page.view[3] - data.rect[1] + page.view[1],
  4232. data.rect[2],
  4233. page.view[3] - data.rect[3] + page.view[1]
  4234. ]);
  4235. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  4236. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  4237. if (data.borderStyle.width > 0) {
  4238. container.style.borderWidth = data.borderStyle.width + 'px';
  4239. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4240. // Underline styles only have a bottom border, so we do not need
  4241. // to adjust for all borders. This yields a similar result as
  4242. // Adobe Acrobat/Reader.
  4243. width = width - 2 * data.borderStyle.width;
  4244. height = height - 2 * data.borderStyle.width;
  4245. }
  4246. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4247. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4248. if (horizontalRadius > 0 || verticalRadius > 0) {
  4249. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4250. CustomStyle.setProp('borderRadius', container, radius);
  4251. }
  4252. switch (data.borderStyle.style) {
  4253. case AnnotationBorderStyleType.SOLID:
  4254. container.style.borderStyle = 'solid';
  4255. break;
  4256. case AnnotationBorderStyleType.DASHED:
  4257. container.style.borderStyle = 'dashed';
  4258. break;
  4259. case AnnotationBorderStyleType.BEVELED:
  4260. warn('Unimplemented border style: beveled');
  4261. break;
  4262. case AnnotationBorderStyleType.INSET:
  4263. warn('Unimplemented border style: inset');
  4264. break;
  4265. case AnnotationBorderStyleType.UNDERLINE:
  4266. container.style.borderBottomStyle = 'solid';
  4267. break;
  4268. default:
  4269. break;
  4270. }
  4271. if (data.color) {
  4272. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  4273. } else {
  4274. // Transparent (invisible) border, so do not draw it at all.
  4275. container.style.borderWidth = 0;
  4276. }
  4277. }
  4278. container.style.left = rect[0] + 'px';
  4279. container.style.top = rect[1] + 'px';
  4280. container.style.width = width + 'px';
  4281. container.style.height = height + 'px';
  4282. return container;
  4283. },
  4284. /**
  4285. * Create a popup for the annotation's HTML element. This is used for
  4286. * annotations that do not have a Popup entry in the dictionary, but
  4287. * are of a type that works with popups (such as Highlight annotations).
  4288. *
  4289. * @private
  4290. * @param {HTMLSectionElement} container
  4291. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4292. * @param {Object} data
  4293. * @memberof AnnotationElement
  4294. */
  4295. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  4296. // If no trigger element is specified, create it.
  4297. if (!trigger) {
  4298. trigger = document.createElement('div');
  4299. trigger.style.height = container.style.height;
  4300. trigger.style.width = container.style.width;
  4301. container.appendChild(trigger);
  4302. }
  4303. var popupElement = new PopupElement({
  4304. container: container,
  4305. trigger: trigger,
  4306. color: data.color,
  4307. title: data.title,
  4308. contents: data.contents,
  4309. hideWrapper: true
  4310. });
  4311. var popup = popupElement.render();
  4312. // Position the popup next to the annotation's container.
  4313. popup.style.left = container.style.width;
  4314. container.appendChild(popup);
  4315. },
  4316. /**
  4317. * Render the annotation's HTML element in the empty container.
  4318. *
  4319. * @public
  4320. * @memberof AnnotationElement
  4321. */
  4322. render: function AnnotationElement_render() {
  4323. throw new Error('Abstract method AnnotationElement.render called');
  4324. }
  4325. };
  4326. return AnnotationElement;
  4327. }();
  4328. /**
  4329. * @class
  4330. * @alias LinkAnnotationElement
  4331. */
  4332. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  4333. function LinkAnnotationElement(parameters) {
  4334. AnnotationElement.call(this, parameters, true);
  4335. }
  4336. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4337. /**
  4338. * Render the link annotation's HTML element in the empty container.
  4339. *
  4340. * @public
  4341. * @memberof LinkAnnotationElement
  4342. * @returns {HTMLSectionElement}
  4343. */
  4344. render: function LinkAnnotationElement_render() {
  4345. this.container.className = 'linkAnnotation';
  4346. var link = document.createElement('a');
  4347. addLinkAttributes(link, {
  4348. url: this.data.url,
  4349. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  4350. });
  4351. if (!this.data.url) {
  4352. if (this.data.action) {
  4353. this._bindNamedAction(link, this.data.action);
  4354. } else {
  4355. this._bindLink(link, this.data.dest || null);
  4356. }
  4357. }
  4358. this.container.appendChild(link);
  4359. return this.container;
  4360. },
  4361. /**
  4362. * Bind internal links to the link element.
  4363. *
  4364. * @private
  4365. * @param {Object} link
  4366. * @param {Object} destination
  4367. * @memberof LinkAnnotationElement
  4368. */
  4369. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4370. var self = this;
  4371. link.href = this.linkService.getDestinationHash(destination);
  4372. link.onclick = function () {
  4373. if (destination) {
  4374. self.linkService.navigateTo(destination);
  4375. }
  4376. return false;
  4377. };
  4378. if (destination) {
  4379. link.className = 'internalLink';
  4380. }
  4381. },
  4382. /**
  4383. * Bind named actions to the link element.
  4384. *
  4385. * @private
  4386. * @param {Object} link
  4387. * @param {Object} action
  4388. * @memberof LinkAnnotationElement
  4389. */
  4390. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  4391. var self = this;
  4392. link.href = this.linkService.getAnchorUrl('');
  4393. link.onclick = function () {
  4394. self.linkService.executeNamedAction(action);
  4395. return false;
  4396. };
  4397. link.className = 'internalLink';
  4398. }
  4399. });
  4400. return LinkAnnotationElement;
  4401. }();
  4402. /**
  4403. * @class
  4404. * @alias TextAnnotationElement
  4405. */
  4406. var TextAnnotationElement = function TextAnnotationElementClosure() {
  4407. function TextAnnotationElement(parameters) {
  4408. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4409. AnnotationElement.call(this, parameters, isRenderable);
  4410. }
  4411. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4412. /**
  4413. * Render the text annotation's HTML element in the empty container.
  4414. *
  4415. * @public
  4416. * @memberof TextAnnotationElement
  4417. * @returns {HTMLSectionElement}
  4418. */
  4419. render: function TextAnnotationElement_render() {
  4420. this.container.className = 'textAnnotation';
  4421. var image = document.createElement('img');
  4422. image.style.height = this.container.style.height;
  4423. image.style.width = this.container.style.width;
  4424. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  4425. image.alt = '[{{type}} Annotation]';
  4426. image.dataset.l10nId = 'text_annotation_type';
  4427. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  4428. if (!this.data.hasPopup) {
  4429. this._createPopup(this.container, image, this.data);
  4430. }
  4431. this.container.appendChild(image);
  4432. return this.container;
  4433. }
  4434. });
  4435. return TextAnnotationElement;
  4436. }();
  4437. /**
  4438. * @class
  4439. * @alias WidgetAnnotationElement
  4440. */
  4441. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4442. function WidgetAnnotationElement(parameters, isRenderable) {
  4443. AnnotationElement.call(this, parameters, isRenderable);
  4444. }
  4445. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4446. /**
  4447. * Render the widget annotation's HTML element in the empty container.
  4448. *
  4449. * @public
  4450. * @memberof WidgetAnnotationElement
  4451. * @returns {HTMLSectionElement}
  4452. */
  4453. render: function WidgetAnnotationElement_render() {
  4454. // Show only the container for unsupported field types.
  4455. return this.container;
  4456. }
  4457. });
  4458. return WidgetAnnotationElement;
  4459. }();
  4460. /**
  4461. * @class
  4462. * @alias TextWidgetAnnotationElement
  4463. */
  4464. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4465. var TEXT_ALIGNMENT = [
  4466. 'left',
  4467. 'center',
  4468. 'right'
  4469. ];
  4470. function TextWidgetAnnotationElement(parameters) {
  4471. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4472. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4473. }
  4474. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4475. /**
  4476. * Render the text widget annotation's HTML element in the empty container.
  4477. *
  4478. * @public
  4479. * @memberof TextWidgetAnnotationElement
  4480. * @returns {HTMLSectionElement}
  4481. */
  4482. render: function TextWidgetAnnotationElement_render() {
  4483. this.container.className = 'textWidgetAnnotation';
  4484. var element = null;
  4485. if (this.renderInteractiveForms) {
  4486. // NOTE: We cannot set the values using `element.value` below, since it
  4487. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4488. // from parsing the elements correctly for the reference tests.
  4489. if (this.data.multiLine) {
  4490. element = document.createElement('textarea');
  4491. element.textContent = this.data.fieldValue;
  4492. } else {
  4493. element = document.createElement('input');
  4494. element.type = 'text';
  4495. element.setAttribute('value', this.data.fieldValue);
  4496. }
  4497. element.disabled = this.data.readOnly;
  4498. if (this.data.maxLen !== null) {
  4499. element.maxLength = this.data.maxLen;
  4500. }
  4501. if (this.data.comb) {
  4502. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4503. var combWidth = fieldWidth / this.data.maxLen;
  4504. element.classList.add('comb');
  4505. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4506. }
  4507. } else {
  4508. element = document.createElement('div');
  4509. element.textContent = this.data.fieldValue;
  4510. element.style.verticalAlign = 'middle';
  4511. element.style.display = 'table-cell';
  4512. var font = null;
  4513. if (this.data.fontRefName) {
  4514. font = this.page.commonObjs.getData(this.data.fontRefName);
  4515. }
  4516. this._setTextStyle(element, font);
  4517. }
  4518. if (this.data.textAlignment !== null) {
  4519. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4520. }
  4521. this.container.appendChild(element);
  4522. return this.container;
  4523. },
  4524. /**
  4525. * Apply text styles to the text in the element.
  4526. *
  4527. * @private
  4528. * @param {HTMLDivElement} element
  4529. * @param {Object} font
  4530. * @memberof TextWidgetAnnotationElement
  4531. */
  4532. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4533. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4534. var style = element.style;
  4535. style.fontSize = this.data.fontSize + 'px';
  4536. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4537. if (!font) {
  4538. return;
  4539. }
  4540. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4541. style.fontStyle = font.italic ? 'italic' : 'normal';
  4542. // Use a reasonable default font if the font doesn't specify a fallback.
  4543. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4544. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4545. style.fontFamily = fontFamily + fallbackName;
  4546. }
  4547. });
  4548. return TextWidgetAnnotationElement;
  4549. }();
  4550. /**
  4551. * @class
  4552. * @alias ChoiceWidgetAnnotationElement
  4553. */
  4554. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4555. function ChoiceWidgetAnnotationElement(parameters) {
  4556. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4557. }
  4558. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4559. /**
  4560. * Render the choice widget annotation's HTML element in the empty
  4561. * container.
  4562. *
  4563. * @public
  4564. * @memberof ChoiceWidgetAnnotationElement
  4565. * @returns {HTMLSectionElement}
  4566. */
  4567. render: function ChoiceWidgetAnnotationElement_render() {
  4568. this.container.className = 'choiceWidgetAnnotation';
  4569. var selectElement = document.createElement('select');
  4570. selectElement.disabled = this.data.readOnly;
  4571. if (!this.data.combo) {
  4572. // List boxes have a size and (optionally) multiple selection.
  4573. selectElement.size = this.data.options.length;
  4574. if (this.data.multiSelect) {
  4575. selectElement.multiple = true;
  4576. }
  4577. }
  4578. // Insert the options into the choice field.
  4579. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4580. var option = this.data.options[i];
  4581. var optionElement = document.createElement('option');
  4582. optionElement.textContent = option.displayValue;
  4583. optionElement.value = option.exportValue;
  4584. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4585. optionElement.setAttribute('selected', true);
  4586. }
  4587. selectElement.appendChild(optionElement);
  4588. }
  4589. this.container.appendChild(selectElement);
  4590. return this.container;
  4591. }
  4592. });
  4593. return ChoiceWidgetAnnotationElement;
  4594. }();
  4595. /**
  4596. * @class
  4597. * @alias PopupAnnotationElement
  4598. */
  4599. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4600. function PopupAnnotationElement(parameters) {
  4601. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4602. AnnotationElement.call(this, parameters, isRenderable);
  4603. }
  4604. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4605. /**
  4606. * Render the popup annotation's HTML element in the empty container.
  4607. *
  4608. * @public
  4609. * @memberof PopupAnnotationElement
  4610. * @returns {HTMLSectionElement}
  4611. */
  4612. render: function PopupAnnotationElement_render() {
  4613. this.container.className = 'popupAnnotation';
  4614. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4615. var parentElement = this.layer.querySelector(selector);
  4616. if (!parentElement) {
  4617. return this.container;
  4618. }
  4619. var popup = new PopupElement({
  4620. container: this.container,
  4621. trigger: parentElement,
  4622. color: this.data.color,
  4623. title: this.data.title,
  4624. contents: this.data.contents
  4625. });
  4626. // Position the popup next to the parent annotation's container.
  4627. // PDF viewers ignore a popup annotation's rectangle.
  4628. var parentLeft = parseFloat(parentElement.style.left);
  4629. var parentWidth = parseFloat(parentElement.style.width);
  4630. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4631. this.container.style.left = parentLeft + parentWidth + 'px';
  4632. this.container.appendChild(popup.render());
  4633. return this.container;
  4634. }
  4635. });
  4636. return PopupAnnotationElement;
  4637. }();
  4638. /**
  4639. * @class
  4640. * @alias PopupElement
  4641. */
  4642. var PopupElement = function PopupElementClosure() {
  4643. var BACKGROUND_ENLIGHT = 0.7;
  4644. function PopupElement(parameters) {
  4645. this.container = parameters.container;
  4646. this.trigger = parameters.trigger;
  4647. this.color = parameters.color;
  4648. this.title = parameters.title;
  4649. this.contents = parameters.contents;
  4650. this.hideWrapper = parameters.hideWrapper || false;
  4651. this.pinned = false;
  4652. }
  4653. PopupElement.prototype = /** @lends PopupElement.prototype */
  4654. {
  4655. /**
  4656. * Render the popup's HTML element.
  4657. *
  4658. * @public
  4659. * @memberof PopupElement
  4660. * @returns {HTMLSectionElement}
  4661. */
  4662. render: function PopupElement_render() {
  4663. var wrapper = document.createElement('div');
  4664. wrapper.className = 'popupWrapper';
  4665. // For Popup annotations we hide the entire section because it contains
  4666. // only the popup. However, for Text annotations without a separate Popup
  4667. // annotation, we cannot hide the entire container as the image would
  4668. // disappear too. In that special case, hiding the wrapper suffices.
  4669. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4670. this.hideElement.setAttribute('hidden', true);
  4671. var popup = document.createElement('div');
  4672. popup.className = 'popup';
  4673. var color = this.color;
  4674. if (color) {
  4675. // Enlighten the color.
  4676. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4677. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4678. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4679. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4680. }
  4681. var contents = this._formatContents(this.contents);
  4682. var title = document.createElement('h1');
  4683. title.textContent = this.title;
  4684. // Attach the event listeners to the trigger element.
  4685. this.trigger.addEventListener('click', this._toggle.bind(this));
  4686. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4687. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4688. popup.addEventListener('click', this._hide.bind(this, true));
  4689. popup.appendChild(title);
  4690. popup.appendChild(contents);
  4691. wrapper.appendChild(popup);
  4692. return wrapper;
  4693. },
  4694. /**
  4695. * Format the contents of the popup by adding newlines where necessary.
  4696. *
  4697. * @private
  4698. * @param {string} contents
  4699. * @memberof PopupElement
  4700. * @returns {HTMLParagraphElement}
  4701. */
  4702. _formatContents: function PopupElement_formatContents(contents) {
  4703. var p = document.createElement('p');
  4704. var lines = contents.split(/(?:\r\n?|\n)/);
  4705. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4706. var line = lines[i];
  4707. p.appendChild(document.createTextNode(line));
  4708. if (i < ii - 1) {
  4709. p.appendChild(document.createElement('br'));
  4710. }
  4711. }
  4712. return p;
  4713. },
  4714. /**
  4715. * Toggle the visibility of the popup.
  4716. *
  4717. * @private
  4718. * @memberof PopupElement
  4719. */
  4720. _toggle: function PopupElement_toggle() {
  4721. if (this.pinned) {
  4722. this._hide(true);
  4723. } else {
  4724. this._show(true);
  4725. }
  4726. },
  4727. /**
  4728. * Show the popup.
  4729. *
  4730. * @private
  4731. * @param {boolean} pin
  4732. * @memberof PopupElement
  4733. */
  4734. _show: function PopupElement_show(pin) {
  4735. if (pin) {
  4736. this.pinned = true;
  4737. }
  4738. if (this.hideElement.hasAttribute('hidden')) {
  4739. this.hideElement.removeAttribute('hidden');
  4740. this.container.style.zIndex += 1;
  4741. }
  4742. },
  4743. /**
  4744. * Hide the popup.
  4745. *
  4746. * @private
  4747. * @param {boolean} unpin
  4748. * @memberof PopupElement
  4749. */
  4750. _hide: function PopupElement_hide(unpin) {
  4751. if (unpin) {
  4752. this.pinned = false;
  4753. }
  4754. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4755. this.hideElement.setAttribute('hidden', true);
  4756. this.container.style.zIndex -= 1;
  4757. }
  4758. }
  4759. };
  4760. return PopupElement;
  4761. }();
  4762. /**
  4763. * @class
  4764. * @alias HighlightAnnotationElement
  4765. */
  4766. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4767. function HighlightAnnotationElement(parameters) {
  4768. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4769. AnnotationElement.call(this, parameters, isRenderable);
  4770. }
  4771. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4772. /**
  4773. * Render the highlight annotation's HTML element in the empty container.
  4774. *
  4775. * @public
  4776. * @memberof HighlightAnnotationElement
  4777. * @returns {HTMLSectionElement}
  4778. */
  4779. render: function HighlightAnnotationElement_render() {
  4780. this.container.className = 'highlightAnnotation';
  4781. if (!this.data.hasPopup) {
  4782. this._createPopup(this.container, null, this.data);
  4783. }
  4784. return this.container;
  4785. }
  4786. });
  4787. return HighlightAnnotationElement;
  4788. }();
  4789. /**
  4790. * @class
  4791. * @alias UnderlineAnnotationElement
  4792. */
  4793. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4794. function UnderlineAnnotationElement(parameters) {
  4795. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4796. AnnotationElement.call(this, parameters, isRenderable);
  4797. }
  4798. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4799. /**
  4800. * Render the underline annotation's HTML element in the empty container.
  4801. *
  4802. * @public
  4803. * @memberof UnderlineAnnotationElement
  4804. * @returns {HTMLSectionElement}
  4805. */
  4806. render: function UnderlineAnnotationElement_render() {
  4807. this.container.className = 'underlineAnnotation';
  4808. if (!this.data.hasPopup) {
  4809. this._createPopup(this.container, null, this.data);
  4810. }
  4811. return this.container;
  4812. }
  4813. });
  4814. return UnderlineAnnotationElement;
  4815. }();
  4816. /**
  4817. * @class
  4818. * @alias SquigglyAnnotationElement
  4819. */
  4820. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4821. function SquigglyAnnotationElement(parameters) {
  4822. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4823. AnnotationElement.call(this, parameters, isRenderable);
  4824. }
  4825. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4826. /**
  4827. * Render the squiggly annotation's HTML element in the empty container.
  4828. *
  4829. * @public
  4830. * @memberof SquigglyAnnotationElement
  4831. * @returns {HTMLSectionElement}
  4832. */
  4833. render: function SquigglyAnnotationElement_render() {
  4834. this.container.className = 'squigglyAnnotation';
  4835. if (!this.data.hasPopup) {
  4836. this._createPopup(this.container, null, this.data);
  4837. }
  4838. return this.container;
  4839. }
  4840. });
  4841. return SquigglyAnnotationElement;
  4842. }();
  4843. /**
  4844. * @class
  4845. * @alias StrikeOutAnnotationElement
  4846. */
  4847. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4848. function StrikeOutAnnotationElement(parameters) {
  4849. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4850. AnnotationElement.call(this, parameters, isRenderable);
  4851. }
  4852. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4853. /**
  4854. * Render the strikeout annotation's HTML element in the empty container.
  4855. *
  4856. * @public
  4857. * @memberof StrikeOutAnnotationElement
  4858. * @returns {HTMLSectionElement}
  4859. */
  4860. render: function StrikeOutAnnotationElement_render() {
  4861. this.container.className = 'strikeoutAnnotation';
  4862. if (!this.data.hasPopup) {
  4863. this._createPopup(this.container, null, this.data);
  4864. }
  4865. return this.container;
  4866. }
  4867. });
  4868. return StrikeOutAnnotationElement;
  4869. }();
  4870. /**
  4871. * @class
  4872. * @alias FileAttachmentAnnotationElement
  4873. */
  4874. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4875. function FileAttachmentAnnotationElement(parameters) {
  4876. AnnotationElement.call(this, parameters, true);
  4877. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4878. this.content = parameters.data.file.content;
  4879. }
  4880. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4881. /**
  4882. * Render the file attachment annotation's HTML element in the empty
  4883. * container.
  4884. *
  4885. * @public
  4886. * @memberof FileAttachmentAnnotationElement
  4887. * @returns {HTMLSectionElement}
  4888. */
  4889. render: function FileAttachmentAnnotationElement_render() {
  4890. this.container.className = 'fileAttachmentAnnotation';
  4891. var trigger = document.createElement('div');
  4892. trigger.style.height = this.container.style.height;
  4893. trigger.style.width = this.container.style.width;
  4894. trigger.addEventListener('dblclick', this._download.bind(this));
  4895. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4896. this._createPopup(this.container, trigger, this.data);
  4897. }
  4898. this.container.appendChild(trigger);
  4899. return this.container;
  4900. },
  4901. /**
  4902. * Download the file attachment associated with this annotation.
  4903. *
  4904. * @private
  4905. * @memberof FileAttachmentAnnotationElement
  4906. */
  4907. _download: function FileAttachmentAnnotationElement_download() {
  4908. if (!this.downloadManager) {
  4909. warn('Download cannot be started due to unavailable download manager');
  4910. return;
  4911. }
  4912. this.downloadManager.downloadData(this.content, this.filename, '');
  4913. }
  4914. });
  4915. return FileAttachmentAnnotationElement;
  4916. }();
  4917. /**
  4918. * @typedef {Object} AnnotationLayerParameters
  4919. * @property {PageViewport} viewport
  4920. * @property {HTMLDivElement} div
  4921. * @property {Array} annotations
  4922. * @property {PDFPage} page
  4923. * @property {IPDFLinkService} linkService
  4924. * @property {string} imageResourcesPath
  4925. * @property {boolean} renderInteractiveForms
  4926. */
  4927. /**
  4928. * @class
  4929. * @alias AnnotationLayer
  4930. */
  4931. var AnnotationLayer = function AnnotationLayerClosure() {
  4932. return {
  4933. /**
  4934. * Render a new annotation layer with all annotation elements.
  4935. *
  4936. * @public
  4937. * @param {AnnotationLayerParameters} parameters
  4938. * @memberof AnnotationLayer
  4939. */
  4940. render: function AnnotationLayer_render(parameters) {
  4941. var annotationElementFactory = new AnnotationElementFactory();
  4942. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4943. var data = parameters.annotations[i];
  4944. if (!data) {
  4945. continue;
  4946. }
  4947. var properties = {
  4948. data: data,
  4949. layer: parameters.div,
  4950. page: parameters.page,
  4951. viewport: parameters.viewport,
  4952. linkService: parameters.linkService,
  4953. downloadManager: parameters.downloadManager,
  4954. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4955. renderInteractiveForms: parameters.renderInteractiveForms || false
  4956. };
  4957. var element = annotationElementFactory.create(properties);
  4958. if (element.isRenderable) {
  4959. parameters.div.appendChild(element.render());
  4960. }
  4961. }
  4962. },
  4963. /**
  4964. * Update the annotation elements on existing annotation layer.
  4965. *
  4966. * @public
  4967. * @param {AnnotationLayerParameters} parameters
  4968. * @memberof AnnotationLayer
  4969. */
  4970. update: function AnnotationLayer_update(parameters) {
  4971. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4972. var data = parameters.annotations[i];
  4973. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4974. if (element) {
  4975. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4976. }
  4977. }
  4978. parameters.div.removeAttribute('hidden');
  4979. }
  4980. };
  4981. }();
  4982. exports.AnnotationLayer = AnnotationLayer;
  4983. }));
  4984. (function (root, factory) {
  4985. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4986. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4987. var Util = sharedUtil.Util;
  4988. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4989. var CustomStyle = displayDOMUtils.CustomStyle;
  4990. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4991. /**
  4992. * Text layer render parameters.
  4993. *
  4994. * @typedef {Object} TextLayerRenderParameters
  4995. * @property {TextContent} textContent - Text content to render (the object is
  4996. * returned by the page's getTextContent() method).
  4997. * @property {HTMLElement} container - HTML element that will contain text runs.
  4998. * @property {PageViewport} viewport - The target viewport to properly
  4999. * layout the text runs.
  5000. * @property {Array} textDivs - (optional) HTML elements that are correspond
  5001. * the text items of the textContent input. This is output and shall be
  5002. * initially be set to empty array.
  5003. * @property {number} timeout - (optional) Delay in milliseconds before
  5004. * rendering of the text runs occurs.
  5005. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  5006. * text selection enhancement.
  5007. */
  5008. var renderTextLayer = function renderTextLayerClosure() {
  5009. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  5010. var NonWhitespaceRegexp = /\S/;
  5011. function isAllWhitespace(str) {
  5012. return !NonWhitespaceRegexp.test(str);
  5013. }
  5014. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  5015. // creating many intermediate strings when building their 'style' properties.
  5016. var styleBuf = [
  5017. 'left: ',
  5018. 0,
  5019. 'px; top: ',
  5020. 0,
  5021. 'px; font-size: ',
  5022. 0,
  5023. 'px; font-family: ',
  5024. '',
  5025. ';'
  5026. ];
  5027. function appendText(task, geom, styles) {
  5028. // Initialize all used properties to keep the caches monomorphic.
  5029. var textDiv = document.createElement('div');
  5030. var textDivProperties = {
  5031. style: null,
  5032. angle: 0,
  5033. canvasWidth: 0,
  5034. isWhitespace: false,
  5035. originalTransform: null,
  5036. paddingBottom: 0,
  5037. paddingLeft: 0,
  5038. paddingRight: 0,
  5039. paddingTop: 0,
  5040. scale: 1
  5041. };
  5042. task._textDivs.push(textDiv);
  5043. if (isAllWhitespace(geom.str)) {
  5044. textDivProperties.isWhitespace = true;
  5045. task._textDivProperties.set(textDiv, textDivProperties);
  5046. return;
  5047. }
  5048. var tx = Util.transform(task._viewport.transform, geom.transform);
  5049. var angle = Math.atan2(tx[1], tx[0]);
  5050. var style = styles[geom.fontName];
  5051. if (style.vertical) {
  5052. angle += Math.PI / 2;
  5053. }
  5054. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  5055. var fontAscent = fontHeight;
  5056. if (style.ascent) {
  5057. fontAscent = style.ascent * fontAscent;
  5058. } else if (style.descent) {
  5059. fontAscent = (1 + style.descent) * fontAscent;
  5060. }
  5061. var left;
  5062. var top;
  5063. if (angle === 0) {
  5064. left = tx[4];
  5065. top = tx[5] - fontAscent;
  5066. } else {
  5067. left = tx[4] + fontAscent * Math.sin(angle);
  5068. top = tx[5] - fontAscent * Math.cos(angle);
  5069. }
  5070. styleBuf[1] = left;
  5071. styleBuf[3] = top;
  5072. styleBuf[5] = fontHeight;
  5073. styleBuf[7] = style.fontFamily;
  5074. textDivProperties.style = styleBuf.join('');
  5075. textDiv.setAttribute('style', textDivProperties.style);
  5076. textDiv.textContent = geom.str;
  5077. // |fontName| is only used by the Font Inspector. This test will succeed
  5078. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  5079. // not worth the effort to do a more accurate test. We only use `dataset`
  5080. // here to make the font name available for the debugger.
  5081. if (getDefaultSetting('pdfBug')) {
  5082. textDiv.dataset.fontName = geom.fontName;
  5083. }
  5084. if (angle !== 0) {
  5085. textDivProperties.angle = angle * (180 / Math.PI);
  5086. }
  5087. // We don't bother scaling single-char text divs, because it has very
  5088. // little effect on text highlighting. This makes scrolling on docs with
  5089. // lots of such divs a lot faster.
  5090. if (geom.str.length > 1) {
  5091. if (style.vertical) {
  5092. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  5093. } else {
  5094. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  5095. }
  5096. }
  5097. task._textDivProperties.set(textDiv, textDivProperties);
  5098. if (task._enhanceTextSelection) {
  5099. var angleCos = 1, angleSin = 0;
  5100. if (angle !== 0) {
  5101. angleCos = Math.cos(angle);
  5102. angleSin = Math.sin(angle);
  5103. }
  5104. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  5105. var divHeight = fontHeight;
  5106. var m, b;
  5107. if (angle !== 0) {
  5108. m = [
  5109. angleCos,
  5110. angleSin,
  5111. -angleSin,
  5112. angleCos,
  5113. left,
  5114. top
  5115. ];
  5116. b = Util.getAxialAlignedBoundingBox([
  5117. 0,
  5118. 0,
  5119. divWidth,
  5120. divHeight
  5121. ], m);
  5122. } else {
  5123. b = [
  5124. left,
  5125. top,
  5126. left + divWidth,
  5127. top + divHeight
  5128. ];
  5129. }
  5130. task._bounds.push({
  5131. left: b[0],
  5132. top: b[1],
  5133. right: b[2],
  5134. bottom: b[3],
  5135. div: textDiv,
  5136. size: [
  5137. divWidth,
  5138. divHeight
  5139. ],
  5140. m: m
  5141. });
  5142. }
  5143. }
  5144. function render(task) {
  5145. if (task._canceled) {
  5146. return;
  5147. }
  5148. var textLayerFrag = task._container;
  5149. var textDivs = task._textDivs;
  5150. var capability = task._capability;
  5151. var textDivsLength = textDivs.length;
  5152. // No point in rendering many divs as it would make the browser
  5153. // unusable even after the divs are rendered.
  5154. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  5155. task._renderingDone = true;
  5156. capability.resolve();
  5157. return;
  5158. }
  5159. var canvas = document.createElement('canvas');
  5160. canvas.mozOpaque = true;
  5161. var ctx = canvas.getContext('2d', { alpha: false });
  5162. var lastFontSize;
  5163. var lastFontFamily;
  5164. for (var i = 0; i < textDivsLength; i++) {
  5165. var textDiv = textDivs[i];
  5166. var textDivProperties = task._textDivProperties.get(textDiv);
  5167. if (textDivProperties.isWhitespace) {
  5168. continue;
  5169. }
  5170. var fontSize = textDiv.style.fontSize;
  5171. var fontFamily = textDiv.style.fontFamily;
  5172. // Only build font string and set to context if different from last.
  5173. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  5174. ctx.font = fontSize + ' ' + fontFamily;
  5175. lastFontSize = fontSize;
  5176. lastFontFamily = fontFamily;
  5177. }
  5178. var width = ctx.measureText(textDiv.textContent).width;
  5179. textLayerFrag.appendChild(textDiv);
  5180. var transform = '';
  5181. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  5182. textDivProperties.scale = textDivProperties.canvasWidth / width;
  5183. transform = 'scaleX(' + textDivProperties.scale + ')';
  5184. }
  5185. if (textDivProperties.angle !== 0) {
  5186. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  5187. }
  5188. if (transform !== '') {
  5189. textDivProperties.originalTransform = transform;
  5190. CustomStyle.setProp('transform', textDiv, transform);
  5191. }
  5192. task._textDivProperties.set(textDiv, textDivProperties);
  5193. }
  5194. task._renderingDone = true;
  5195. capability.resolve();
  5196. }
  5197. function expand(task) {
  5198. var bounds = task._bounds;
  5199. var viewport = task._viewport;
  5200. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  5201. for (var i = 0; i < expanded.length; i++) {
  5202. var div = bounds[i].div;
  5203. var divProperties = task._textDivProperties.get(div);
  5204. if (divProperties.angle === 0) {
  5205. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  5206. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  5207. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  5208. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  5209. task._textDivProperties.set(div, divProperties);
  5210. continue;
  5211. }
  5212. // Box is rotated -- trying to find padding so rotated div will not
  5213. // exceed its expanded bounds.
  5214. var e = expanded[i], b = bounds[i];
  5215. var m = b.m, c = m[0], s = m[1];
  5216. // Finding intersections with expanded box.
  5217. var points = [
  5218. [
  5219. 0,
  5220. 0
  5221. ],
  5222. [
  5223. 0,
  5224. b.size[1]
  5225. ],
  5226. [
  5227. b.size[0],
  5228. 0
  5229. ],
  5230. b.size
  5231. ];
  5232. var ts = new Float64Array(64);
  5233. points.forEach(function (p, i) {
  5234. var t = Util.applyTransform(p, m);
  5235. ts[i + 0] = c && (e.left - t[0]) / c;
  5236. ts[i + 4] = s && (e.top - t[1]) / s;
  5237. ts[i + 8] = c && (e.right - t[0]) / c;
  5238. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5239. ts[i + 16] = s && (e.left - t[0]) / -s;
  5240. ts[i + 20] = c && (e.top - t[1]) / c;
  5241. ts[i + 24] = s && (e.right - t[0]) / -s;
  5242. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5243. ts[i + 32] = c && (e.left - t[0]) / -c;
  5244. ts[i + 36] = s && (e.top - t[1]) / -s;
  5245. ts[i + 40] = c && (e.right - t[0]) / -c;
  5246. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5247. ts[i + 48] = s && (e.left - t[0]) / s;
  5248. ts[i + 52] = c && (e.top - t[1]) / -c;
  5249. ts[i + 56] = s && (e.right - t[0]) / s;
  5250. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5251. });
  5252. var findPositiveMin = function (ts, offset, count) {
  5253. var result = 0;
  5254. for (var i = 0; i < count; i++) {
  5255. var t = ts[offset++];
  5256. if (t > 0) {
  5257. result = result ? Math.min(t, result) : t;
  5258. }
  5259. }
  5260. return result;
  5261. };
  5262. // Not based on math, but to simplify calculations, using cos and sin
  5263. // absolute values to not exceed the box (it can but insignificantly).
  5264. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5265. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5266. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5267. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5268. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5269. task._textDivProperties.set(div, divProperties);
  5270. }
  5271. }
  5272. function expandBounds(width, height, boxes) {
  5273. var bounds = boxes.map(function (box, i) {
  5274. return {
  5275. x1: box.left,
  5276. y1: box.top,
  5277. x2: box.right,
  5278. y2: box.bottom,
  5279. index: i,
  5280. x1New: undefined,
  5281. x2New: undefined
  5282. };
  5283. });
  5284. expandBoundsLTR(width, bounds);
  5285. var expanded = new Array(boxes.length);
  5286. bounds.forEach(function (b) {
  5287. var i = b.index;
  5288. expanded[i] = {
  5289. left: b.x1New,
  5290. top: 0,
  5291. right: b.x2New,
  5292. bottom: 0
  5293. };
  5294. });
  5295. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5296. // array and objects.
  5297. boxes.map(function (box, i) {
  5298. var e = expanded[i], b = bounds[i];
  5299. b.x1 = box.top;
  5300. b.y1 = width - e.right;
  5301. b.x2 = box.bottom;
  5302. b.y2 = width - e.left;
  5303. b.index = i;
  5304. b.x1New = undefined;
  5305. b.x2New = undefined;
  5306. });
  5307. expandBoundsLTR(height, bounds);
  5308. bounds.forEach(function (b) {
  5309. var i = b.index;
  5310. expanded[i].top = b.x1New;
  5311. expanded[i].bottom = b.x2New;
  5312. });
  5313. return expanded;
  5314. }
  5315. function expandBoundsLTR(width, bounds) {
  5316. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5317. bounds.sort(function (a, b) {
  5318. return a.x1 - b.x1 || a.index - b.index;
  5319. });
  5320. // First we see on the horizon is a fake boundary.
  5321. var fakeBoundary = {
  5322. x1: -Infinity,
  5323. y1: -Infinity,
  5324. x2: 0,
  5325. y2: Infinity,
  5326. index: -1,
  5327. x1New: 0,
  5328. x2New: 0
  5329. };
  5330. var horizon = [{
  5331. start: -Infinity,
  5332. end: Infinity,
  5333. boundary: fakeBoundary
  5334. }];
  5335. bounds.forEach(function (boundary) {
  5336. // Searching for the affected part of horizon.
  5337. // TODO red-black tree or simple binary search
  5338. var i = 0;
  5339. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5340. i++;
  5341. }
  5342. var j = horizon.length - 1;
  5343. while (j >= 0 && horizon[j].start >= boundary.y2) {
  5344. j--;
  5345. }
  5346. var horizonPart, affectedBoundary;
  5347. var q, k, maxXNew = -Infinity;
  5348. for (q = i; q <= j; q++) {
  5349. horizonPart = horizon[q];
  5350. affectedBoundary = horizonPart.boundary;
  5351. var xNew;
  5352. if (affectedBoundary.x2 > boundary.x1) {
  5353. // In the middle of the previous element, new x shall be at the
  5354. // boundary start. Extending if further if the affected bondary
  5355. // placed on top of the current one.
  5356. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  5357. } else if (affectedBoundary.x2New === undefined) {
  5358. // We have some space in between, new x in middle will be a fair
  5359. // choice.
  5360. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5361. } else {
  5362. // Affected boundary has x2new set, using it as new x.
  5363. xNew = affectedBoundary.x2New;
  5364. }
  5365. if (xNew > maxXNew) {
  5366. maxXNew = xNew;
  5367. }
  5368. }
  5369. // Set new x1 for current boundary.
  5370. boundary.x1New = maxXNew;
  5371. // Adjusts new x2 for the affected boundaries.
  5372. for (q = i; q <= j; q++) {
  5373. horizonPart = horizon[q];
  5374. affectedBoundary = horizonPart.boundary;
  5375. if (affectedBoundary.x2New === undefined) {
  5376. // Was not set yet, choosing new x if possible.
  5377. if (affectedBoundary.x2 > boundary.x1) {
  5378. // Current and affected boundaries intersect. If affected boundary
  5379. // is placed on top of the current, shrinking the affected.
  5380. if (affectedBoundary.index > boundary.index) {
  5381. affectedBoundary.x2New = affectedBoundary.x2;
  5382. }
  5383. } else {
  5384. affectedBoundary.x2New = maxXNew;
  5385. }
  5386. } else if (affectedBoundary.x2New > maxXNew) {
  5387. // Affected boundary is touching new x, pushing it back.
  5388. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5389. }
  5390. }
  5391. // Fixing the horizon.
  5392. var changedHorizon = [], lastBoundary = null;
  5393. for (q = i; q <= j; q++) {
  5394. horizonPart = horizon[q];
  5395. affectedBoundary = horizonPart.boundary;
  5396. // Checking which boundary will be visible.
  5397. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  5398. if (lastBoundary === useBoundary) {
  5399. // Merging with previous.
  5400. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5401. } else {
  5402. changedHorizon.push({
  5403. start: horizonPart.start,
  5404. end: horizonPart.end,
  5405. boundary: useBoundary
  5406. });
  5407. lastBoundary = useBoundary;
  5408. }
  5409. }
  5410. if (horizon[i].start < boundary.y1) {
  5411. changedHorizon[0].start = boundary.y1;
  5412. changedHorizon.unshift({
  5413. start: horizon[i].start,
  5414. end: boundary.y1,
  5415. boundary: horizon[i].boundary
  5416. });
  5417. }
  5418. if (boundary.y2 < horizon[j].end) {
  5419. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5420. changedHorizon.push({
  5421. start: boundary.y2,
  5422. end: horizon[j].end,
  5423. boundary: horizon[j].boundary
  5424. });
  5425. }
  5426. // Set x2 new of boundary that is no longer visible (see overlapping case
  5427. // above).
  5428. // TODO more efficient, e.g. via reference counting.
  5429. for (q = i; q <= j; q++) {
  5430. horizonPart = horizon[q];
  5431. affectedBoundary = horizonPart.boundary;
  5432. if (affectedBoundary.x2New !== undefined) {
  5433. continue;
  5434. }
  5435. var used = false;
  5436. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  5437. used = horizon[k].boundary === affectedBoundary;
  5438. }
  5439. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  5440. used = horizon[k].boundary === affectedBoundary;
  5441. }
  5442. for (k = 0; !used && k < changedHorizon.length; k++) {
  5443. used = changedHorizon[k].boundary === affectedBoundary;
  5444. }
  5445. if (!used) {
  5446. affectedBoundary.x2New = maxXNew;
  5447. }
  5448. }
  5449. Array.prototype.splice.apply(horizon, [
  5450. i,
  5451. j - i + 1
  5452. ].concat(changedHorizon));
  5453. });
  5454. // Set new x2 for all unset boundaries.
  5455. horizon.forEach(function (horizonPart) {
  5456. var affectedBoundary = horizonPart.boundary;
  5457. if (affectedBoundary.x2New === undefined) {
  5458. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5459. }
  5460. });
  5461. }
  5462. /**
  5463. * Text layer rendering task.
  5464. *
  5465. * @param {TextContent} textContent
  5466. * @param {HTMLElement} container
  5467. * @param {PageViewport} viewport
  5468. * @param {Array} textDivs
  5469. * @param {boolean} enhanceTextSelection
  5470. * @private
  5471. */
  5472. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  5473. this._textContent = textContent;
  5474. this._container = container;
  5475. this._viewport = viewport;
  5476. this._textDivs = textDivs || [];
  5477. this._textDivProperties = new WeakMap();
  5478. this._renderingDone = false;
  5479. this._canceled = false;
  5480. this._capability = createPromiseCapability();
  5481. this._renderTimer = null;
  5482. this._bounds = [];
  5483. this._enhanceTextSelection = !!enhanceTextSelection;
  5484. }
  5485. TextLayerRenderTask.prototype = {
  5486. get promise() {
  5487. return this._capability.promise;
  5488. },
  5489. cancel: function TextLayer_cancel() {
  5490. this._canceled = true;
  5491. if (this._renderTimer !== null) {
  5492. clearTimeout(this._renderTimer);
  5493. this._renderTimer = null;
  5494. }
  5495. this._capability.reject('canceled');
  5496. },
  5497. _render: function TextLayer_render(timeout) {
  5498. var textItems = this._textContent.items;
  5499. var textStyles = this._textContent.styles;
  5500. for (var i = 0, len = textItems.length; i < len; i++) {
  5501. appendText(this, textItems[i], textStyles);
  5502. }
  5503. if (!timeout) {
  5504. // Render right away
  5505. render(this);
  5506. } else {
  5507. // Schedule
  5508. var self = this;
  5509. this._renderTimer = setTimeout(function () {
  5510. render(self);
  5511. self._renderTimer = null;
  5512. }, timeout);
  5513. }
  5514. },
  5515. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5516. if (!this._enhanceTextSelection || !this._renderingDone) {
  5517. return;
  5518. }
  5519. if (this._bounds !== null) {
  5520. expand(this);
  5521. this._bounds = null;
  5522. }
  5523. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5524. var div = this._textDivs[i];
  5525. var divProperties = this._textDivProperties.get(div);
  5526. if (divProperties.isWhitespace) {
  5527. continue;
  5528. }
  5529. if (expandDivs) {
  5530. var transform = '', padding = '';
  5531. if (divProperties.scale !== 1) {
  5532. transform = 'scaleX(' + divProperties.scale + ')';
  5533. }
  5534. if (divProperties.angle !== 0) {
  5535. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5536. }
  5537. if (divProperties.paddingLeft !== 0) {
  5538. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  5539. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  5540. }
  5541. if (divProperties.paddingTop !== 0) {
  5542. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5543. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  5544. }
  5545. if (divProperties.paddingRight !== 0) {
  5546. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  5547. }
  5548. if (divProperties.paddingBottom !== 0) {
  5549. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  5550. }
  5551. if (padding !== '') {
  5552. div.setAttribute('style', divProperties.style + padding);
  5553. }
  5554. if (transform !== '') {
  5555. CustomStyle.setProp('transform', div, transform);
  5556. }
  5557. } else {
  5558. div.style.padding = 0;
  5559. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  5560. }
  5561. }
  5562. }
  5563. };
  5564. /**
  5565. * Starts rendering of the text layer.
  5566. *
  5567. * @param {TextLayerRenderParameters} renderParameters
  5568. * @returns {TextLayerRenderTask}
  5569. */
  5570. function renderTextLayer(renderParameters) {
  5571. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  5572. task._render(renderParameters.timeout);
  5573. return task;
  5574. }
  5575. return renderTextLayer;
  5576. }();
  5577. exports.renderTextLayer = renderTextLayer;
  5578. }));
  5579. (function (root, factory) {
  5580. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  5581. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5582. var shadow = sharedUtil.shadow;
  5583. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5584. var WebGLUtils = function WebGLUtilsClosure() {
  5585. function loadShader(gl, code, shaderType) {
  5586. var shader = gl.createShader(shaderType);
  5587. gl.shaderSource(shader, code);
  5588. gl.compileShader(shader);
  5589. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5590. if (!compiled) {
  5591. var errorMsg = gl.getShaderInfoLog(shader);
  5592. throw new Error('Error during shader compilation: ' + errorMsg);
  5593. }
  5594. return shader;
  5595. }
  5596. function createVertexShader(gl, code) {
  5597. return loadShader(gl, code, gl.VERTEX_SHADER);
  5598. }
  5599. function createFragmentShader(gl, code) {
  5600. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5601. }
  5602. function createProgram(gl, shaders) {
  5603. var program = gl.createProgram();
  5604. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5605. gl.attachShader(program, shaders[i]);
  5606. }
  5607. gl.linkProgram(program);
  5608. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5609. if (!linked) {
  5610. var errorMsg = gl.getProgramInfoLog(program);
  5611. throw new Error('Error during program linking: ' + errorMsg);
  5612. }
  5613. return program;
  5614. }
  5615. function createTexture(gl, image, textureId) {
  5616. gl.activeTexture(textureId);
  5617. var texture = gl.createTexture();
  5618. gl.bindTexture(gl.TEXTURE_2D, texture);
  5619. // Set the parameters so we can render any size image.
  5620. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5624. // Upload the image into the texture.
  5625. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5626. return texture;
  5627. }
  5628. var currentGL, currentCanvas;
  5629. function generateGL() {
  5630. if (currentGL) {
  5631. return;
  5632. }
  5633. currentCanvas = document.createElement('canvas');
  5634. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  5635. }
  5636. var smaskVertexShaderCode = '\
  5637. attribute vec2 a_position; \
  5638. attribute vec2 a_texCoord; \
  5639. \
  5640. uniform vec2 u_resolution; \
  5641. \
  5642. varying vec2 v_texCoord; \
  5643. \
  5644. void main() { \
  5645. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5646. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5647. \
  5648. v_texCoord = a_texCoord; \
  5649. } ';
  5650. var smaskFragmentShaderCode = '\
  5651. precision mediump float; \
  5652. \
  5653. uniform vec4 u_backdrop; \
  5654. uniform int u_subtype; \
  5655. uniform sampler2D u_image; \
  5656. uniform sampler2D u_mask; \
  5657. \
  5658. varying vec2 v_texCoord; \
  5659. \
  5660. void main() { \
  5661. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5662. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5663. if (u_backdrop.a > 0.0) { \
  5664. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5665. u_backdrop.rgb * (1.0 - maskColor.a); \
  5666. } \
  5667. float lum; \
  5668. if (u_subtype == 0) { \
  5669. lum = maskColor.a; \
  5670. } else { \
  5671. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5672. maskColor.b * 0.11; \
  5673. } \
  5674. imageColor.a *= lum; \
  5675. imageColor.rgb *= imageColor.a; \
  5676. gl_FragColor = imageColor; \
  5677. } ';
  5678. var smaskCache = null;
  5679. function initSmaskGL() {
  5680. var canvas, gl;
  5681. generateGL();
  5682. canvas = currentCanvas;
  5683. currentCanvas = null;
  5684. gl = currentGL;
  5685. currentGL = null;
  5686. // setup a GLSL program
  5687. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5688. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5689. var program = createProgram(gl, [
  5690. vertexShader,
  5691. fragmentShader
  5692. ]);
  5693. gl.useProgram(program);
  5694. var cache = {};
  5695. cache.gl = gl;
  5696. cache.canvas = canvas;
  5697. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5698. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5699. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5700. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5701. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5702. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5703. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5704. // provide texture coordinates for the rectangle.
  5705. var texCoordBuffer = gl.createBuffer();
  5706. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5707. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5708. 0.0,
  5709. 0.0,
  5710. 1.0,
  5711. 0.0,
  5712. 0.0,
  5713. 1.0,
  5714. 0.0,
  5715. 1.0,
  5716. 1.0,
  5717. 0.0,
  5718. 1.0,
  5719. 1.0
  5720. ]), gl.STATIC_DRAW);
  5721. gl.enableVertexAttribArray(texCoordLocation);
  5722. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5723. gl.uniform1i(texLayerLocation, 0);
  5724. gl.uniform1i(texMaskLocation, 1);
  5725. smaskCache = cache;
  5726. }
  5727. function composeSMask(layer, mask, properties) {
  5728. var width = layer.width, height = layer.height;
  5729. if (!smaskCache) {
  5730. initSmaskGL();
  5731. }
  5732. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5733. canvas.width = width;
  5734. canvas.height = height;
  5735. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5736. gl.uniform2f(cache.resolutionLocation, width, height);
  5737. if (properties.backdrop) {
  5738. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5739. } else {
  5740. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5741. }
  5742. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5743. // Create a textures
  5744. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5745. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5746. // Create a buffer and put a single clipspace rectangle in
  5747. // it (2 triangles)
  5748. var buffer = gl.createBuffer();
  5749. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5750. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5751. 0,
  5752. 0,
  5753. width,
  5754. 0,
  5755. 0,
  5756. height,
  5757. 0,
  5758. height,
  5759. width,
  5760. 0,
  5761. width,
  5762. height
  5763. ]), gl.STATIC_DRAW);
  5764. gl.enableVertexAttribArray(cache.positionLocation);
  5765. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5766. // draw
  5767. gl.clearColor(0, 0, 0, 0);
  5768. gl.enable(gl.BLEND);
  5769. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5770. gl.clear(gl.COLOR_BUFFER_BIT);
  5771. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5772. gl.flush();
  5773. gl.deleteTexture(texture);
  5774. gl.deleteTexture(maskTexture);
  5775. gl.deleteBuffer(buffer);
  5776. return canvas;
  5777. }
  5778. var figuresVertexShaderCode = '\
  5779. attribute vec2 a_position; \
  5780. attribute vec3 a_color; \
  5781. \
  5782. uniform vec2 u_resolution; \
  5783. uniform vec2 u_scale; \
  5784. uniform vec2 u_offset; \
  5785. \
  5786. varying vec4 v_color; \
  5787. \
  5788. void main() { \
  5789. vec2 position = (a_position + u_offset) * u_scale; \
  5790. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5791. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5792. \
  5793. v_color = vec4(a_color / 255.0, 1.0); \
  5794. } ';
  5795. var figuresFragmentShaderCode = '\
  5796. precision mediump float; \
  5797. \
  5798. varying vec4 v_color; \
  5799. \
  5800. void main() { \
  5801. gl_FragColor = v_color; \
  5802. } ';
  5803. var figuresCache = null;
  5804. function initFiguresGL() {
  5805. var canvas, gl;
  5806. generateGL();
  5807. canvas = currentCanvas;
  5808. currentCanvas = null;
  5809. gl = currentGL;
  5810. currentGL = null;
  5811. // setup a GLSL program
  5812. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5813. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5814. var program = createProgram(gl, [
  5815. vertexShader,
  5816. fragmentShader
  5817. ]);
  5818. gl.useProgram(program);
  5819. var cache = {};
  5820. cache.gl = gl;
  5821. cache.canvas = canvas;
  5822. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5823. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5824. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5825. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5826. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5827. figuresCache = cache;
  5828. }
  5829. function drawFigures(width, height, backgroundColor, figures, context) {
  5830. if (!figuresCache) {
  5831. initFiguresGL();
  5832. }
  5833. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5834. canvas.width = width;
  5835. canvas.height = height;
  5836. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5837. gl.uniform2f(cache.resolutionLocation, width, height);
  5838. // count triangle points
  5839. var count = 0;
  5840. var i, ii, rows;
  5841. for (i = 0, ii = figures.length; i < ii; i++) {
  5842. switch (figures[i].type) {
  5843. case 'lattice':
  5844. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5845. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5846. break;
  5847. case 'triangles':
  5848. count += figures[i].coords.length;
  5849. break;
  5850. }
  5851. }
  5852. // transfer data
  5853. var coords = new Float32Array(count * 2);
  5854. var colors = new Uint8Array(count * 3);
  5855. var coordsMap = context.coords, colorsMap = context.colors;
  5856. var pIndex = 0, cIndex = 0;
  5857. for (i = 0, ii = figures.length; i < ii; i++) {
  5858. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5859. switch (figure.type) {
  5860. case 'lattice':
  5861. var cols = figure.verticesPerRow;
  5862. rows = ps.length / cols | 0;
  5863. for (var row = 1; row < rows; row++) {
  5864. var offset = row * cols + 1;
  5865. for (var col = 1; col < cols; col++, offset++) {
  5866. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5867. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5868. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5869. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5870. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5871. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5872. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5873. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5874. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5875. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5876. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5877. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5878. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5879. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5880. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5881. coords[pIndex + 6] = coords[pIndex + 2];
  5882. coords[pIndex + 7] = coords[pIndex + 3];
  5883. coords[pIndex + 8] = coords[pIndex + 4];
  5884. coords[pIndex + 9] = coords[pIndex + 5];
  5885. coords[pIndex + 10] = coordsMap[ps[offset]];
  5886. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5887. colors[cIndex + 9] = colors[cIndex + 3];
  5888. colors[cIndex + 10] = colors[cIndex + 4];
  5889. colors[cIndex + 11] = colors[cIndex + 5];
  5890. colors[cIndex + 12] = colors[cIndex + 6];
  5891. colors[cIndex + 13] = colors[cIndex + 7];
  5892. colors[cIndex + 14] = colors[cIndex + 8];
  5893. colors[cIndex + 15] = colorsMap[cs[offset]];
  5894. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5895. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5896. pIndex += 12;
  5897. cIndex += 18;
  5898. }
  5899. }
  5900. break;
  5901. case 'triangles':
  5902. for (var j = 0, jj = ps.length; j < jj; j++) {
  5903. coords[pIndex] = coordsMap[ps[j]];
  5904. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5905. colors[cIndex] = colorsMap[cs[j]];
  5906. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5907. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5908. pIndex += 2;
  5909. cIndex += 3;
  5910. }
  5911. break;
  5912. }
  5913. }
  5914. // draw
  5915. if (backgroundColor) {
  5916. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5917. } else {
  5918. gl.clearColor(0, 0, 0, 0);
  5919. }
  5920. gl.clear(gl.COLOR_BUFFER_BIT);
  5921. var coordsBuffer = gl.createBuffer();
  5922. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5923. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5924. gl.enableVertexAttribArray(cache.positionLocation);
  5925. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5926. var colorsBuffer = gl.createBuffer();
  5927. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5928. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5929. gl.enableVertexAttribArray(cache.colorLocation);
  5930. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5931. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5932. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5933. gl.drawArrays(gl.TRIANGLES, 0, count);
  5934. gl.flush();
  5935. gl.deleteBuffer(coordsBuffer);
  5936. gl.deleteBuffer(colorsBuffer);
  5937. return canvas;
  5938. }
  5939. function cleanup() {
  5940. if (smaskCache && smaskCache.canvas) {
  5941. smaskCache.canvas.width = 0;
  5942. smaskCache.canvas.height = 0;
  5943. }
  5944. if (figuresCache && figuresCache.canvas) {
  5945. figuresCache.canvas.width = 0;
  5946. figuresCache.canvas.height = 0;
  5947. }
  5948. smaskCache = null;
  5949. figuresCache = null;
  5950. }
  5951. return {
  5952. get isEnabled() {
  5953. if (getDefaultSetting('disableWebGL')) {
  5954. return false;
  5955. }
  5956. var enabled = false;
  5957. try {
  5958. generateGL();
  5959. enabled = !!currentGL;
  5960. } catch (e) {
  5961. }
  5962. return shadow(this, 'isEnabled', enabled);
  5963. },
  5964. composeSMask: composeSMask,
  5965. drawFigures: drawFigures,
  5966. clear: cleanup
  5967. };
  5968. }();
  5969. exports.WebGLUtils = WebGLUtils;
  5970. }));
  5971. (function (root, factory) {
  5972. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5973. }(this, function (exports, sharedUtil, displayWebGL) {
  5974. var Util = sharedUtil.Util;
  5975. var info = sharedUtil.info;
  5976. var isArray = sharedUtil.isArray;
  5977. var error = sharedUtil.error;
  5978. var WebGLUtils = displayWebGL.WebGLUtils;
  5979. var ShadingIRs = {};
  5980. ShadingIRs.RadialAxial = {
  5981. fromIR: function RadialAxial_fromIR(raw) {
  5982. var type = raw[1];
  5983. var colorStops = raw[2];
  5984. var p0 = raw[3];
  5985. var p1 = raw[4];
  5986. var r0 = raw[5];
  5987. var r1 = raw[6];
  5988. return {
  5989. type: 'Pattern',
  5990. getPattern: function RadialAxial_getPattern(ctx) {
  5991. var grad;
  5992. if (type === 'axial') {
  5993. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5994. } else if (type === 'radial') {
  5995. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5996. }
  5997. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5998. var c = colorStops[i];
  5999. grad.addColorStop(c[0], c[1]);
  6000. }
  6001. return grad;
  6002. }
  6003. };
  6004. }
  6005. };
  6006. var createMeshCanvas = function createMeshCanvasClosure() {
  6007. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  6008. // Very basic Gouraud-shaded triangle rasterization algorithm.
  6009. var coords = context.coords, colors = context.colors;
  6010. var bytes = data.data, rowSize = data.width * 4;
  6011. var tmp;
  6012. if (coords[p1 + 1] > coords[p2 + 1]) {
  6013. tmp = p1;
  6014. p1 = p2;
  6015. p2 = tmp;
  6016. tmp = c1;
  6017. c1 = c2;
  6018. c2 = tmp;
  6019. }
  6020. if (coords[p2 + 1] > coords[p3 + 1]) {
  6021. tmp = p2;
  6022. p2 = p3;
  6023. p3 = tmp;
  6024. tmp = c2;
  6025. c2 = c3;
  6026. c3 = tmp;
  6027. }
  6028. if (coords[p1 + 1] > coords[p2 + 1]) {
  6029. tmp = p1;
  6030. p1 = p2;
  6031. p2 = tmp;
  6032. tmp = c1;
  6033. c1 = c2;
  6034. c2 = tmp;
  6035. }
  6036. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6037. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6038. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6039. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6040. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6041. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6042. if (y1 >= y3) {
  6043. return;
  6044. }
  6045. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  6046. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  6047. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  6048. var minY = Math.round(y1), maxY = Math.round(y3);
  6049. var xa, car, cag, cab;
  6050. var xb, cbr, cbg, cbb;
  6051. var k;
  6052. for (var y = minY; y <= maxY; y++) {
  6053. if (y < y2) {
  6054. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  6055. xa = x1 - (x1 - x2) * k;
  6056. car = c1r - (c1r - c2r) * k;
  6057. cag = c1g - (c1g - c2g) * k;
  6058. cab = c1b - (c1b - c2b) * k;
  6059. } else {
  6060. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  6061. xa = x2 - (x2 - x3) * k;
  6062. car = c2r - (c2r - c3r) * k;
  6063. cag = c2g - (c2g - c3g) * k;
  6064. cab = c2b - (c2b - c3b) * k;
  6065. }
  6066. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  6067. xb = x1 - (x1 - x3) * k;
  6068. cbr = c1r - (c1r - c3r) * k;
  6069. cbg = c1g - (c1g - c3g) * k;
  6070. cbb = c1b - (c1b - c3b) * k;
  6071. var x1_ = Math.round(Math.min(xa, xb));
  6072. var x2_ = Math.round(Math.max(xa, xb));
  6073. var j = rowSize * y + x1_ * 4;
  6074. for (var x = x1_; x <= x2_; x++) {
  6075. k = (xa - x) / (xa - xb);
  6076. k = k < 0 ? 0 : k > 1 ? 1 : k;
  6077. bytes[j++] = car - (car - cbr) * k | 0;
  6078. bytes[j++] = cag - (cag - cbg) * k | 0;
  6079. bytes[j++] = cab - (cab - cbb) * k | 0;
  6080. bytes[j++] = 255;
  6081. }
  6082. }
  6083. }
  6084. function drawFigure(data, figure, context) {
  6085. var ps = figure.coords;
  6086. var cs = figure.colors;
  6087. var i, ii;
  6088. switch (figure.type) {
  6089. case 'lattice':
  6090. var verticesPerRow = figure.verticesPerRow;
  6091. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  6092. var cols = verticesPerRow - 1;
  6093. for (i = 0; i < rows; i++) {
  6094. var q = i * verticesPerRow;
  6095. for (var j = 0; j < cols; j++, q++) {
  6096. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6097. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6098. }
  6099. }
  6100. break;
  6101. case 'triangles':
  6102. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6103. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6104. }
  6105. break;
  6106. default:
  6107. error('illigal figure');
  6108. break;
  6109. }
  6110. }
  6111. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  6112. // we will increase scale on some weird factor to let antialiasing take
  6113. // care of "rough" edges
  6114. var EXPECTED_SCALE = 1.1;
  6115. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6116. var MAX_PATTERN_SIZE = 3000;
  6117. // 10in @ 300dpi shall be enough
  6118. // We need to keep transparent border around our pattern for fill():
  6119. // createPattern with 'no-repeat' will bleed edges across entire area.
  6120. var BORDER_SIZE = 2;
  6121. var offsetX = Math.floor(bounds[0]);
  6122. var offsetY = Math.floor(bounds[1]);
  6123. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  6124. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  6125. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6126. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6127. var scaleX = boundsWidth / width;
  6128. var scaleY = boundsHeight / height;
  6129. var context = {
  6130. coords: coords,
  6131. colors: colors,
  6132. offsetX: -offsetX,
  6133. offsetY: -offsetY,
  6134. scaleX: 1 / scaleX,
  6135. scaleY: 1 / scaleY
  6136. };
  6137. var paddedWidth = width + BORDER_SIZE * 2;
  6138. var paddedHeight = height + BORDER_SIZE * 2;
  6139. var canvas, tmpCanvas, i, ii;
  6140. if (WebGLUtils.isEnabled) {
  6141. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  6142. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  6143. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6144. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  6145. canvas = tmpCanvas.canvas;
  6146. } else {
  6147. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6148. var tmpCtx = tmpCanvas.context;
  6149. var data = tmpCtx.createImageData(width, height);
  6150. if (backgroundColor) {
  6151. var bytes = data.data;
  6152. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  6153. bytes[i] = backgroundColor[0];
  6154. bytes[i + 1] = backgroundColor[1];
  6155. bytes[i + 2] = backgroundColor[2];
  6156. bytes[i + 3] = 255;
  6157. }
  6158. }
  6159. for (i = 0; i < figures.length; i++) {
  6160. drawFigure(data, figures[i], context);
  6161. }
  6162. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6163. canvas = tmpCanvas.canvas;
  6164. }
  6165. return {
  6166. canvas: canvas,
  6167. offsetX: offsetX - BORDER_SIZE * scaleX,
  6168. offsetY: offsetY - BORDER_SIZE * scaleY,
  6169. scaleX: scaleX,
  6170. scaleY: scaleY
  6171. };
  6172. }
  6173. return createMeshCanvas;
  6174. }();
  6175. ShadingIRs.Mesh = {
  6176. fromIR: function Mesh_fromIR(raw) {
  6177. //var type = raw[1];
  6178. var coords = raw[2];
  6179. var colors = raw[3];
  6180. var figures = raw[4];
  6181. var bounds = raw[5];
  6182. var matrix = raw[6];
  6183. //var bbox = raw[7];
  6184. var background = raw[8];
  6185. return {
  6186. type: 'Pattern',
  6187. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  6188. var scale;
  6189. if (shadingFill) {
  6190. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6191. } else {
  6192. // Obtain scale from matrix and current transformation matrix.
  6193. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6194. if (matrix) {
  6195. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  6196. scale = [
  6197. scale[0] * matrixScale[0],
  6198. scale[1] * matrixScale[1]
  6199. ];
  6200. }
  6201. }
  6202. // Rasterizing on the main thread since sending/queue large canvases
  6203. // might cause OOM.
  6204. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  6205. if (!shadingFill) {
  6206. ctx.setTransform.apply(ctx, owner.baseTransform);
  6207. if (matrix) {
  6208. ctx.transform.apply(ctx, matrix);
  6209. }
  6210. }
  6211. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6212. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6213. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  6214. }
  6215. };
  6216. }
  6217. };
  6218. ShadingIRs.Dummy = {
  6219. fromIR: function Dummy_fromIR() {
  6220. return {
  6221. type: 'Pattern',
  6222. getPattern: function Dummy_fromIR_getPattern() {
  6223. return 'hotpink';
  6224. }
  6225. };
  6226. }
  6227. };
  6228. function getShadingPatternFromIR(raw) {
  6229. var shadingIR = ShadingIRs[raw[0]];
  6230. if (!shadingIR) {
  6231. error('Unknown IR type: ' + raw[0]);
  6232. }
  6233. return shadingIR.fromIR(raw);
  6234. }
  6235. var TilingPattern = function TilingPatternClosure() {
  6236. var PaintType = {
  6237. COLORED: 1,
  6238. UNCOLORED: 2
  6239. };
  6240. var MAX_PATTERN_SIZE = 3000;
  6241. // 10in @ 300dpi shall be enough
  6242. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6243. this.operatorList = IR[2];
  6244. this.matrix = IR[3] || [
  6245. 1,
  6246. 0,
  6247. 0,
  6248. 1,
  6249. 0,
  6250. 0
  6251. ];
  6252. this.bbox = IR[4];
  6253. this.xstep = IR[5];
  6254. this.ystep = IR[6];
  6255. this.paintType = IR[7];
  6256. this.tilingType = IR[8];
  6257. this.color = color;
  6258. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6259. this.baseTransform = baseTransform;
  6260. this.type = 'Pattern';
  6261. this.ctx = ctx;
  6262. }
  6263. TilingPattern.prototype = {
  6264. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6265. var operatorList = this.operatorList;
  6266. var bbox = this.bbox;
  6267. var xstep = this.xstep;
  6268. var ystep = this.ystep;
  6269. var paintType = this.paintType;
  6270. var tilingType = this.tilingType;
  6271. var color = this.color;
  6272. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6273. info('TilingType: ' + tilingType);
  6274. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6275. var topLeft = [
  6276. x0,
  6277. y0
  6278. ];
  6279. // we want the canvas to be as large as the step size
  6280. var botRight = [
  6281. x0 + xstep,
  6282. y0 + ystep
  6283. ];
  6284. var width = botRight[0] - topLeft[0];
  6285. var height = botRight[1] - topLeft[1];
  6286. // Obtain scale from matrix and current transformation matrix.
  6287. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6288. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6289. var combinedScale = [
  6290. matrixScale[0] * curMatrixScale[0],
  6291. matrixScale[1] * curMatrixScale[1]
  6292. ];
  6293. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6294. // Use width and height values that are as close as possible to the end
  6295. // result when the pattern is used. Too low value makes the pattern look
  6296. // blurry. Too large value makes it look too crispy.
  6297. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  6298. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  6299. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  6300. var tmpCtx = tmpCanvas.context;
  6301. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6302. graphics.groupLevel = owner.groupLevel;
  6303. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6304. this.setScale(width, height, xstep, ystep);
  6305. this.transformToScale(graphics);
  6306. // transform coordinates to pattern space
  6307. var tmpTranslate = [
  6308. 1,
  6309. 0,
  6310. 0,
  6311. 1,
  6312. -topLeft[0],
  6313. -topLeft[1]
  6314. ];
  6315. graphics.transform.apply(graphics, tmpTranslate);
  6316. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6317. graphics.executeOperatorList(operatorList);
  6318. return tmpCanvas.canvas;
  6319. },
  6320. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6321. this.scale = [
  6322. width / xstep,
  6323. height / ystep
  6324. ];
  6325. },
  6326. transformToScale: function TilingPattern_transformToScale(graphics) {
  6327. var scale = this.scale;
  6328. var tmpScale = [
  6329. scale[0],
  6330. 0,
  6331. 0,
  6332. scale[1],
  6333. 0,
  6334. 0
  6335. ];
  6336. graphics.transform.apply(graphics, tmpScale);
  6337. },
  6338. scaleToContext: function TilingPattern_scaleToContext() {
  6339. var scale = this.scale;
  6340. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6341. },
  6342. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6343. if (bbox && isArray(bbox) && bbox.length === 4) {
  6344. var bboxWidth = x1 - x0;
  6345. var bboxHeight = y1 - y0;
  6346. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6347. graphics.clip();
  6348. graphics.endPath();
  6349. }
  6350. },
  6351. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  6352. switch (paintType) {
  6353. case PaintType.COLORED:
  6354. var ctx = this.ctx;
  6355. context.fillStyle = ctx.fillStyle;
  6356. context.strokeStyle = ctx.strokeStyle;
  6357. break;
  6358. case PaintType.UNCOLORED:
  6359. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6360. context.fillStyle = cssColor;
  6361. context.strokeStyle = cssColor;
  6362. break;
  6363. default:
  6364. error('Unsupported paint type: ' + paintType);
  6365. }
  6366. },
  6367. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6368. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6369. ctx = this.ctx;
  6370. ctx.setTransform.apply(ctx, this.baseTransform);
  6371. ctx.transform.apply(ctx, this.matrix);
  6372. this.scaleToContext();
  6373. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6374. }
  6375. };
  6376. return TilingPattern;
  6377. }();
  6378. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6379. exports.TilingPattern = TilingPattern;
  6380. }));
  6381. (function (root, factory) {
  6382. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  6383. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  6384. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6385. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6386. var ImageKind = sharedUtil.ImageKind;
  6387. var OPS = sharedUtil.OPS;
  6388. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6389. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6390. var Util = sharedUtil.Util;
  6391. var assert = sharedUtil.assert;
  6392. var info = sharedUtil.info;
  6393. var isNum = sharedUtil.isNum;
  6394. var isArray = sharedUtil.isArray;
  6395. var isLittleEndian = sharedUtil.isLittleEndian;
  6396. var error = sharedUtil.error;
  6397. var shadow = sharedUtil.shadow;
  6398. var warn = sharedUtil.warn;
  6399. var TilingPattern = displayPatternHelper.TilingPattern;
  6400. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6401. var WebGLUtils = displayWebGL.WebGLUtils;
  6402. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6403. // <canvas> contexts store most of the state we need natively.
  6404. // However, PDF needs a bit more state, which we store here.
  6405. // Minimal font size that would be used during canvas fillText operations.
  6406. var MIN_FONT_SIZE = 16;
  6407. // Maximum font size that would be used during canvas fillText operations.
  6408. var MAX_FONT_SIZE = 100;
  6409. var MAX_GROUP_SIZE = 4096;
  6410. // Heuristic value used when enforcing minimum line widths.
  6411. var MIN_WIDTH_FACTOR = 0.65;
  6412. var COMPILE_TYPE3_GLYPHS = true;
  6413. var MAX_SIZE_TO_COMPILE = 1000;
  6414. var FULL_CHUNK_HEIGHT = 16;
  6415. var HasCanvasTypedArraysCached = {
  6416. get value() {
  6417. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6418. }
  6419. };
  6420. var IsLittleEndianCached = {
  6421. get value() {
  6422. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6423. }
  6424. };
  6425. function createScratchCanvas(width, height) {
  6426. var canvas = document.createElement('canvas');
  6427. canvas.width = width;
  6428. canvas.height = height;
  6429. return canvas;
  6430. }
  6431. function addContextCurrentTransform(ctx) {
  6432. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6433. if (!ctx.mozCurrentTransform) {
  6434. ctx._originalSave = ctx.save;
  6435. ctx._originalRestore = ctx.restore;
  6436. ctx._originalRotate = ctx.rotate;
  6437. ctx._originalScale = ctx.scale;
  6438. ctx._originalTranslate = ctx.translate;
  6439. ctx._originalTransform = ctx.transform;
  6440. ctx._originalSetTransform = ctx.setTransform;
  6441. ctx._transformMatrix = ctx._transformMatrix || [
  6442. 1,
  6443. 0,
  6444. 0,
  6445. 1,
  6446. 0,
  6447. 0
  6448. ];
  6449. ctx._transformStack = [];
  6450. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6451. get: function getCurrentTransform() {
  6452. return this._transformMatrix;
  6453. }
  6454. });
  6455. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6456. get: function getCurrentTransformInverse() {
  6457. // Calculation done using WolframAlpha:
  6458. // http://www.wolframalpha.com/input/?
  6459. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6460. var m = this._transformMatrix;
  6461. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6462. var ad_bc = a * d - b * c;
  6463. var bc_ad = b * c - a * d;
  6464. return [
  6465. d / ad_bc,
  6466. b / bc_ad,
  6467. c / bc_ad,
  6468. a / ad_bc,
  6469. (d * e - c * f) / bc_ad,
  6470. (b * e - a * f) / ad_bc
  6471. ];
  6472. }
  6473. });
  6474. ctx.save = function ctxSave() {
  6475. var old = this._transformMatrix;
  6476. this._transformStack.push(old);
  6477. this._transformMatrix = old.slice(0, 6);
  6478. this._originalSave();
  6479. };
  6480. ctx.restore = function ctxRestore() {
  6481. var prev = this._transformStack.pop();
  6482. if (prev) {
  6483. this._transformMatrix = prev;
  6484. this._originalRestore();
  6485. }
  6486. };
  6487. ctx.translate = function ctxTranslate(x, y) {
  6488. var m = this._transformMatrix;
  6489. m[4] = m[0] * x + m[2] * y + m[4];
  6490. m[5] = m[1] * x + m[3] * y + m[5];
  6491. this._originalTranslate(x, y);
  6492. };
  6493. ctx.scale = function ctxScale(x, y) {
  6494. var m = this._transformMatrix;
  6495. m[0] = m[0] * x;
  6496. m[1] = m[1] * x;
  6497. m[2] = m[2] * y;
  6498. m[3] = m[3] * y;
  6499. this._originalScale(x, y);
  6500. };
  6501. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6502. var m = this._transformMatrix;
  6503. this._transformMatrix = [
  6504. m[0] * a + m[2] * b,
  6505. m[1] * a + m[3] * b,
  6506. m[0] * c + m[2] * d,
  6507. m[1] * c + m[3] * d,
  6508. m[0] * e + m[2] * f + m[4],
  6509. m[1] * e + m[3] * f + m[5]
  6510. ];
  6511. ctx._originalTransform(a, b, c, d, e, f);
  6512. };
  6513. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6514. this._transformMatrix = [
  6515. a,
  6516. b,
  6517. c,
  6518. d,
  6519. e,
  6520. f
  6521. ];
  6522. ctx._originalSetTransform(a, b, c, d, e, f);
  6523. };
  6524. ctx.rotate = function ctxRotate(angle) {
  6525. var cosValue = Math.cos(angle);
  6526. var sinValue = Math.sin(angle);
  6527. var m = this._transformMatrix;
  6528. this._transformMatrix = [
  6529. m[0] * cosValue + m[2] * sinValue,
  6530. m[1] * cosValue + m[3] * sinValue,
  6531. m[0] * -sinValue + m[2] * cosValue,
  6532. m[1] * -sinValue + m[3] * cosValue,
  6533. m[4],
  6534. m[5]
  6535. ];
  6536. this._originalRotate(angle);
  6537. };
  6538. }
  6539. }
  6540. var CachedCanvases = function CachedCanvasesClosure() {
  6541. function CachedCanvases() {
  6542. this.cache = Object.create(null);
  6543. }
  6544. CachedCanvases.prototype = {
  6545. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  6546. var canvasEntry;
  6547. if (this.cache[id] !== undefined) {
  6548. canvasEntry = this.cache[id];
  6549. canvasEntry.canvas.width = width;
  6550. canvasEntry.canvas.height = height;
  6551. // reset canvas transform for emulated mozCurrentTransform, if needed
  6552. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6553. } else {
  6554. var canvas = createScratchCanvas(width, height);
  6555. var ctx = canvas.getContext('2d');
  6556. if (trackTransform) {
  6557. addContextCurrentTransform(ctx);
  6558. }
  6559. this.cache[id] = canvasEntry = {
  6560. canvas: canvas,
  6561. context: ctx
  6562. };
  6563. }
  6564. return canvasEntry;
  6565. },
  6566. clear: function () {
  6567. for (var id in this.cache) {
  6568. var canvasEntry = this.cache[id];
  6569. // Zeroing the width and height causes Firefox to release graphics
  6570. // resources immediately, which can greatly reduce memory consumption.
  6571. canvasEntry.canvas.width = 0;
  6572. canvasEntry.canvas.height = 0;
  6573. delete this.cache[id];
  6574. }
  6575. }
  6576. };
  6577. return CachedCanvases;
  6578. }();
  6579. function compileType3Glyph(imgData) {
  6580. var POINT_TO_PROCESS_LIMIT = 1000;
  6581. var width = imgData.width, height = imgData.height;
  6582. var i, j, j0, width1 = width + 1;
  6583. var points = new Uint8Array(width1 * (height + 1));
  6584. var POINT_TYPES = new Uint8Array([
  6585. 0,
  6586. 2,
  6587. 4,
  6588. 0,
  6589. 1,
  6590. 0,
  6591. 5,
  6592. 4,
  6593. 8,
  6594. 10,
  6595. 0,
  6596. 8,
  6597. 0,
  6598. 2,
  6599. 1,
  6600. 0
  6601. ]);
  6602. // decodes bit-packed mask data
  6603. var lineSize = width + 7 & ~7, data0 = imgData.data;
  6604. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6605. for (i = 0, ii = data0.length; i < ii; i++) {
  6606. var mask = 128, elem = data0[i];
  6607. while (mask > 0) {
  6608. data[pos++] = elem & mask ? 0 : 255;
  6609. mask >>= 1;
  6610. }
  6611. }
  6612. // finding iteresting points: every point is located between mask pixels,
  6613. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6614. // will have flags assigned based on neighboring mask pixels:
  6615. // 4 | 8
  6616. // --P--
  6617. // 2 | 1
  6618. // We are interested only in points with the flags:
  6619. // - outside corners: 1, 2, 4, 8;
  6620. // - inside corners: 7, 11, 13, 14;
  6621. // - and, intersections: 5, 10.
  6622. var count = 0;
  6623. pos = 0;
  6624. if (data[pos] !== 0) {
  6625. points[0] = 1;
  6626. ++count;
  6627. }
  6628. for (j = 1; j < width; j++) {
  6629. if (data[pos] !== data[pos + 1]) {
  6630. points[j] = data[pos] ? 2 : 1;
  6631. ++count;
  6632. }
  6633. pos++;
  6634. }
  6635. if (data[pos] !== 0) {
  6636. points[j] = 2;
  6637. ++count;
  6638. }
  6639. for (i = 1; i < height; i++) {
  6640. pos = i * lineSize;
  6641. j0 = i * width1;
  6642. if (data[pos - lineSize] !== data[pos]) {
  6643. points[j0] = data[pos] ? 1 : 8;
  6644. ++count;
  6645. }
  6646. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6647. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6648. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6649. for (j = 1; j < width; j++) {
  6650. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6651. if (POINT_TYPES[sum]) {
  6652. points[j0 + j] = POINT_TYPES[sum];
  6653. ++count;
  6654. }
  6655. pos++;
  6656. }
  6657. if (data[pos - lineSize] !== data[pos]) {
  6658. points[j0 + j] = data[pos] ? 2 : 4;
  6659. ++count;
  6660. }
  6661. if (count > POINT_TO_PROCESS_LIMIT) {
  6662. return null;
  6663. }
  6664. }
  6665. pos = lineSize * (height - 1);
  6666. j0 = i * width1;
  6667. if (data[pos] !== 0) {
  6668. points[j0] = 8;
  6669. ++count;
  6670. }
  6671. for (j = 1; j < width; j++) {
  6672. if (data[pos] !== data[pos + 1]) {
  6673. points[j0 + j] = data[pos] ? 4 : 8;
  6674. ++count;
  6675. }
  6676. pos++;
  6677. }
  6678. if (data[pos] !== 0) {
  6679. points[j0 + j] = 4;
  6680. ++count;
  6681. }
  6682. if (count > POINT_TO_PROCESS_LIMIT) {
  6683. return null;
  6684. }
  6685. // building outlines
  6686. var steps = new Int32Array([
  6687. 0,
  6688. width1,
  6689. -1,
  6690. 0,
  6691. -width1,
  6692. 0,
  6693. 0,
  6694. 0,
  6695. 1
  6696. ]);
  6697. var outlines = [];
  6698. for (i = 0; count && i <= height; i++) {
  6699. var p = i * width1;
  6700. var end = p + width;
  6701. while (p < end && !points[p]) {
  6702. p++;
  6703. }
  6704. if (p === end) {
  6705. continue;
  6706. }
  6707. var coords = [
  6708. p % width1,
  6709. i
  6710. ];
  6711. var type = points[p], p0 = p, pp;
  6712. do {
  6713. var step = steps[type];
  6714. do {
  6715. p += step;
  6716. } while (!points[p]);
  6717. pp = points[p];
  6718. if (pp !== 5 && pp !== 10) {
  6719. // set new direction
  6720. type = pp;
  6721. // delete mark
  6722. points[p] = 0;
  6723. } else {
  6724. // type is 5 or 10, ie, a crossing
  6725. // set new direction
  6726. type = pp & 0x33 * type >> 4;
  6727. // set new type for "future hit"
  6728. points[p] &= type >> 2 | type << 2;
  6729. }
  6730. coords.push(p % width1);
  6731. coords.push(p / width1 | 0);
  6732. --count;
  6733. } while (p0 !== p);
  6734. outlines.push(coords);
  6735. --i;
  6736. }
  6737. var drawOutline = function (c) {
  6738. c.save();
  6739. // the path shall be painted in [0..1]x[0..1] space
  6740. c.scale(1 / width, -1 / height);
  6741. c.translate(0, -height);
  6742. c.beginPath();
  6743. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6744. var o = outlines[i];
  6745. c.moveTo(o[0], o[1]);
  6746. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6747. c.lineTo(o[j], o[j + 1]);
  6748. }
  6749. }
  6750. c.fill();
  6751. c.beginPath();
  6752. c.restore();
  6753. };
  6754. return drawOutline;
  6755. }
  6756. var CanvasExtraState = function CanvasExtraStateClosure() {
  6757. function CanvasExtraState(old) {
  6758. // Are soft masks and alpha values shapes or opacities?
  6759. this.alphaIsShape = false;
  6760. this.fontSize = 0;
  6761. this.fontSizeScale = 1;
  6762. this.textMatrix = IDENTITY_MATRIX;
  6763. this.textMatrixScale = 1;
  6764. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6765. this.leading = 0;
  6766. // Current point (in user coordinates)
  6767. this.x = 0;
  6768. this.y = 0;
  6769. // Start of text line (in text coordinates)
  6770. this.lineX = 0;
  6771. this.lineY = 0;
  6772. // Character and word spacing
  6773. this.charSpacing = 0;
  6774. this.wordSpacing = 0;
  6775. this.textHScale = 1;
  6776. this.textRenderingMode = TextRenderingMode.FILL;
  6777. this.textRise = 0;
  6778. // Default fore and background colors
  6779. this.fillColor = '#000000';
  6780. this.strokeColor = '#000000';
  6781. this.patternFill = false;
  6782. // Note: fill alpha applies to all non-stroking operations
  6783. this.fillAlpha = 1;
  6784. this.strokeAlpha = 1;
  6785. this.lineWidth = 1;
  6786. this.activeSMask = null;
  6787. this.resumeSMaskCtx = null;
  6788. // nonclonable field (see the save method below)
  6789. this.old = old;
  6790. }
  6791. CanvasExtraState.prototype = {
  6792. clone: function CanvasExtraState_clone() {
  6793. return Object.create(this);
  6794. },
  6795. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6796. this.x = x;
  6797. this.y = y;
  6798. }
  6799. };
  6800. return CanvasExtraState;
  6801. }();
  6802. var CanvasGraphics = function CanvasGraphicsClosure() {
  6803. // Defines the time the executeOperatorList is going to be executing
  6804. // before it stops and shedules a continue of execution.
  6805. var EXECUTION_TIME = 15;
  6806. // Defines the number of steps before checking the execution time
  6807. var EXECUTION_STEPS = 10;
  6808. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6809. this.ctx = canvasCtx;
  6810. this.current = new CanvasExtraState();
  6811. this.stateStack = [];
  6812. this.pendingClip = null;
  6813. this.pendingEOFill = false;
  6814. this.res = null;
  6815. this.xobjs = null;
  6816. this.commonObjs = commonObjs;
  6817. this.objs = objs;
  6818. this.imageLayer = imageLayer;
  6819. this.groupStack = [];
  6820. this.processingType3 = null;
  6821. // Patterns are painted relative to the initial page/form transform, see pdf
  6822. // spec 8.7.2 NOTE 1.
  6823. this.baseTransform = null;
  6824. this.baseTransformStack = [];
  6825. this.groupLevel = 0;
  6826. this.smaskStack = [];
  6827. this.smaskCounter = 0;
  6828. this.tempSMask = null;
  6829. this.cachedCanvases = new CachedCanvases();
  6830. if (canvasCtx) {
  6831. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6832. // the transformation must already be set in canvasCtx._transformMatrix.
  6833. addContextCurrentTransform(canvasCtx);
  6834. }
  6835. this.cachedGetSinglePixelWidth = null;
  6836. }
  6837. function putBinaryImageData(ctx, imgData) {
  6838. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6839. ctx.putImageData(imgData, 0, 0);
  6840. return;
  6841. }
  6842. // Put the image data to the canvas in chunks, rather than putting the
  6843. // whole image at once. This saves JS memory, because the ImageData object
  6844. // is smaller. It also possibly saves C++ memory within the implementation
  6845. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6846. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6847. // because too many putImageData() calls will slow things down.
  6848. //
  6849. // Note: as written, if the last chunk is partial, the putImageData() call
  6850. // will (conceptually) put pixels past the bounds of the canvas. But
  6851. // that's ok; any such pixels are ignored.
  6852. var height = imgData.height, width = imgData.width;
  6853. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6854. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6855. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6856. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6857. var srcPos = 0, destPos;
  6858. var src = imgData.data;
  6859. var dest = chunkImgData.data;
  6860. var i, j, thisChunkHeight, elemsInThisChunk;
  6861. // There are multiple forms in which the pixel data can be passed, and
  6862. // imgData.kind tells us which one this is.
  6863. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6864. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6865. var srcLength = src.byteLength;
  6866. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6867. var dest32DataLength = dest32.length;
  6868. var fullSrcDiff = width + 7 >> 3;
  6869. var white = 0xFFFFFFFF;
  6870. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6871. for (i = 0; i < totalChunks; i++) {
  6872. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6873. destPos = 0;
  6874. for (j = 0; j < thisChunkHeight; j++) {
  6875. var srcDiff = srcLength - srcPos;
  6876. var k = 0;
  6877. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6878. var kEndUnrolled = kEnd & ~7;
  6879. var mask = 0;
  6880. var srcByte = 0;
  6881. for (; k < kEndUnrolled; k += 8) {
  6882. srcByte = src[srcPos++];
  6883. dest32[destPos++] = srcByte & 128 ? white : black;
  6884. dest32[destPos++] = srcByte & 64 ? white : black;
  6885. dest32[destPos++] = srcByte & 32 ? white : black;
  6886. dest32[destPos++] = srcByte & 16 ? white : black;
  6887. dest32[destPos++] = srcByte & 8 ? white : black;
  6888. dest32[destPos++] = srcByte & 4 ? white : black;
  6889. dest32[destPos++] = srcByte & 2 ? white : black;
  6890. dest32[destPos++] = srcByte & 1 ? white : black;
  6891. }
  6892. for (; k < kEnd; k++) {
  6893. if (mask === 0) {
  6894. srcByte = src[srcPos++];
  6895. mask = 128;
  6896. }
  6897. dest32[destPos++] = srcByte & mask ? white : black;
  6898. mask >>= 1;
  6899. }
  6900. }
  6901. // We ran out of input. Make all remaining pixels transparent.
  6902. while (destPos < dest32DataLength) {
  6903. dest32[destPos++] = 0;
  6904. }
  6905. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6906. }
  6907. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6908. // RGBA, 32-bits per pixel.
  6909. j = 0;
  6910. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6911. for (i = 0; i < fullChunks; i++) {
  6912. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6913. srcPos += elemsInThisChunk;
  6914. ctx.putImageData(chunkImgData, 0, j);
  6915. j += FULL_CHUNK_HEIGHT;
  6916. }
  6917. if (i < totalChunks) {
  6918. elemsInThisChunk = width * partialChunkHeight * 4;
  6919. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6920. ctx.putImageData(chunkImgData, 0, j);
  6921. }
  6922. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6923. // RGB, 24-bits per pixel.
  6924. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6925. elemsInThisChunk = width * thisChunkHeight;
  6926. for (i = 0; i < totalChunks; i++) {
  6927. if (i >= fullChunks) {
  6928. thisChunkHeight = partialChunkHeight;
  6929. elemsInThisChunk = width * thisChunkHeight;
  6930. }
  6931. destPos = 0;
  6932. for (j = elemsInThisChunk; j--;) {
  6933. dest[destPos++] = src[srcPos++];
  6934. dest[destPos++] = src[srcPos++];
  6935. dest[destPos++] = src[srcPos++];
  6936. dest[destPos++] = 255;
  6937. }
  6938. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6939. }
  6940. } else {
  6941. error('bad image kind: ' + imgData.kind);
  6942. }
  6943. }
  6944. function putBinaryImageMask(ctx, imgData) {
  6945. var height = imgData.height, width = imgData.width;
  6946. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6947. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6948. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6949. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6950. var srcPos = 0;
  6951. var src = imgData.data;
  6952. var dest = chunkImgData.data;
  6953. for (var i = 0; i < totalChunks; i++) {
  6954. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6955. // Expand the mask so it can be used by the canvas. Any required
  6956. // inversion has already been handled.
  6957. var destPos = 3;
  6958. // alpha component offset
  6959. for (var j = 0; j < thisChunkHeight; j++) {
  6960. var mask = 0;
  6961. for (var k = 0; k < width; k++) {
  6962. if (!mask) {
  6963. var elem = src[srcPos++];
  6964. mask = 128;
  6965. }
  6966. dest[destPos] = elem & mask ? 0 : 255;
  6967. destPos += 4;
  6968. mask >>= 1;
  6969. }
  6970. }
  6971. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6972. }
  6973. }
  6974. function copyCtxState(sourceCtx, destCtx) {
  6975. var properties = [
  6976. 'strokeStyle',
  6977. 'fillStyle',
  6978. 'fillRule',
  6979. 'globalAlpha',
  6980. 'lineWidth',
  6981. 'lineCap',
  6982. 'lineJoin',
  6983. 'miterLimit',
  6984. 'globalCompositeOperation',
  6985. 'font'
  6986. ];
  6987. for (var i = 0, ii = properties.length; i < ii; i++) {
  6988. var property = properties[i];
  6989. if (sourceCtx[property] !== undefined) {
  6990. destCtx[property] = sourceCtx[property];
  6991. }
  6992. }
  6993. if (sourceCtx.setLineDash !== undefined) {
  6994. destCtx.setLineDash(sourceCtx.getLineDash());
  6995. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6996. }
  6997. }
  6998. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6999. var length = bytes.length;
  7000. for (var i = 3; i < length; i += 4) {
  7001. var alpha = bytes[i];
  7002. if (alpha === 0) {
  7003. bytes[i - 3] = r0;
  7004. bytes[i - 2] = g0;
  7005. bytes[i - 1] = b0;
  7006. } else if (alpha < 255) {
  7007. var alpha_ = 255 - alpha;
  7008. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  7009. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  7010. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  7011. }
  7012. }
  7013. }
  7014. function composeSMaskAlpha(maskData, layerData, transferMap) {
  7015. var length = maskData.length;
  7016. var scale = 1 / 255;
  7017. for (var i = 3; i < length; i += 4) {
  7018. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  7019. layerData[i] = layerData[i] * alpha * scale | 0;
  7020. }
  7021. }
  7022. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  7023. var length = maskData.length;
  7024. for (var i = 3; i < length; i += 4) {
  7025. var y = maskData[i - 3] * 77 + // * 0.3 / 255 * 0x10000
  7026. maskData[i - 2] * 152 + // * 0.59 ....
  7027. maskData[i - 1] * 28;
  7028. // * 0.11 ....
  7029. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  7030. }
  7031. }
  7032. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  7033. var hasBackdrop = !!backdrop;
  7034. var r0 = hasBackdrop ? backdrop[0] : 0;
  7035. var g0 = hasBackdrop ? backdrop[1] : 0;
  7036. var b0 = hasBackdrop ? backdrop[2] : 0;
  7037. var composeFn;
  7038. if (subtype === 'Luminosity') {
  7039. composeFn = composeSMaskLuminosity;
  7040. } else {
  7041. composeFn = composeSMaskAlpha;
  7042. }
  7043. // processing image in chunks to save memory
  7044. var PIXELS_TO_PROCESS = 1048576;
  7045. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  7046. for (var row = 0; row < height; row += chunkSize) {
  7047. var chunkHeight = Math.min(chunkSize, height - row);
  7048. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  7049. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  7050. if (hasBackdrop) {
  7051. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  7052. }
  7053. composeFn(maskData.data, layerData.data, transferMap);
  7054. maskCtx.putImageData(layerData, 0, row);
  7055. }
  7056. }
  7057. function composeSMask(ctx, smask, layerCtx) {
  7058. var mask = smask.canvas;
  7059. var maskCtx = smask.context;
  7060. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  7061. var backdrop = smask.backdrop || null;
  7062. if (!smask.transferMap && WebGLUtils.isEnabled) {
  7063. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  7064. subtype: smask.subtype,
  7065. backdrop: backdrop
  7066. });
  7067. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7068. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  7069. return;
  7070. }
  7071. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  7072. ctx.drawImage(mask, 0, 0);
  7073. }
  7074. var LINE_CAP_STYLES = [
  7075. 'butt',
  7076. 'round',
  7077. 'square'
  7078. ];
  7079. var LINE_JOIN_STYLES = [
  7080. 'miter',
  7081. 'round',
  7082. 'bevel'
  7083. ];
  7084. var NORMAL_CLIP = {};
  7085. var EO_CLIP = {};
  7086. CanvasGraphics.prototype = {
  7087. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  7088. // For pdfs that use blend modes we have to clear the canvas else certain
  7089. // blend modes can look wrong since we'd be blending with a white
  7090. // backdrop. The problem with a transparent backdrop though is we then
  7091. // don't get sub pixel anti aliasing on text, creating temporary
  7092. // transparent canvas when we have blend modes.
  7093. var width = this.ctx.canvas.width;
  7094. var height = this.ctx.canvas.height;
  7095. this.ctx.save();
  7096. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  7097. this.ctx.fillRect(0, 0, width, height);
  7098. this.ctx.restore();
  7099. if (transparency) {
  7100. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  7101. this.compositeCtx = this.ctx;
  7102. this.transparentCanvas = transparentCanvas.canvas;
  7103. this.ctx = transparentCanvas.context;
  7104. this.ctx.save();
  7105. // The transform can be applied before rendering, transferring it to
  7106. // the new canvas.
  7107. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  7108. }
  7109. this.ctx.save();
  7110. if (transform) {
  7111. this.ctx.transform.apply(this.ctx, transform);
  7112. }
  7113. this.ctx.transform.apply(this.ctx, viewport.transform);
  7114. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  7115. if (this.imageLayer) {
  7116. this.imageLayer.beginLayout();
  7117. }
  7118. },
  7119. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7120. var argsArray = operatorList.argsArray;
  7121. var fnArray = operatorList.fnArray;
  7122. var i = executionStartIdx || 0;
  7123. var argsArrayLen = argsArray.length;
  7124. // Sometimes the OperatorList to execute is empty.
  7125. if (argsArrayLen === i) {
  7126. return i;
  7127. }
  7128. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  7129. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7130. var steps = 0;
  7131. var commonObjs = this.commonObjs;
  7132. var objs = this.objs;
  7133. var fnId;
  7134. while (true) {
  7135. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7136. stepper.breakIt(i, continueCallback);
  7137. return i;
  7138. }
  7139. fnId = fnArray[i];
  7140. if (fnId !== OPS.dependency) {
  7141. this[fnId].apply(this, argsArray[i]);
  7142. } else {
  7143. var deps = argsArray[i];
  7144. for (var n = 0, nn = deps.length; n < nn; n++) {
  7145. var depObjId = deps[n];
  7146. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  7147. var objsPool = common ? commonObjs : objs;
  7148. // If the promise isn't resolved yet, add the continueCallback
  7149. // to the promise and bail out.
  7150. if (!objsPool.isResolved(depObjId)) {
  7151. objsPool.get(depObjId, continueCallback);
  7152. return i;
  7153. }
  7154. }
  7155. }
  7156. i++;
  7157. // If the entire operatorList was executed, stop as were done.
  7158. if (i === argsArrayLen) {
  7159. return i;
  7160. }
  7161. // If the execution took longer then a certain amount of time and
  7162. // `continueCallback` is specified, interrupt the execution.
  7163. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7164. if (Date.now() > endTime) {
  7165. continueCallback();
  7166. return i;
  7167. }
  7168. steps = 0;
  7169. }
  7170. }
  7171. },
  7172. // If the operatorList isn't executed completely yet OR the execution
  7173. // time was short enough, do another execution round.
  7174. endDrawing: function CanvasGraphics_endDrawing() {
  7175. // Finishing all opened operations such as SMask group painting.
  7176. if (this.current.activeSMask !== null) {
  7177. this.endSMaskGroup();
  7178. }
  7179. this.ctx.restore();
  7180. if (this.transparentCanvas) {
  7181. this.ctx = this.compositeCtx;
  7182. this.ctx.save();
  7183. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7184. // Avoid apply transform twice
  7185. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7186. this.ctx.restore();
  7187. this.transparentCanvas = null;
  7188. }
  7189. this.cachedCanvases.clear();
  7190. WebGLUtils.clear();
  7191. if (this.imageLayer) {
  7192. this.imageLayer.endLayout();
  7193. }
  7194. },
  7195. // Graphics state
  7196. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  7197. this.current.lineWidth = width;
  7198. this.ctx.lineWidth = width;
  7199. },
  7200. setLineCap: function CanvasGraphics_setLineCap(style) {
  7201. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7202. },
  7203. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  7204. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7205. },
  7206. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  7207. this.ctx.miterLimit = limit;
  7208. },
  7209. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  7210. var ctx = this.ctx;
  7211. if (ctx.setLineDash !== undefined) {
  7212. ctx.setLineDash(dashArray);
  7213. ctx.lineDashOffset = dashPhase;
  7214. }
  7215. },
  7216. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  7217. },
  7218. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  7219. },
  7220. setGState: function CanvasGraphics_setGState(states) {
  7221. for (var i = 0, ii = states.length; i < ii; i++) {
  7222. var state = states[i];
  7223. var key = state[0];
  7224. var value = state[1];
  7225. switch (key) {
  7226. case 'LW':
  7227. this.setLineWidth(value);
  7228. break;
  7229. case 'LC':
  7230. this.setLineCap(value);
  7231. break;
  7232. case 'LJ':
  7233. this.setLineJoin(value);
  7234. break;
  7235. case 'ML':
  7236. this.setMiterLimit(value);
  7237. break;
  7238. case 'D':
  7239. this.setDash(value[0], value[1]);
  7240. break;
  7241. case 'RI':
  7242. this.setRenderingIntent(value);
  7243. break;
  7244. case 'FL':
  7245. this.setFlatness(value);
  7246. break;
  7247. case 'Font':
  7248. this.setFont(value[0], value[1]);
  7249. break;
  7250. case 'CA':
  7251. this.current.strokeAlpha = state[1];
  7252. break;
  7253. case 'ca':
  7254. this.current.fillAlpha = state[1];
  7255. this.ctx.globalAlpha = state[1];
  7256. break;
  7257. case 'BM':
  7258. if (value && value.name && value.name !== 'Normal') {
  7259. var mode = value.name.replace(/([A-Z])/g, function (c) {
  7260. return '-' + c.toLowerCase();
  7261. }).substring(1);
  7262. this.ctx.globalCompositeOperation = mode;
  7263. if (this.ctx.globalCompositeOperation !== mode) {
  7264. warn('globalCompositeOperation "' + mode + '" is not supported');
  7265. }
  7266. } else {
  7267. this.ctx.globalCompositeOperation = 'source-over';
  7268. }
  7269. break;
  7270. case 'SMask':
  7271. if (this.current.activeSMask) {
  7272. // If SMask is currrenly used, it needs to be suspended or
  7273. // finished. Suspend only makes sense when at least one save()
  7274. // was performed and state needs to be reverted on restore().
  7275. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  7276. this.suspendSMaskGroup();
  7277. } else {
  7278. this.endSMaskGroup();
  7279. }
  7280. }
  7281. this.current.activeSMask = value ? this.tempSMask : null;
  7282. if (this.current.activeSMask) {
  7283. this.beginSMaskGroup();
  7284. }
  7285. this.tempSMask = null;
  7286. break;
  7287. }
  7288. }
  7289. },
  7290. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  7291. var activeSMask = this.current.activeSMask;
  7292. var drawnWidth = activeSMask.canvas.width;
  7293. var drawnHeight = activeSMask.canvas.height;
  7294. var cacheId = 'smaskGroupAt' + this.groupLevel;
  7295. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7296. var currentCtx = this.ctx;
  7297. var currentTransform = currentCtx.mozCurrentTransform;
  7298. this.ctx.save();
  7299. var groupCtx = scratchCanvas.context;
  7300. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  7301. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  7302. groupCtx.transform.apply(groupCtx, currentTransform);
  7303. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  7304. copyCtxState(currentCtx, groupCtx);
  7305. this.ctx = groupCtx;
  7306. this.setGState([
  7307. [
  7308. 'BM',
  7309. 'Normal'
  7310. ],
  7311. [
  7312. 'ca',
  7313. 1
  7314. ],
  7315. [
  7316. 'CA',
  7317. 1
  7318. ]
  7319. ]);
  7320. this.groupStack.push(currentCtx);
  7321. this.groupLevel++;
  7322. },
  7323. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7324. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7325. // and future ctx state restored.
  7326. var groupCtx = this.ctx;
  7327. this.groupLevel--;
  7328. this.ctx = this.groupStack.pop();
  7329. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7330. this.ctx.restore();
  7331. this.ctx.save();
  7332. // save is needed since SMask will be resumed.
  7333. copyCtxState(groupCtx, this.ctx);
  7334. // Saving state for resuming.
  7335. this.current.resumeSMaskCtx = groupCtx;
  7336. // Transform was changed in the SMask canvas, reflecting this change on
  7337. // this.ctx.
  7338. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7339. this.ctx.transform.apply(this.ctx, deltaTransform);
  7340. // SMask was composed, the results at the groupCtx can be cleared.
  7341. groupCtx.save();
  7342. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7343. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7344. groupCtx.restore();
  7345. },
  7346. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7347. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7348. // any groupCtx state since restore() command (the only caller) will do
  7349. // that for us. See also beginSMaskGroup.
  7350. var groupCtx = this.current.resumeSMaskCtx;
  7351. var currentCtx = this.ctx;
  7352. this.ctx = groupCtx;
  7353. this.groupStack.push(currentCtx);
  7354. this.groupLevel++;
  7355. },
  7356. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7357. var groupCtx = this.ctx;
  7358. this.groupLevel--;
  7359. this.ctx = this.groupStack.pop();
  7360. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7361. this.ctx.restore();
  7362. copyCtxState(groupCtx, this.ctx);
  7363. // Transform was changed in the SMask canvas, reflecting this change on
  7364. // this.ctx.
  7365. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7366. this.ctx.transform.apply(this.ctx, deltaTransform);
  7367. },
  7368. save: function CanvasGraphics_save() {
  7369. this.ctx.save();
  7370. var old = this.current;
  7371. this.stateStack.push(old);
  7372. this.current = old.clone();
  7373. this.current.resumeSMaskCtx = null;
  7374. },
  7375. restore: function CanvasGraphics_restore() {
  7376. // SMask was suspended, we just need to resume it.
  7377. if (this.current.resumeSMaskCtx) {
  7378. this.resumeSMaskGroup();
  7379. }
  7380. // SMask has to be finished once there is no states that are using the
  7381. // same SMask.
  7382. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  7383. this.endSMaskGroup();
  7384. }
  7385. if (this.stateStack.length !== 0) {
  7386. this.current = this.stateStack.pop();
  7387. this.ctx.restore();
  7388. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7389. this.pendingClip = null;
  7390. this.cachedGetSinglePixelWidth = null;
  7391. }
  7392. },
  7393. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7394. this.ctx.transform(a, b, c, d, e, f);
  7395. this.cachedGetSinglePixelWidth = null;
  7396. },
  7397. // Path
  7398. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7399. var ctx = this.ctx;
  7400. var current = this.current;
  7401. var x = current.x, y = current.y;
  7402. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7403. switch (ops[i] | 0) {
  7404. case OPS.rectangle:
  7405. x = args[j++];
  7406. y = args[j++];
  7407. var width = args[j++];
  7408. var height = args[j++];
  7409. if (width === 0) {
  7410. width = this.getSinglePixelWidth();
  7411. }
  7412. if (height === 0) {
  7413. height = this.getSinglePixelWidth();
  7414. }
  7415. var xw = x + width;
  7416. var yh = y + height;
  7417. this.ctx.moveTo(x, y);
  7418. this.ctx.lineTo(xw, y);
  7419. this.ctx.lineTo(xw, yh);
  7420. this.ctx.lineTo(x, yh);
  7421. this.ctx.lineTo(x, y);
  7422. this.ctx.closePath();
  7423. break;
  7424. case OPS.moveTo:
  7425. x = args[j++];
  7426. y = args[j++];
  7427. ctx.moveTo(x, y);
  7428. break;
  7429. case OPS.lineTo:
  7430. x = args[j++];
  7431. y = args[j++];
  7432. ctx.lineTo(x, y);
  7433. break;
  7434. case OPS.curveTo:
  7435. x = args[j + 4];
  7436. y = args[j + 5];
  7437. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7438. j += 6;
  7439. break;
  7440. case OPS.curveTo2:
  7441. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7442. x = args[j + 2];
  7443. y = args[j + 3];
  7444. j += 4;
  7445. break;
  7446. case OPS.curveTo3:
  7447. x = args[j + 2];
  7448. y = args[j + 3];
  7449. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7450. j += 4;
  7451. break;
  7452. case OPS.closePath:
  7453. ctx.closePath();
  7454. break;
  7455. }
  7456. }
  7457. current.setCurrentPoint(x, y);
  7458. },
  7459. closePath: function CanvasGraphics_closePath() {
  7460. this.ctx.closePath();
  7461. },
  7462. stroke: function CanvasGraphics_stroke(consumePath) {
  7463. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7464. var ctx = this.ctx;
  7465. var strokeColor = this.current.strokeColor;
  7466. // Prevent drawing too thin lines by enforcing a minimum line width.
  7467. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  7468. // For stroke we want to temporarily change the global alpha to the
  7469. // stroking alpha.
  7470. ctx.globalAlpha = this.current.strokeAlpha;
  7471. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  7472. // for patterns, we transform to pattern space, calculate
  7473. // the pattern, call stroke, and restore to user space
  7474. ctx.save();
  7475. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7476. ctx.stroke();
  7477. ctx.restore();
  7478. } else {
  7479. ctx.stroke();
  7480. }
  7481. if (consumePath) {
  7482. this.consumePath();
  7483. }
  7484. // Restore the global alpha to the fill alpha
  7485. ctx.globalAlpha = this.current.fillAlpha;
  7486. },
  7487. closeStroke: function CanvasGraphics_closeStroke() {
  7488. this.closePath();
  7489. this.stroke();
  7490. },
  7491. fill: function CanvasGraphics_fill(consumePath) {
  7492. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7493. var ctx = this.ctx;
  7494. var fillColor = this.current.fillColor;
  7495. var isPatternFill = this.current.patternFill;
  7496. var needRestore = false;
  7497. if (isPatternFill) {
  7498. ctx.save();
  7499. if (this.baseTransform) {
  7500. ctx.setTransform.apply(ctx, this.baseTransform);
  7501. }
  7502. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7503. needRestore = true;
  7504. }
  7505. if (this.pendingEOFill) {
  7506. if (ctx.mozFillRule !== undefined) {
  7507. ctx.mozFillRule = 'evenodd';
  7508. ctx.fill();
  7509. ctx.mozFillRule = 'nonzero';
  7510. } else {
  7511. ctx.fill('evenodd');
  7512. }
  7513. this.pendingEOFill = false;
  7514. } else {
  7515. ctx.fill();
  7516. }
  7517. if (needRestore) {
  7518. ctx.restore();
  7519. }
  7520. if (consumePath) {
  7521. this.consumePath();
  7522. }
  7523. },
  7524. eoFill: function CanvasGraphics_eoFill() {
  7525. this.pendingEOFill = true;
  7526. this.fill();
  7527. },
  7528. fillStroke: function CanvasGraphics_fillStroke() {
  7529. this.fill(false);
  7530. this.stroke(false);
  7531. this.consumePath();
  7532. },
  7533. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7534. this.pendingEOFill = true;
  7535. this.fillStroke();
  7536. },
  7537. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7538. this.closePath();
  7539. this.fillStroke();
  7540. },
  7541. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7542. this.pendingEOFill = true;
  7543. this.closePath();
  7544. this.fillStroke();
  7545. },
  7546. endPath: function CanvasGraphics_endPath() {
  7547. this.consumePath();
  7548. },
  7549. // Clipping
  7550. clip: function CanvasGraphics_clip() {
  7551. this.pendingClip = NORMAL_CLIP;
  7552. },
  7553. eoClip: function CanvasGraphics_eoClip() {
  7554. this.pendingClip = EO_CLIP;
  7555. },
  7556. // Text
  7557. beginText: function CanvasGraphics_beginText() {
  7558. this.current.textMatrix = IDENTITY_MATRIX;
  7559. this.current.textMatrixScale = 1;
  7560. this.current.x = this.current.lineX = 0;
  7561. this.current.y = this.current.lineY = 0;
  7562. },
  7563. endText: function CanvasGraphics_endText() {
  7564. var paths = this.pendingTextPaths;
  7565. var ctx = this.ctx;
  7566. if (paths === undefined) {
  7567. ctx.beginPath();
  7568. return;
  7569. }
  7570. ctx.save();
  7571. ctx.beginPath();
  7572. for (var i = 0; i < paths.length; i++) {
  7573. var path = paths[i];
  7574. ctx.setTransform.apply(ctx, path.transform);
  7575. ctx.translate(path.x, path.y);
  7576. path.addToPath(ctx, path.fontSize);
  7577. }
  7578. ctx.restore();
  7579. ctx.clip();
  7580. ctx.beginPath();
  7581. delete this.pendingTextPaths;
  7582. },
  7583. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7584. this.current.charSpacing = spacing;
  7585. },
  7586. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7587. this.current.wordSpacing = spacing;
  7588. },
  7589. setHScale: function CanvasGraphics_setHScale(scale) {
  7590. this.current.textHScale = scale / 100;
  7591. },
  7592. setLeading: function CanvasGraphics_setLeading(leading) {
  7593. this.current.leading = -leading;
  7594. },
  7595. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7596. var fontObj = this.commonObjs.get(fontRefName);
  7597. var current = this.current;
  7598. if (!fontObj) {
  7599. error('Can\'t find font for ' + fontRefName);
  7600. }
  7601. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  7602. // A valid matrix needs all main diagonal elements to be non-zero
  7603. // This also ensures we bypass FF bugzilla bug #719844.
  7604. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7605. warn('Invalid font matrix for font ' + fontRefName);
  7606. }
  7607. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7608. // and in some docs this can be negative (inverted x-y axes).
  7609. if (size < 0) {
  7610. size = -size;
  7611. current.fontDirection = -1;
  7612. } else {
  7613. current.fontDirection = 1;
  7614. }
  7615. this.current.font = fontObj;
  7616. this.current.fontSize = size;
  7617. if (fontObj.isType3Font) {
  7618. return;
  7619. }
  7620. // we don't need ctx.font for Type3 fonts
  7621. var name = fontObj.loadedName || 'sans-serif';
  7622. var bold = fontObj.black ? fontObj.bold ? '900' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  7623. var italic = fontObj.italic ? 'italic' : 'normal';
  7624. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7625. // Some font backends cannot handle fonts below certain size.
  7626. // Keeping the font at minimal size and using the fontSizeScale to change
  7627. // the current transformation matrix before the fillText/strokeText.
  7628. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7629. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7630. this.current.fontSizeScale = size / browserFontSize;
  7631. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7632. this.ctx.font = rule;
  7633. },
  7634. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7635. this.current.textRenderingMode = mode;
  7636. },
  7637. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7638. this.current.textRise = rise;
  7639. },
  7640. moveText: function CanvasGraphics_moveText(x, y) {
  7641. this.current.x = this.current.lineX += x;
  7642. this.current.y = this.current.lineY += y;
  7643. },
  7644. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7645. this.setLeading(-y);
  7646. this.moveText(x, y);
  7647. },
  7648. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7649. this.current.textMatrix = [
  7650. a,
  7651. b,
  7652. c,
  7653. d,
  7654. e,
  7655. f
  7656. ];
  7657. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7658. this.current.x = this.current.lineX = 0;
  7659. this.current.y = this.current.lineY = 0;
  7660. },
  7661. nextLine: function CanvasGraphics_nextLine() {
  7662. this.moveText(0, this.current.leading);
  7663. },
  7664. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7665. var ctx = this.ctx;
  7666. var current = this.current;
  7667. var font = current.font;
  7668. var textRenderingMode = current.textRenderingMode;
  7669. var fontSize = current.fontSize / current.fontSizeScale;
  7670. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7671. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7672. var addToPath;
  7673. if (font.disableFontFace || isAddToPathSet) {
  7674. addToPath = font.getPathGenerator(this.commonObjs, character);
  7675. }
  7676. if (font.disableFontFace) {
  7677. ctx.save();
  7678. ctx.translate(x, y);
  7679. ctx.beginPath();
  7680. addToPath(ctx, fontSize);
  7681. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7682. ctx.fill();
  7683. }
  7684. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7685. ctx.stroke();
  7686. }
  7687. ctx.restore();
  7688. } else {
  7689. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7690. ctx.fillText(character, x, y);
  7691. }
  7692. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7693. ctx.strokeText(character, x, y);
  7694. }
  7695. }
  7696. if (isAddToPathSet) {
  7697. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7698. paths.push({
  7699. transform: ctx.mozCurrentTransform,
  7700. x: x,
  7701. y: y,
  7702. fontSize: fontSize,
  7703. addToPath: addToPath
  7704. });
  7705. }
  7706. },
  7707. get isFontSubpixelAAEnabled() {
  7708. // Checks if anti-aliasing is enabled when scaled text is painted.
  7709. // On Windows GDI scaled fonts looks bad.
  7710. var ctx = document.createElement('canvas').getContext('2d');
  7711. ctx.scale(1.5, 1);
  7712. ctx.fillText('I', 0, 10);
  7713. var data = ctx.getImageData(0, 0, 10, 10).data;
  7714. var enabled = false;
  7715. for (var i = 3; i < data.length; i += 4) {
  7716. if (data[i] > 0 && data[i] < 255) {
  7717. enabled = true;
  7718. break;
  7719. }
  7720. }
  7721. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7722. },
  7723. showText: function CanvasGraphics_showText(glyphs) {
  7724. var current = this.current;
  7725. var font = current.font;
  7726. if (font.isType3Font) {
  7727. return this.showType3Text(glyphs);
  7728. }
  7729. var fontSize = current.fontSize;
  7730. if (fontSize === 0) {
  7731. return;
  7732. }
  7733. var ctx = this.ctx;
  7734. var fontSizeScale = current.fontSizeScale;
  7735. var charSpacing = current.charSpacing;
  7736. var wordSpacing = current.wordSpacing;
  7737. var fontDirection = current.fontDirection;
  7738. var textHScale = current.textHScale * fontDirection;
  7739. var glyphsLength = glyphs.length;
  7740. var vertical = font.vertical;
  7741. var spacingDir = vertical ? 1 : -1;
  7742. var defaultVMetrics = font.defaultVMetrics;
  7743. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7744. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  7745. ctx.save();
  7746. ctx.transform.apply(ctx, current.textMatrix);
  7747. ctx.translate(current.x, current.y + current.textRise);
  7748. if (current.patternFill) {
  7749. // TODO: Some shading patterns are not applied correctly to text,
  7750. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7751. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7752. }
  7753. if (fontDirection > 0) {
  7754. ctx.scale(textHScale, -1);
  7755. } else {
  7756. ctx.scale(textHScale, 1);
  7757. }
  7758. var lineWidth = current.lineWidth;
  7759. var scale = current.textMatrixScale;
  7760. if (scale === 0 || lineWidth === 0) {
  7761. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7762. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7763. this.cachedGetSinglePixelWidth = null;
  7764. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7765. }
  7766. } else {
  7767. lineWidth /= scale;
  7768. }
  7769. if (fontSizeScale !== 1.0) {
  7770. ctx.scale(fontSizeScale, fontSizeScale);
  7771. lineWidth /= fontSizeScale;
  7772. }
  7773. ctx.lineWidth = lineWidth;
  7774. var x = 0, i;
  7775. for (i = 0; i < glyphsLength; ++i) {
  7776. var glyph = glyphs[i];
  7777. if (isNum(glyph)) {
  7778. x += spacingDir * glyph * fontSize / 1000;
  7779. continue;
  7780. }
  7781. var restoreNeeded = false;
  7782. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7783. var character = glyph.fontChar;
  7784. var accent = glyph.accent;
  7785. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7786. var width = glyph.width;
  7787. if (vertical) {
  7788. var vmetric, vx, vy;
  7789. vmetric = glyph.vmetric || defaultVMetrics;
  7790. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7791. vx = -vx * widthAdvanceScale;
  7792. vy = vmetric[2] * widthAdvanceScale;
  7793. width = vmetric ? -vmetric[0] : width;
  7794. scaledX = vx / fontSizeScale;
  7795. scaledY = (x + vy) / fontSizeScale;
  7796. } else {
  7797. scaledX = x / fontSizeScale;
  7798. scaledY = 0;
  7799. }
  7800. if (font.remeasure && width > 0) {
  7801. // Some standard fonts may not have the exact width: rescale per
  7802. // character if measured width is greater than expected glyph width
  7803. // and subpixel-aa is enabled, otherwise just center the glyph.
  7804. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7805. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7806. var characterScaleX = width / measuredWidth;
  7807. restoreNeeded = true;
  7808. ctx.save();
  7809. ctx.scale(characterScaleX, 1);
  7810. scaledX /= characterScaleX;
  7811. } else if (width !== measuredWidth) {
  7812. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7813. }
  7814. }
  7815. // Only attempt to draw the glyph if it is actually in the embedded font
  7816. // file or if there isn't a font file so the fallback font is shown.
  7817. if (glyph.isInFont || font.missingFile) {
  7818. if (simpleFillText && !accent) {
  7819. // common case
  7820. ctx.fillText(character, scaledX, scaledY);
  7821. } else {
  7822. this.paintChar(character, scaledX, scaledY);
  7823. if (accent) {
  7824. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7825. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7826. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7827. }
  7828. }
  7829. }
  7830. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7831. x += charWidth;
  7832. if (restoreNeeded) {
  7833. ctx.restore();
  7834. }
  7835. }
  7836. if (vertical) {
  7837. current.y -= x * textHScale;
  7838. } else {
  7839. current.x += x * textHScale;
  7840. }
  7841. ctx.restore();
  7842. },
  7843. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7844. // Type3 fonts - each glyph is a "mini-PDF"
  7845. var ctx = this.ctx;
  7846. var current = this.current;
  7847. var font = current.font;
  7848. var fontSize = current.fontSize;
  7849. var fontDirection = current.fontDirection;
  7850. var spacingDir = font.vertical ? 1 : -1;
  7851. var charSpacing = current.charSpacing;
  7852. var wordSpacing = current.wordSpacing;
  7853. var textHScale = current.textHScale * fontDirection;
  7854. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7855. var glyphsLength = glyphs.length;
  7856. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7857. var i, glyph, width, spacingLength;
  7858. if (isTextInvisible || fontSize === 0) {
  7859. return;
  7860. }
  7861. this.cachedGetSinglePixelWidth = null;
  7862. ctx.save();
  7863. ctx.transform.apply(ctx, current.textMatrix);
  7864. ctx.translate(current.x, current.y);
  7865. ctx.scale(textHScale, fontDirection);
  7866. for (i = 0; i < glyphsLength; ++i) {
  7867. glyph = glyphs[i];
  7868. if (isNum(glyph)) {
  7869. spacingLength = spacingDir * glyph * fontSize / 1000;
  7870. this.ctx.translate(spacingLength, 0);
  7871. current.x += spacingLength * textHScale;
  7872. continue;
  7873. }
  7874. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7875. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7876. if (!operatorList) {
  7877. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7878. continue;
  7879. }
  7880. this.processingType3 = glyph;
  7881. this.save();
  7882. ctx.scale(fontSize, fontSize);
  7883. ctx.transform.apply(ctx, fontMatrix);
  7884. this.executeOperatorList(operatorList);
  7885. this.restore();
  7886. var transformed = Util.applyTransform([
  7887. glyph.width,
  7888. 0
  7889. ], fontMatrix);
  7890. width = transformed[0] * fontSize + spacing;
  7891. ctx.translate(width, 0);
  7892. current.x += width * textHScale;
  7893. }
  7894. ctx.restore();
  7895. this.processingType3 = null;
  7896. },
  7897. // Type3 fonts
  7898. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7899. },
  7900. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7901. // TODO According to the spec we're also suppose to ignore any operators
  7902. // that set color or include images while processing this type3 font.
  7903. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7904. this.clip();
  7905. this.endPath();
  7906. },
  7907. // Color
  7908. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7909. var pattern;
  7910. if (IR[0] === 'TilingPattern') {
  7911. var color = IR[1];
  7912. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7913. var self = this;
  7914. var canvasGraphicsFactory = {
  7915. createCanvasGraphics: function (ctx) {
  7916. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7917. }
  7918. };
  7919. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7920. } else {
  7921. pattern = getShadingPatternFromIR(IR);
  7922. }
  7923. return pattern;
  7924. },
  7925. setStrokeColorN: function CanvasGraphics_setStrokeColorN()
  7926. /*...*/
  7927. {
  7928. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7929. },
  7930. setFillColorN: function CanvasGraphics_setFillColorN()
  7931. /*...*/
  7932. {
  7933. this.current.fillColor = this.getColorN_Pattern(arguments);
  7934. this.current.patternFill = true;
  7935. },
  7936. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7937. var color = Util.makeCssRgb(r, g, b);
  7938. this.ctx.strokeStyle = color;
  7939. this.current.strokeColor = color;
  7940. },
  7941. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7942. var color = Util.makeCssRgb(r, g, b);
  7943. this.ctx.fillStyle = color;
  7944. this.current.fillColor = color;
  7945. this.current.patternFill = false;
  7946. },
  7947. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7948. var ctx = this.ctx;
  7949. this.save();
  7950. var pattern = getShadingPatternFromIR(patternIR);
  7951. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7952. var inv = ctx.mozCurrentTransformInverse;
  7953. if (inv) {
  7954. var canvas = ctx.canvas;
  7955. var width = canvas.width;
  7956. var height = canvas.height;
  7957. var bl = Util.applyTransform([
  7958. 0,
  7959. 0
  7960. ], inv);
  7961. var br = Util.applyTransform([
  7962. 0,
  7963. height
  7964. ], inv);
  7965. var ul = Util.applyTransform([
  7966. width,
  7967. 0
  7968. ], inv);
  7969. var ur = Util.applyTransform([
  7970. width,
  7971. height
  7972. ], inv);
  7973. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7974. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7975. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7976. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7977. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7978. } else {
  7979. // HACK to draw the gradient onto an infinite rectangle.
  7980. // PDF gradients are drawn across the entire image while
  7981. // Canvas only allows gradients to be drawn in a rectangle
  7982. // The following bug should allow us to remove this.
  7983. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7984. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7985. }
  7986. this.restore();
  7987. },
  7988. // Images
  7989. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7990. error('Should not call beginInlineImage');
  7991. },
  7992. beginImageData: function CanvasGraphics_beginImageData() {
  7993. error('Should not call beginImageData');
  7994. },
  7995. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  7996. this.save();
  7997. this.baseTransformStack.push(this.baseTransform);
  7998. if (isArray(matrix) && 6 === matrix.length) {
  7999. this.transform.apply(this, matrix);
  8000. }
  8001. this.baseTransform = this.ctx.mozCurrentTransform;
  8002. if (isArray(bbox) && 4 === bbox.length) {
  8003. var width = bbox[2] - bbox[0];
  8004. var height = bbox[3] - bbox[1];
  8005. this.ctx.rect(bbox[0], bbox[1], width, height);
  8006. this.clip();
  8007. this.endPath();
  8008. }
  8009. },
  8010. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  8011. this.restore();
  8012. this.baseTransform = this.baseTransformStack.pop();
  8013. },
  8014. beginGroup: function CanvasGraphics_beginGroup(group) {
  8015. this.save();
  8016. var currentCtx = this.ctx;
  8017. // TODO non-isolated groups - according to Rik at adobe non-isolated
  8018. // group results aren't usually that different and they even have tools
  8019. // that ignore this setting. Notes from Rik on implementing:
  8020. // - When you encounter an transparency group, create a new canvas with
  8021. // the dimensions of the bbox
  8022. // - copy the content from the previous canvas to the new canvas
  8023. // - draw as usual
  8024. // - remove the backdrop alpha:
  8025. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  8026. // value of your transparency group and 'alphaBackdrop' the alpha of the
  8027. // backdrop
  8028. // - remove background color:
  8029. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  8030. if (!group.isolated) {
  8031. info('TODO: Support non-isolated groups.');
  8032. }
  8033. // TODO knockout - supposedly possible with the clever use of compositing
  8034. // modes.
  8035. if (group.knockout) {
  8036. warn('Knockout groups not supported.');
  8037. }
  8038. var currentTransform = currentCtx.mozCurrentTransform;
  8039. if (group.matrix) {
  8040. currentCtx.transform.apply(currentCtx, group.matrix);
  8041. }
  8042. assert(group.bbox, 'Bounding box is required.');
  8043. // Based on the current transform figure out how big the bounding box
  8044. // will actually be.
  8045. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  8046. // Clip the bounding box to the current canvas.
  8047. var canvasBounds = [
  8048. 0,
  8049. 0,
  8050. currentCtx.canvas.width,
  8051. currentCtx.canvas.height
  8052. ];
  8053. bounds = Util.intersect(bounds, canvasBounds) || [
  8054. 0,
  8055. 0,
  8056. 0,
  8057. 0
  8058. ];
  8059. // Use ceil in case we're between sizes so we don't create canvas that is
  8060. // too small and make the canvas at least 1x1 pixels.
  8061. var offsetX = Math.floor(bounds[0]);
  8062. var offsetY = Math.floor(bounds[1]);
  8063. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8064. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8065. var scaleX = 1, scaleY = 1;
  8066. if (drawnWidth > MAX_GROUP_SIZE) {
  8067. scaleX = drawnWidth / MAX_GROUP_SIZE;
  8068. drawnWidth = MAX_GROUP_SIZE;
  8069. }
  8070. if (drawnHeight > MAX_GROUP_SIZE) {
  8071. scaleY = drawnHeight / MAX_GROUP_SIZE;
  8072. drawnHeight = MAX_GROUP_SIZE;
  8073. }
  8074. var cacheId = 'groupAt' + this.groupLevel;
  8075. if (group.smask) {
  8076. // Using two cache entries is case if masks are used one after another.
  8077. cacheId += '_smask_' + this.smaskCounter++ % 2;
  8078. }
  8079. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  8080. var groupCtx = scratchCanvas.context;
  8081. // Since we created a new canvas that is just the size of the bounding box
  8082. // we have to translate the group ctx.
  8083. groupCtx.scale(1 / scaleX, 1 / scaleY);
  8084. groupCtx.translate(-offsetX, -offsetY);
  8085. groupCtx.transform.apply(groupCtx, currentTransform);
  8086. if (group.smask) {
  8087. // Saving state and cached mask to be used in setGState.
  8088. this.smaskStack.push({
  8089. canvas: scratchCanvas.canvas,
  8090. context: groupCtx,
  8091. offsetX: offsetX,
  8092. offsetY: offsetY,
  8093. scaleX: scaleX,
  8094. scaleY: scaleY,
  8095. subtype: group.smask.subtype,
  8096. backdrop: group.smask.backdrop,
  8097. transferMap: group.smask.transferMap || null,
  8098. startTransformInverse: null
  8099. });
  8100. } else
  8101. // used during suspend operation
  8102. {
  8103. // Setup the current ctx so when the group is popped we draw it at the
  8104. // right location.
  8105. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8106. currentCtx.translate(offsetX, offsetY);
  8107. currentCtx.scale(scaleX, scaleY);
  8108. }
  8109. // The transparency group inherits all off the current graphics state
  8110. // except the blend mode, soft mask, and alpha constants.
  8111. copyCtxState(currentCtx, groupCtx);
  8112. this.ctx = groupCtx;
  8113. this.setGState([
  8114. [
  8115. 'BM',
  8116. 'Normal'
  8117. ],
  8118. [
  8119. 'ca',
  8120. 1
  8121. ],
  8122. [
  8123. 'CA',
  8124. 1
  8125. ]
  8126. ]);
  8127. this.groupStack.push(currentCtx);
  8128. this.groupLevel++;
  8129. // Reseting mask state, masks will be applied on restore of the group.
  8130. this.current.activeSMask = null;
  8131. },
  8132. endGroup: function CanvasGraphics_endGroup(group) {
  8133. this.groupLevel--;
  8134. var groupCtx = this.ctx;
  8135. this.ctx = this.groupStack.pop();
  8136. // Turn off image smoothing to avoid sub pixel interpolation which can
  8137. // look kind of blurry for some pdfs.
  8138. if (this.ctx.imageSmoothingEnabled !== undefined) {
  8139. this.ctx.imageSmoothingEnabled = false;
  8140. } else {
  8141. this.ctx.mozImageSmoothingEnabled = false;
  8142. }
  8143. if (group.smask) {
  8144. this.tempSMask = this.smaskStack.pop();
  8145. } else {
  8146. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8147. }
  8148. this.restore();
  8149. },
  8150. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  8151. this.save();
  8152. this.current = new CanvasExtraState();
  8153. if (this.baseTransform) {
  8154. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  8155. }
  8156. },
  8157. endAnnotations: function CanvasGraphics_endAnnotations() {
  8158. this.restore();
  8159. },
  8160. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  8161. this.save();
  8162. if (isArray(rect) && 4 === rect.length) {
  8163. var width = rect[2] - rect[0];
  8164. var height = rect[3] - rect[1];
  8165. this.ctx.rect(rect[0], rect[1], width, height);
  8166. this.clip();
  8167. this.endPath();
  8168. }
  8169. this.transform.apply(this, transform);
  8170. this.transform.apply(this, matrix);
  8171. },
  8172. endAnnotation: function CanvasGraphics_endAnnotation() {
  8173. this.restore();
  8174. },
  8175. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  8176. var domImage = this.objs.get(objId);
  8177. if (!domImage) {
  8178. warn('Dependent image isn\'t ready yet');
  8179. return;
  8180. }
  8181. this.save();
  8182. var ctx = this.ctx;
  8183. // scale the image to the unit square
  8184. ctx.scale(1 / w, -1 / h);
  8185. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  8186. if (this.imageLayer) {
  8187. var currentTransform = ctx.mozCurrentTransformInverse;
  8188. var position = this.getCanvasPosition(0, 0);
  8189. this.imageLayer.appendImage({
  8190. objId: objId,
  8191. left: position[0],
  8192. top: position[1],
  8193. width: w / currentTransform[0],
  8194. height: h / currentTransform[3]
  8195. });
  8196. }
  8197. this.restore();
  8198. },
  8199. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  8200. var ctx = this.ctx;
  8201. var width = img.width, height = img.height;
  8202. var fillColor = this.current.fillColor;
  8203. var isPatternFill = this.current.patternFill;
  8204. var glyph = this.processingType3;
  8205. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  8206. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  8207. glyph.compiled = compileType3Glyph({
  8208. data: img.data,
  8209. width: width,
  8210. height: height
  8211. });
  8212. } else {
  8213. glyph.compiled = null;
  8214. }
  8215. }
  8216. if (glyph && glyph.compiled) {
  8217. glyph.compiled(ctx);
  8218. return;
  8219. }
  8220. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8221. var maskCtx = maskCanvas.context;
  8222. maskCtx.save();
  8223. putBinaryImageMask(maskCtx, img);
  8224. maskCtx.globalCompositeOperation = 'source-in';
  8225. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8226. maskCtx.fillRect(0, 0, width, height);
  8227. maskCtx.restore();
  8228. this.paintInlineImageXObject(maskCanvas.canvas);
  8229. },
  8230. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  8231. var width = imgData.width;
  8232. var height = imgData.height;
  8233. var fillColor = this.current.fillColor;
  8234. var isPatternFill = this.current.patternFill;
  8235. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8236. var maskCtx = maskCanvas.context;
  8237. maskCtx.save();
  8238. putBinaryImageMask(maskCtx, imgData);
  8239. maskCtx.globalCompositeOperation = 'source-in';
  8240. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8241. maskCtx.fillRect(0, 0, width, height);
  8242. maskCtx.restore();
  8243. var ctx = this.ctx;
  8244. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8245. ctx.save();
  8246. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  8247. ctx.scale(1, -1);
  8248. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8249. ctx.restore();
  8250. }
  8251. },
  8252. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  8253. var ctx = this.ctx;
  8254. var fillColor = this.current.fillColor;
  8255. var isPatternFill = this.current.patternFill;
  8256. for (var i = 0, ii = images.length; i < ii; i++) {
  8257. var image = images[i];
  8258. var width = image.width, height = image.height;
  8259. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8260. var maskCtx = maskCanvas.context;
  8261. maskCtx.save();
  8262. putBinaryImageMask(maskCtx, image);
  8263. maskCtx.globalCompositeOperation = 'source-in';
  8264. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8265. maskCtx.fillRect(0, 0, width, height);
  8266. maskCtx.restore();
  8267. ctx.save();
  8268. ctx.transform.apply(ctx, image.transform);
  8269. ctx.scale(1, -1);
  8270. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8271. ctx.restore();
  8272. }
  8273. },
  8274. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  8275. var imgData = this.objs.get(objId);
  8276. if (!imgData) {
  8277. warn('Dependent image isn\'t ready yet');
  8278. return;
  8279. }
  8280. this.paintInlineImageXObject(imgData);
  8281. },
  8282. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8283. var imgData = this.objs.get(objId);
  8284. if (!imgData) {
  8285. warn('Dependent image isn\'t ready yet');
  8286. return;
  8287. }
  8288. var width = imgData.width;
  8289. var height = imgData.height;
  8290. var map = [];
  8291. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8292. map.push({
  8293. transform: [
  8294. scaleX,
  8295. 0,
  8296. 0,
  8297. scaleY,
  8298. positions[i],
  8299. positions[i + 1]
  8300. ],
  8301. x: 0,
  8302. y: 0,
  8303. w: width,
  8304. h: height
  8305. });
  8306. }
  8307. this.paintInlineImageXObjectGroup(imgData, map);
  8308. },
  8309. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  8310. var width = imgData.width;
  8311. var height = imgData.height;
  8312. var ctx = this.ctx;
  8313. this.save();
  8314. // scale the image to the unit square
  8315. ctx.scale(1 / width, -1 / height);
  8316. var currentTransform = ctx.mozCurrentTransformInverse;
  8317. var a = currentTransform[0], b = currentTransform[1];
  8318. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8319. var c = currentTransform[2], d = currentTransform[3];
  8320. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8321. var imgToPaint, tmpCanvas;
  8322. // instanceof HTMLElement does not work in jsdom node.js module
  8323. if (imgData instanceof HTMLElement || !imgData.data) {
  8324. imgToPaint = imgData;
  8325. } else {
  8326. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  8327. var tmpCtx = tmpCanvas.context;
  8328. putBinaryImageData(tmpCtx, imgData);
  8329. imgToPaint = tmpCanvas.canvas;
  8330. }
  8331. var paintWidth = width, paintHeight = height;
  8332. var tmpCanvasId = 'prescale1';
  8333. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8334. // pixels during drawImage operation, painting on the temporary canvas(es)
  8335. // that are twice smaller in size
  8336. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  8337. var newWidth = paintWidth, newHeight = paintHeight;
  8338. if (widthScale > 2 && paintWidth > 1) {
  8339. newWidth = Math.ceil(paintWidth / 2);
  8340. widthScale /= paintWidth / newWidth;
  8341. }
  8342. if (heightScale > 2 && paintHeight > 1) {
  8343. newHeight = Math.ceil(paintHeight / 2);
  8344. heightScale /= paintHeight / newHeight;
  8345. }
  8346. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  8347. tmpCtx = tmpCanvas.context;
  8348. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8349. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  8350. imgToPaint = tmpCanvas.canvas;
  8351. paintWidth = newWidth;
  8352. paintHeight = newHeight;
  8353. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8354. }
  8355. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  8356. if (this.imageLayer) {
  8357. var position = this.getCanvasPosition(0, -height);
  8358. this.imageLayer.appendImage({
  8359. imgData: imgData,
  8360. left: position[0],
  8361. top: position[1],
  8362. width: width / currentTransform[0],
  8363. height: height / currentTransform[3]
  8364. });
  8365. }
  8366. this.restore();
  8367. },
  8368. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8369. var ctx = this.ctx;
  8370. var w = imgData.width;
  8371. var h = imgData.height;
  8372. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8373. var tmpCtx = tmpCanvas.context;
  8374. putBinaryImageData(tmpCtx, imgData);
  8375. for (var i = 0, ii = map.length; i < ii; i++) {
  8376. var entry = map[i];
  8377. ctx.save();
  8378. ctx.transform.apply(ctx, entry.transform);
  8379. ctx.scale(1, -1);
  8380. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8381. if (this.imageLayer) {
  8382. var position = this.getCanvasPosition(entry.x, entry.y);
  8383. this.imageLayer.appendImage({
  8384. imgData: imgData,
  8385. left: position[0],
  8386. top: position[1],
  8387. width: w,
  8388. height: h
  8389. });
  8390. }
  8391. ctx.restore();
  8392. }
  8393. },
  8394. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  8395. this.ctx.fillRect(0, 0, 1, 1);
  8396. },
  8397. paintXObject: function CanvasGraphics_paintXObject() {
  8398. warn('Unsupported \'paintXObject\' command.');
  8399. },
  8400. // Marked content
  8401. markPoint: function CanvasGraphics_markPoint(tag) {
  8402. },
  8403. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8404. },
  8405. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8406. },
  8407. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  8408. },
  8409. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8410. },
  8411. // Compatibility
  8412. beginCompat: function CanvasGraphics_beginCompat() {
  8413. },
  8414. endCompat: function CanvasGraphics_endCompat() {
  8415. },
  8416. // Helper functions
  8417. consumePath: function CanvasGraphics_consumePath() {
  8418. var ctx = this.ctx;
  8419. if (this.pendingClip) {
  8420. if (this.pendingClip === EO_CLIP) {
  8421. if (ctx.mozFillRule !== undefined) {
  8422. ctx.mozFillRule = 'evenodd';
  8423. ctx.clip();
  8424. ctx.mozFillRule = 'nonzero';
  8425. } else {
  8426. ctx.clip('evenodd');
  8427. }
  8428. } else {
  8429. ctx.clip();
  8430. }
  8431. this.pendingClip = null;
  8432. }
  8433. ctx.beginPath();
  8434. },
  8435. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8436. if (this.cachedGetSinglePixelWidth === null) {
  8437. // NOTE: The `save` and `restore` commands used below is a workaround
  8438. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8439. // from intermittently returning incorrect values in Firefox, see:
  8440. // https://github.com/mozilla/pdf.js/issues/7188.
  8441. this.ctx.save();
  8442. var inverse = this.ctx.mozCurrentTransformInverse;
  8443. this.ctx.restore();
  8444. // max of the current horizontal and vertical scale
  8445. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  8446. }
  8447. return this.cachedGetSinglePixelWidth;
  8448. },
  8449. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8450. var transform = this.ctx.mozCurrentTransform;
  8451. return [
  8452. transform[0] * x + transform[2] * y + transform[4],
  8453. transform[1] * x + transform[3] * y + transform[5]
  8454. ];
  8455. }
  8456. };
  8457. for (var op in OPS) {
  8458. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8459. }
  8460. return CanvasGraphics;
  8461. }();
  8462. exports.CanvasGraphics = CanvasGraphics;
  8463. exports.createScratchCanvas = createScratchCanvas;
  8464. }));
  8465. (function (root, factory) {
  8466. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8467. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  8468. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8469. var MessageHandler = sharedUtil.MessageHandler;
  8470. var MissingPDFException = sharedUtil.MissingPDFException;
  8471. var PageViewport = sharedUtil.PageViewport;
  8472. var PasswordResponses = sharedUtil.PasswordResponses;
  8473. var PasswordException = sharedUtil.PasswordException;
  8474. var StatTimer = sharedUtil.StatTimer;
  8475. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8476. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8477. var Util = sharedUtil.Util;
  8478. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8479. var error = sharedUtil.error;
  8480. var deprecated = sharedUtil.deprecated;
  8481. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8482. var info = sharedUtil.info;
  8483. var isInt = sharedUtil.isInt;
  8484. var isArray = sharedUtil.isArray;
  8485. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8486. var isSameOrigin = sharedUtil.isSameOrigin;
  8487. var loadJpegStream = sharedUtil.loadJpegStream;
  8488. var stringToBytes = sharedUtil.stringToBytes;
  8489. var globalScope = sharedUtil.globalScope;
  8490. var warn = sharedUtil.warn;
  8491. var FontFaceObject = displayFontLoader.FontFaceObject;
  8492. var FontLoader = displayFontLoader.FontLoader;
  8493. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8494. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8495. var Metadata = displayMetadata.Metadata;
  8496. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8497. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  8498. // 2^16 = 65536
  8499. var isWorkerDisabled = false;
  8500. var workerSrc;
  8501. var isPostMessageTransfersDisabled = false;
  8502. var fakeWorkerFilesLoader = null;
  8503. var useRequireEnsure = false;
  8504. // For GENERIC build we need add support of different fake file loaders
  8505. // for different frameworks.
  8506. if (typeof window === 'undefined') {
  8507. // node.js - disable worker and set require.ensure.
  8508. isWorkerDisabled = true;
  8509. if (typeof require.ensure === 'undefined') {
  8510. require.ensure = require('node-ensure');
  8511. }
  8512. useRequireEnsure = true;
  8513. }
  8514. if (typeof __webpack_require__ !== 'undefined') {
  8515. useRequireEnsure = true;
  8516. }
  8517. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8518. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8519. }
  8520. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8521. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  8522. require.ensure([], function () {
  8523. var worker = require('./pdf.worker.js');
  8524. callback(worker.WorkerMessageHandler);
  8525. });
  8526. } : dynamicLoaderSupported ? function (callback) {
  8527. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8528. callback(worker.WorkerMessageHandler);
  8529. });
  8530. } : null;
  8531. /**
  8532. * Document initialization / loading parameters object.
  8533. *
  8534. * @typedef {Object} DocumentInitParameters
  8535. * @property {string} url - The URL of the PDF.
  8536. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8537. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8538. * use atob() to convert it to a binary string first.
  8539. * @property {Object} httpHeaders - Basic authentication headers.
  8540. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8541. * Access-Control requests should be made using credentials such as cookies
  8542. * or authorization headers. The default is false.
  8543. * @property {string} password - For decrypting password-protected PDFs.
  8544. * @property {TypedArray} initialData - A typed array with the first portion or
  8545. * all of the pdf data. Used by the extension since some data is already
  8546. * loaded before the switch to range requests.
  8547. * @property {number} length - The PDF file length. It's used for progress
  8548. * reports and range requests operations.
  8549. * @property {PDFDataRangeTransport} range
  8550. * @property {number} rangeChunkSize - Optional parameter to specify
  8551. * maximum number of bytes fetched per range request. The default value is
  8552. * 2^16 = 65536.
  8553. * @property {PDFWorker} worker - The worker that will be used for the loading
  8554. * and parsing of the PDF data.
  8555. */
  8556. /**
  8557. * @typedef {Object} PDFDocumentStats
  8558. * @property {Array} streamTypes - Used stream types in the document (an item
  8559. * is set to true if specific stream ID was used in the document).
  8560. * @property {Array} fontTypes - Used font type in the document (an item is set
  8561. * to true if specific font ID was used in the document).
  8562. */
  8563. /**
  8564. * This is the main entry point for loading a PDF and interacting with it.
  8565. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8566. * is used, which means it must follow the same origin rules that any XHR does
  8567. * e.g. No cross domain requests without CORS.
  8568. *
  8569. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8570. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8571. * already populated with data or parameter object.
  8572. *
  8573. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8574. * if you want to manually serve range requests for data in the PDF.
  8575. *
  8576. * @param {function} passwordCallback (deprecated) It is used to request a
  8577. * password if wrong or no password was provided. The callback receives two
  8578. * parameters: function that needs to be called with new password and reason
  8579. * (see {PasswordResponses}).
  8580. *
  8581. * @param {function} progressCallback (deprecated) It is used to be able to
  8582. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8583. * a loading bar). The callback receives an {Object} with the properties:
  8584. * {number} loaded and {number} total.
  8585. *
  8586. * @return {PDFDocumentLoadingTask}
  8587. */
  8588. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  8589. var task = new PDFDocumentLoadingTask();
  8590. // Support of the obsolete arguments (for compatibility with API v1.0)
  8591. if (arguments.length > 1) {
  8592. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  8593. }
  8594. if (pdfDataRangeTransport) {
  8595. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8596. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8597. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8598. pdfDataRangeTransport.length = src.length;
  8599. pdfDataRangeTransport.initialData = src.initialData;
  8600. if (!pdfDataRangeTransport.abort) {
  8601. pdfDataRangeTransport.abort = function () {
  8602. };
  8603. }
  8604. }
  8605. src = Object.create(src);
  8606. src.range = pdfDataRangeTransport;
  8607. }
  8608. task.onPassword = passwordCallback || null;
  8609. task.onProgress = progressCallback || null;
  8610. var source;
  8611. if (typeof src === 'string') {
  8612. source = { url: src };
  8613. } else if (isArrayBuffer(src)) {
  8614. source = { data: src };
  8615. } else if (src instanceof PDFDataRangeTransport) {
  8616. source = { range: src };
  8617. } else {
  8618. if (typeof src !== 'object') {
  8619. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  8620. }
  8621. if (!src.url && !src.data && !src.range) {
  8622. error('Invalid parameter object: need either .data, .range or .url');
  8623. }
  8624. source = src;
  8625. }
  8626. var params = {};
  8627. var rangeTransport = null;
  8628. var worker = null;
  8629. for (var key in source) {
  8630. if (key === 'url' && typeof window !== 'undefined') {
  8631. // The full path is required in the 'url' field.
  8632. params[key] = new URL(source[key], window.location).href;
  8633. continue;
  8634. } else if (key === 'range') {
  8635. rangeTransport = source[key];
  8636. continue;
  8637. } else if (key === 'worker') {
  8638. worker = source[key];
  8639. continue;
  8640. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8641. // Converting string or array-like data to Uint8Array.
  8642. var pdfBytes = source[key];
  8643. if (typeof pdfBytes === 'string') {
  8644. params[key] = stringToBytes(pdfBytes);
  8645. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  8646. params[key] = new Uint8Array(pdfBytes);
  8647. } else if (isArrayBuffer(pdfBytes)) {
  8648. params[key] = new Uint8Array(pdfBytes);
  8649. } else {
  8650. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  8651. }
  8652. continue;
  8653. }
  8654. params[key] = source[key];
  8655. }
  8656. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8657. if (!worker) {
  8658. // Worker was not provided -- creating and owning our own.
  8659. worker = new PDFWorker();
  8660. task._worker = worker;
  8661. }
  8662. var docId = task.docId;
  8663. worker.promise.then(function () {
  8664. if (task.destroyed) {
  8665. throw new Error('Loading aborted');
  8666. }
  8667. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  8668. if (task.destroyed) {
  8669. throw new Error('Loading aborted');
  8670. }
  8671. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8672. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8673. task._transport = transport;
  8674. messageHandler.send('Ready', null);
  8675. });
  8676. }).catch(task._capability.reject);
  8677. return task;
  8678. }
  8679. /**
  8680. * Starts fetching of specified PDF document/data.
  8681. * @param {PDFWorker} worker
  8682. * @param {Object} source
  8683. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8684. * @param {string} docId Unique document id, used as MessageHandler id.
  8685. * @returns {Promise} The promise, which is resolved when worker id of
  8686. * MessageHandler is known.
  8687. * @private
  8688. */
  8689. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8690. if (worker.destroyed) {
  8691. return Promise.reject(new Error('Worker was destroyed'));
  8692. }
  8693. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8694. source.disableStream = getDefaultSetting('disableStream');
  8695. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8696. if (pdfDataRangeTransport) {
  8697. source.length = pdfDataRangeTransport.length;
  8698. source.initialData = pdfDataRangeTransport.initialData;
  8699. }
  8700. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8701. docId: docId,
  8702. source: source,
  8703. disableRange: getDefaultSetting('disableRange'),
  8704. maxImageSize: getDefaultSetting('maxImageSize'),
  8705. cMapUrl: getDefaultSetting('cMapUrl'),
  8706. cMapPacked: getDefaultSetting('cMapPacked'),
  8707. disableFontFace: getDefaultSetting('disableFontFace'),
  8708. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8709. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled
  8710. }).then(function (workerId) {
  8711. if (worker.destroyed) {
  8712. throw new Error('Worker was destroyed');
  8713. }
  8714. return workerId;
  8715. });
  8716. }
  8717. /**
  8718. * PDF document loading operation.
  8719. * @class
  8720. * @alias PDFDocumentLoadingTask
  8721. */
  8722. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  8723. var nextDocumentId = 0;
  8724. /** @constructs PDFDocumentLoadingTask */
  8725. function PDFDocumentLoadingTask() {
  8726. this._capability = createPromiseCapability();
  8727. this._transport = null;
  8728. this._worker = null;
  8729. /**
  8730. * Unique document loading task id -- used in MessageHandlers.
  8731. * @type {string}
  8732. */
  8733. this.docId = 'd' + nextDocumentId++;
  8734. /**
  8735. * Shows if loading task is destroyed.
  8736. * @type {boolean}
  8737. */
  8738. this.destroyed = false;
  8739. /**
  8740. * Callback to request a password if wrong or no password was provided.
  8741. * The callback receives two parameters: function that needs to be called
  8742. * with new password and reason (see {PasswordResponses}).
  8743. */
  8744. this.onPassword = null;
  8745. /**
  8746. * Callback to be able to monitor the loading progress of the PDF file
  8747. * (necessary to implement e.g. a loading bar). The callback receives
  8748. * an {Object} with the properties: {number} loaded and {number} total.
  8749. */
  8750. this.onProgress = null;
  8751. /**
  8752. * Callback to when unsupported feature is used. The callback receives
  8753. * an {UNSUPPORTED_FEATURES} argument.
  8754. */
  8755. this.onUnsupportedFeature = null;
  8756. }
  8757. PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */
  8758. {
  8759. /**
  8760. * @return {Promise}
  8761. */
  8762. get promise() {
  8763. return this._capability.promise;
  8764. },
  8765. /**
  8766. * Aborts all network requests and destroys worker.
  8767. * @return {Promise} A promise that is resolved after destruction activity
  8768. * is completed.
  8769. */
  8770. destroy: function () {
  8771. this.destroyed = true;
  8772. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  8773. return transportDestroyed.then(function () {
  8774. this._transport = null;
  8775. if (this._worker) {
  8776. this._worker.destroy();
  8777. this._worker = null;
  8778. }
  8779. }.bind(this));
  8780. },
  8781. /**
  8782. * Registers callbacks to indicate the document loading completion.
  8783. *
  8784. * @param {function} onFulfilled The callback for the loading completion.
  8785. * @param {function} onRejected The callback for the loading failure.
  8786. * @return {Promise} A promise that is resolved after the onFulfilled or
  8787. * onRejected callback.
  8788. */
  8789. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8790. return this.promise.then.apply(this.promise, arguments);
  8791. }
  8792. };
  8793. return PDFDocumentLoadingTask;
  8794. }();
  8795. /**
  8796. * Abstract class to support range requests file loading.
  8797. * @class
  8798. * @alias PDFDataRangeTransport
  8799. * @param {number} length
  8800. * @param {Uint8Array} initialData
  8801. */
  8802. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  8803. function PDFDataRangeTransport(length, initialData) {
  8804. this.length = length;
  8805. this.initialData = initialData;
  8806. this._rangeListeners = [];
  8807. this._progressListeners = [];
  8808. this._progressiveReadListeners = [];
  8809. this._readyCapability = createPromiseCapability();
  8810. }
  8811. PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */
  8812. {
  8813. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  8814. this._rangeListeners.push(listener);
  8815. },
  8816. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  8817. this._progressListeners.push(listener);
  8818. },
  8819. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8820. this._progressiveReadListeners.push(listener);
  8821. },
  8822. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8823. var listeners = this._rangeListeners;
  8824. for (var i = 0, n = listeners.length; i < n; ++i) {
  8825. listeners[i](begin, chunk);
  8826. }
  8827. },
  8828. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8829. this._readyCapability.promise.then(function () {
  8830. var listeners = this._progressListeners;
  8831. for (var i = 0, n = listeners.length; i < n; ++i) {
  8832. listeners[i](loaded);
  8833. }
  8834. }.bind(this));
  8835. },
  8836. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  8837. this._readyCapability.promise.then(function () {
  8838. var listeners = this._progressiveReadListeners;
  8839. for (var i = 0, n = listeners.length; i < n; ++i) {
  8840. listeners[i](chunk);
  8841. }
  8842. }.bind(this));
  8843. },
  8844. transportReady: function PDFDataRangeTransport_transportReady() {
  8845. this._readyCapability.resolve();
  8846. },
  8847. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  8848. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8849. },
  8850. abort: function PDFDataRangeTransport_abort() {
  8851. }
  8852. };
  8853. return PDFDataRangeTransport;
  8854. }();
  8855. /**
  8856. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8857. * properties that can be read synchronously.
  8858. * @class
  8859. * @alias PDFDocumentProxy
  8860. */
  8861. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  8862. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8863. this.pdfInfo = pdfInfo;
  8864. this.transport = transport;
  8865. this.loadingTask = loadingTask;
  8866. }
  8867. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */
  8868. {
  8869. /**
  8870. * @return {number} Total number of pages the PDF contains.
  8871. */
  8872. get numPages() {
  8873. return this.pdfInfo.numPages;
  8874. },
  8875. /**
  8876. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8877. * unique.
  8878. */
  8879. get fingerprint() {
  8880. return this.pdfInfo.fingerprint;
  8881. },
  8882. /**
  8883. * @param {number} pageNumber The page number to get. The first page is 1.
  8884. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8885. * object.
  8886. */
  8887. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8888. return this.transport.getPage(pageNumber);
  8889. },
  8890. /**
  8891. * @param {{num: number, gen: number}} ref The page reference. Must have
  8892. * the 'num' and 'gen' properties.
  8893. * @return {Promise} A promise that is resolved with the page index that is
  8894. * associated with the reference.
  8895. */
  8896. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8897. return this.transport.getPageIndex(ref);
  8898. },
  8899. /**
  8900. * @return {Promise} A promise that is resolved with a lookup table for
  8901. * mapping named destinations to reference numbers.
  8902. *
  8903. * This can be slow for large documents: use getDestination instead
  8904. */
  8905. getDestinations: function PDFDocumentProxy_getDestinations() {
  8906. return this.transport.getDestinations();
  8907. },
  8908. /**
  8909. * @param {string} id The named destination to get.
  8910. * @return {Promise} A promise that is resolved with all information
  8911. * of the given named destination.
  8912. */
  8913. getDestination: function PDFDocumentProxy_getDestination(id) {
  8914. return this.transport.getDestination(id);
  8915. },
  8916. /**
  8917. * @return {Promise} A promise that is resolved with:
  8918. * an Array containing the pageLabels that correspond to the pageIndexes,
  8919. * or `null` when no pageLabels are present in the PDF file.
  8920. */
  8921. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8922. return this.transport.getPageLabels();
  8923. },
  8924. /**
  8925. * @return {Promise} A promise that is resolved with a lookup table for
  8926. * mapping named attachments to their content.
  8927. */
  8928. getAttachments: function PDFDocumentProxy_getAttachments() {
  8929. return this.transport.getAttachments();
  8930. },
  8931. /**
  8932. * @return {Promise} A promise that is resolved with an array of all the
  8933. * JavaScript strings in the name tree.
  8934. */
  8935. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8936. return this.transport.getJavaScript();
  8937. },
  8938. /**
  8939. * @return {Promise} A promise that is resolved with an {Array} that is a
  8940. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8941. * [
  8942. * {
  8943. * title: string,
  8944. * bold: boolean,
  8945. * italic: boolean,
  8946. * color: rgb Uint8Array,
  8947. * dest: dest obj,
  8948. * url: string,
  8949. * items: array of more items like this
  8950. * },
  8951. * ...
  8952. * ].
  8953. */
  8954. getOutline: function PDFDocumentProxy_getOutline() {
  8955. return this.transport.getOutline();
  8956. },
  8957. /**
  8958. * @return {Promise} A promise that is resolved with an {Object} that has
  8959. * info and metadata properties. Info is an {Object} filled with anything
  8960. * available in the information dictionary and similarly metadata is a
  8961. * {Metadata} object with information from the metadata section of the PDF.
  8962. */
  8963. getMetadata: function PDFDocumentProxy_getMetadata() {
  8964. return this.transport.getMetadata();
  8965. },
  8966. /**
  8967. * @return {Promise} A promise that is resolved with a TypedArray that has
  8968. * the raw data from the PDF.
  8969. */
  8970. getData: function PDFDocumentProxy_getData() {
  8971. return this.transport.getData();
  8972. },
  8973. /**
  8974. * @return {Promise} A promise that is resolved when the document's data
  8975. * is loaded. It is resolved with an {Object} that contains the length
  8976. * property that indicates size of the PDF data in bytes.
  8977. */
  8978. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8979. return this.transport.downloadInfoCapability.promise;
  8980. },
  8981. /**
  8982. * @return {Promise} A promise this is resolved with current stats about
  8983. * document structures (see {@link PDFDocumentStats}).
  8984. */
  8985. getStats: function PDFDocumentProxy_getStats() {
  8986. return this.transport.getStats();
  8987. },
  8988. /**
  8989. * Cleans up resources allocated by the document, e.g. created @font-face.
  8990. */
  8991. cleanup: function PDFDocumentProxy_cleanup() {
  8992. this.transport.startCleanup();
  8993. },
  8994. /**
  8995. * Destroys current document instance and terminates worker.
  8996. */
  8997. destroy: function PDFDocumentProxy_destroy() {
  8998. return this.loadingTask.destroy();
  8999. }
  9000. };
  9001. return PDFDocumentProxy;
  9002. }();
  9003. /**
  9004. * Page getTextContent parameters.
  9005. *
  9006. * @typedef {Object} getTextContentParameters
  9007. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  9008. * whitespace with standard spaces (0x20). The default value is `false`.
  9009. * @param {boolean} disableCombineTextItems - do not attempt to combine
  9010. * same line {@link TextItem}'s. The default value is `false`.
  9011. */
  9012. /**
  9013. * Page text content.
  9014. *
  9015. * @typedef {Object} TextContent
  9016. * @property {array} items - array of {@link TextItem}
  9017. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  9018. * name.
  9019. */
  9020. /**
  9021. * Page text content part.
  9022. *
  9023. * @typedef {Object} TextItem
  9024. * @property {string} str - text content.
  9025. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  9026. * @property {array} transform - transformation matrix.
  9027. * @property {number} width - width in device space.
  9028. * @property {number} height - height in device space.
  9029. * @property {string} fontName - font name used by pdf.js for converted font.
  9030. */
  9031. /**
  9032. * Text style.
  9033. *
  9034. * @typedef {Object} TextStyle
  9035. * @property {number} ascent - font ascent.
  9036. * @property {number} descent - font descent.
  9037. * @property {boolean} vertical - text is in vertical mode.
  9038. * @property {string} fontFamily - possible font family
  9039. */
  9040. /**
  9041. * Page annotation parameters.
  9042. *
  9043. * @typedef {Object} GetAnnotationsParameters
  9044. * @param {string} intent - Determines the annotations that will be fetched,
  9045. * can be either 'display' (viewable annotations) or 'print'
  9046. * (printable annotations).
  9047. * If the parameter is omitted, all annotations are fetched.
  9048. */
  9049. /**
  9050. * Page render parameters.
  9051. *
  9052. * @typedef {Object} RenderParameters
  9053. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  9054. * @property {PageViewport} viewport - Rendering viewport obtained by
  9055. * calling of PDFPage.getViewport method.
  9056. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  9057. * (default value is 'display').
  9058. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  9059. * interactive form elements are rendered in the display
  9060. * layer. If so, we do not render them on canvas as well.
  9061. * @property {Array} transform - (optional) Additional transform, applied
  9062. * just before viewport transform.
  9063. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  9064. * endLayout and appendImage functions.
  9065. * @property {function} continueCallback - (deprecated) A function that will be
  9066. * called each time the rendering is paused. To continue
  9067. * rendering call the function that is the first argument
  9068. * to the callback.
  9069. */
  9070. /**
  9071. * PDF page operator list.
  9072. *
  9073. * @typedef {Object} PDFOperatorList
  9074. * @property {Array} fnArray - Array containing the operator functions.
  9075. * @property {Array} argsArray - Array containing the arguments of the
  9076. * functions.
  9077. */
  9078. /**
  9079. * Proxy to a PDFPage in the worker thread.
  9080. * @class
  9081. * @alias PDFPageProxy
  9082. */
  9083. var PDFPageProxy = function PDFPageProxyClosure() {
  9084. function PDFPageProxy(pageIndex, pageInfo, transport) {
  9085. this.pageIndex = pageIndex;
  9086. this.pageInfo = pageInfo;
  9087. this.transport = transport;
  9088. this.stats = new StatTimer();
  9089. this.stats.enabled = getDefaultSetting('enableStats');
  9090. this.commonObjs = transport.commonObjs;
  9091. this.objs = new PDFObjects();
  9092. this.cleanupAfterRender = false;
  9093. this.pendingCleanup = false;
  9094. this.intentStates = Object.create(null);
  9095. this.destroyed = false;
  9096. }
  9097. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */
  9098. {
  9099. /**
  9100. * @return {number} Page number of the page. First page is 1.
  9101. */
  9102. get pageNumber() {
  9103. return this.pageIndex + 1;
  9104. },
  9105. /**
  9106. * @return {number} The number of degrees the page is rotated clockwise.
  9107. */
  9108. get rotate() {
  9109. return this.pageInfo.rotate;
  9110. },
  9111. /**
  9112. * @return {Object} The reference that points to this page. It has 'num' and
  9113. * 'gen' properties.
  9114. */
  9115. get ref() {
  9116. return this.pageInfo.ref;
  9117. },
  9118. /**
  9119. * @return {Array} An array of the visible portion of the PDF page in the
  9120. * user space units - [x1, y1, x2, y2].
  9121. */
  9122. get view() {
  9123. return this.pageInfo.view;
  9124. },
  9125. /**
  9126. * @param {number} scale The desired scale of the viewport.
  9127. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  9128. * defaults to the page rotation.
  9129. * @return {PageViewport} Contains 'width' and 'height' properties
  9130. * along with transforms required for rendering.
  9131. */
  9132. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  9133. if (arguments.length < 2) {
  9134. rotate = this.rotate;
  9135. }
  9136. return new PageViewport(this.view, scale, rotate, 0, 0);
  9137. },
  9138. /**
  9139. * @param {GetAnnotationsParameters} params - Annotation parameters.
  9140. * @return {Promise} A promise that is resolved with an {Array} of the
  9141. * annotation objects.
  9142. */
  9143. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  9144. var intent = params && params.intent || null;
  9145. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  9146. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  9147. this.annotationsIntent = intent;
  9148. }
  9149. return this.annotationsPromise;
  9150. },
  9151. /**
  9152. * Begins the process of rendering a page to the desired context.
  9153. * @param {RenderParameters} params Page render parameters.
  9154. * @return {RenderTask} An object that contains the promise, which
  9155. * is resolved when the page finishes rendering.
  9156. */
  9157. render: function PDFPageProxy_render(params) {
  9158. var stats = this.stats;
  9159. stats.time('Overall');
  9160. // If there was a pending destroy cancel it so no cleanup happens during
  9161. // this call to render.
  9162. this.pendingCleanup = false;
  9163. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  9164. var renderInteractiveForms = params.renderInteractiveForms === true ? true : /* Default */
  9165. false;
  9166. if (!this.intentStates[renderingIntent]) {
  9167. this.intentStates[renderingIntent] = Object.create(null);
  9168. }
  9169. var intentState = this.intentStates[renderingIntent];
  9170. // If there's no displayReadyCapability yet, then the operatorList
  9171. // was never requested before. Make the request and create the promise.
  9172. if (!intentState.displayReadyCapability) {
  9173. intentState.receivingOperatorList = true;
  9174. intentState.displayReadyCapability = createPromiseCapability();
  9175. intentState.operatorList = {
  9176. fnArray: [],
  9177. argsArray: [],
  9178. lastChunk: false
  9179. };
  9180. this.stats.time('Page Request');
  9181. this.transport.messageHandler.send('RenderPageRequest', {
  9182. pageIndex: this.pageNumber - 1,
  9183. intent: renderingIntent,
  9184. renderInteractiveForms: renderInteractiveForms
  9185. });
  9186. }
  9187. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  9188. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  9189. if (!intentState.renderTasks) {
  9190. intentState.renderTasks = [];
  9191. }
  9192. intentState.renderTasks.push(internalRenderTask);
  9193. var renderTask = internalRenderTask.task;
  9194. // Obsolete parameter support
  9195. if (params.continueCallback) {
  9196. deprecated('render is used with continueCallback parameter');
  9197. renderTask.onContinue = params.continueCallback;
  9198. }
  9199. var self = this;
  9200. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  9201. if (self.pendingCleanup) {
  9202. complete();
  9203. return;
  9204. }
  9205. stats.time('Rendering');
  9206. internalRenderTask.initializeGraphics(transparency);
  9207. internalRenderTask.operatorListChanged();
  9208. }, function pageDisplayReadPromiseError(reason) {
  9209. complete(reason);
  9210. });
  9211. function complete(error) {
  9212. var i = intentState.renderTasks.indexOf(internalRenderTask);
  9213. if (i >= 0) {
  9214. intentState.renderTasks.splice(i, 1);
  9215. }
  9216. if (self.cleanupAfterRender) {
  9217. self.pendingCleanup = true;
  9218. }
  9219. self._tryCleanup();
  9220. if (error) {
  9221. internalRenderTask.capability.reject(error);
  9222. } else {
  9223. internalRenderTask.capability.resolve();
  9224. }
  9225. stats.timeEnd('Rendering');
  9226. stats.timeEnd('Overall');
  9227. }
  9228. return renderTask;
  9229. },
  9230. /**
  9231. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  9232. * object that represents page's operator list.
  9233. */
  9234. getOperatorList: function PDFPageProxy_getOperatorList() {
  9235. function operatorListChanged() {
  9236. if (intentState.operatorList.lastChunk) {
  9237. intentState.opListReadCapability.resolve(intentState.operatorList);
  9238. var i = intentState.renderTasks.indexOf(opListTask);
  9239. if (i >= 0) {
  9240. intentState.renderTasks.splice(i, 1);
  9241. }
  9242. }
  9243. }
  9244. var renderingIntent = 'oplist';
  9245. if (!this.intentStates[renderingIntent]) {
  9246. this.intentStates[renderingIntent] = Object.create(null);
  9247. }
  9248. var intentState = this.intentStates[renderingIntent];
  9249. var opListTask;
  9250. if (!intentState.opListReadCapability) {
  9251. opListTask = {};
  9252. opListTask.operatorListChanged = operatorListChanged;
  9253. intentState.receivingOperatorList = true;
  9254. intentState.opListReadCapability = createPromiseCapability();
  9255. intentState.renderTasks = [];
  9256. intentState.renderTasks.push(opListTask);
  9257. intentState.operatorList = {
  9258. fnArray: [],
  9259. argsArray: [],
  9260. lastChunk: false
  9261. };
  9262. this.transport.messageHandler.send('RenderPageRequest', {
  9263. pageIndex: this.pageIndex,
  9264. intent: renderingIntent
  9265. });
  9266. }
  9267. return intentState.opListReadCapability.promise;
  9268. },
  9269. /**
  9270. * @param {getTextContentParameters} params - getTextContent parameters.
  9271. * @return {Promise} That is resolved a {@link TextContent}
  9272. * object that represent the page text content.
  9273. */
  9274. getTextContent: function PDFPageProxy_getTextContent(params) {
  9275. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  9276. pageIndex: this.pageNumber - 1,
  9277. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : /* Default */
  9278. false,
  9279. combineTextItems: params && params.disableCombineTextItems === true ? false : /* Default */
  9280. true
  9281. });
  9282. },
  9283. /**
  9284. * Destroys page object.
  9285. */
  9286. _destroy: function PDFPageProxy_destroy() {
  9287. this.destroyed = true;
  9288. this.transport.pageCache[this.pageIndex] = null;
  9289. var waitOn = [];
  9290. Object.keys(this.intentStates).forEach(function (intent) {
  9291. if (intent === 'oplist') {
  9292. // Avoid errors below, since the renderTasks are just stubs.
  9293. return;
  9294. }
  9295. var intentState = this.intentStates[intent];
  9296. intentState.renderTasks.forEach(function (renderTask) {
  9297. var renderCompleted = renderTask.capability.promise.catch(function () {
  9298. });
  9299. // ignoring failures
  9300. waitOn.push(renderCompleted);
  9301. renderTask.cancel();
  9302. });
  9303. }, this);
  9304. this.objs.clear();
  9305. this.annotationsPromise = null;
  9306. this.pendingCleanup = false;
  9307. return Promise.all(waitOn);
  9308. },
  9309. /**
  9310. * Cleans up resources allocated by the page. (deprecated)
  9311. */
  9312. destroy: function () {
  9313. deprecated('page destroy method, use cleanup() instead');
  9314. this.cleanup();
  9315. },
  9316. /**
  9317. * Cleans up resources allocated by the page.
  9318. */
  9319. cleanup: function PDFPageProxy_cleanup() {
  9320. this.pendingCleanup = true;
  9321. this._tryCleanup();
  9322. },
  9323. /**
  9324. * For internal use only. Attempts to clean up if rendering is in a state
  9325. * where that's possible.
  9326. * @ignore
  9327. */
  9328. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9329. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  9330. var intentState = this.intentStates[intent];
  9331. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  9332. }, this)) {
  9333. return;
  9334. }
  9335. Object.keys(this.intentStates).forEach(function (intent) {
  9336. delete this.intentStates[intent];
  9337. }, this);
  9338. this.objs.clear();
  9339. this.annotationsPromise = null;
  9340. this.pendingCleanup = false;
  9341. },
  9342. /**
  9343. * For internal use only.
  9344. * @ignore
  9345. */
  9346. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  9347. var intentState = this.intentStates[intent];
  9348. // TODO Refactor RenderPageRequest to separate rendering
  9349. // and operator list logic
  9350. if (intentState.displayReadyCapability) {
  9351. intentState.displayReadyCapability.resolve(transparency);
  9352. }
  9353. },
  9354. /**
  9355. * For internal use only.
  9356. * @ignore
  9357. */
  9358. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  9359. var intentState = this.intentStates[intent];
  9360. var i, ii;
  9361. // Add the new chunk to the current operator list.
  9362. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9363. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9364. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  9365. }
  9366. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9367. // Notify all the rendering tasks there are more operators to be consumed.
  9368. for (i = 0; i < intentState.renderTasks.length; i++) {
  9369. intentState.renderTasks[i].operatorListChanged();
  9370. }
  9371. if (operatorListChunk.lastChunk) {
  9372. intentState.receivingOperatorList = false;
  9373. this._tryCleanup();
  9374. }
  9375. }
  9376. };
  9377. return PDFPageProxy;
  9378. }();
  9379. /**
  9380. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9381. * WorkerTransport for them. If creation of a web worker is not possible,
  9382. * a "fake" worker will be used instead.
  9383. * @class
  9384. */
  9385. var PDFWorker = function PDFWorkerClosure() {
  9386. var nextFakeWorkerId = 0;
  9387. function getWorkerSrc() {
  9388. if (typeof workerSrc !== 'undefined') {
  9389. return workerSrc;
  9390. }
  9391. if (getDefaultSetting('workerSrc')) {
  9392. return getDefaultSetting('workerSrc');
  9393. }
  9394. if (pdfjsFilePath) {
  9395. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9396. }
  9397. error('No PDFJS.workerSrc specified');
  9398. }
  9399. var fakeWorkerFilesLoadedCapability;
  9400. // Loads worker code into main thread.
  9401. function setupFakeWorkerGlobal() {
  9402. var WorkerMessageHandler;
  9403. if (fakeWorkerFilesLoadedCapability) {
  9404. return fakeWorkerFilesLoadedCapability.promise;
  9405. }
  9406. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9407. var loader = fakeWorkerFilesLoader || function (callback) {
  9408. Util.loadScript(getWorkerSrc(), function () {
  9409. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9410. });
  9411. };
  9412. loader(fakeWorkerFilesLoadedCapability.resolve);
  9413. return fakeWorkerFilesLoadedCapability.promise;
  9414. }
  9415. function FakeWorkerPort(defer) {
  9416. this._listeners = [];
  9417. this._defer = defer;
  9418. this._deferred = Promise.resolve(undefined);
  9419. }
  9420. FakeWorkerPort.prototype = {
  9421. postMessage: function (obj, transfers) {
  9422. function cloneValue(value) {
  9423. // Trying to perform a structured clone close to the spec, including
  9424. // transfers.
  9425. if (typeof value !== 'object' || value === null) {
  9426. return value;
  9427. }
  9428. if (cloned.has(value)) {
  9429. // already cloned the object
  9430. return cloned.get(value);
  9431. }
  9432. var result;
  9433. var buffer;
  9434. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9435. // We found object with ArrayBuffer (typed array).
  9436. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9437. if (value === buffer) {
  9438. // Special case when we are faking typed arrays in compatibility.js.
  9439. result = value;
  9440. } else if (transferable) {
  9441. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  9442. } else {
  9443. result = new value.constructor(value);
  9444. }
  9445. cloned.set(value, result);
  9446. return result;
  9447. }
  9448. result = isArray(value) ? [] : {};
  9449. cloned.set(value, result);
  9450. // adding to cache now for cyclic references
  9451. // Cloning all value and object properties, however ignoring properties
  9452. // defined via getter.
  9453. for (var i in value) {
  9454. var desc, p = value;
  9455. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9456. p = Object.getPrototypeOf(p);
  9457. }
  9458. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  9459. continue;
  9460. }
  9461. result[i] = cloneValue(desc.value);
  9462. }
  9463. return result;
  9464. }
  9465. if (!this._defer) {
  9466. this._listeners.forEach(function (listener) {
  9467. listener.call(this, { data: obj });
  9468. }, this);
  9469. return;
  9470. }
  9471. var cloned = new WeakMap();
  9472. var e = { data: cloneValue(obj) };
  9473. this._deferred.then(function () {
  9474. this._listeners.forEach(function (listener) {
  9475. listener.call(this, e);
  9476. }, this);
  9477. }.bind(this));
  9478. },
  9479. addEventListener: function (name, listener) {
  9480. this._listeners.push(listener);
  9481. },
  9482. removeEventListener: function (name, listener) {
  9483. var i = this._listeners.indexOf(listener);
  9484. this._listeners.splice(i, 1);
  9485. },
  9486. terminate: function () {
  9487. this._listeners = [];
  9488. }
  9489. };
  9490. function createCDNWrapper(url) {
  9491. // We will rely on blob URL's property to specify origin.
  9492. // We want this function to fail in case if createObjectURL or Blob do not
  9493. // exist or fail for some reason -- our Worker creation will fail anyway.
  9494. var wrapper = 'importScripts(\'' + url + '\');';
  9495. return URL.createObjectURL(new Blob([wrapper]));
  9496. }
  9497. function PDFWorker(name) {
  9498. this.name = name;
  9499. this.destroyed = false;
  9500. this._readyCapability = createPromiseCapability();
  9501. this._port = null;
  9502. this._webWorker = null;
  9503. this._messageHandler = null;
  9504. this._initialize();
  9505. }
  9506. PDFWorker.prototype = /** @lends PDFWorker.prototype */
  9507. {
  9508. get promise() {
  9509. return this._readyCapability.promise;
  9510. },
  9511. get port() {
  9512. return this._port;
  9513. },
  9514. get messageHandler() {
  9515. return this._messageHandler;
  9516. },
  9517. _initialize: function PDFWorker_initialize() {
  9518. // If worker support isn't disabled explicit and the browser has worker
  9519. // support, create a new web worker and test if it/the browser fulfills
  9520. // all requirements to run parts of pdf.js in a web worker.
  9521. // Right now, the requirement is, that an Uint8Array is still an
  9522. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9523. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  9524. var workerSrc = getWorkerSrc();
  9525. try {
  9526. // Wraps workerSrc path into blob URL, if the former does not belong
  9527. // to the same origin.
  9528. if (!isSameOrigin(window.location.href, workerSrc)) {
  9529. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  9530. }
  9531. // Some versions of FF can't create a worker on localhost, see:
  9532. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9533. var worker = new Worker(workerSrc);
  9534. var messageHandler = new MessageHandler('main', 'worker', worker);
  9535. var terminateEarly = function () {
  9536. worker.removeEventListener('error', onWorkerError);
  9537. messageHandler.destroy();
  9538. worker.terminate();
  9539. if (this.destroyed) {
  9540. this._readyCapability.reject(new Error('Worker was destroyed'));
  9541. } else {
  9542. // Fall back to fake worker if the termination is caused by an
  9543. // error (e.g. NetworkError / SecurityError).
  9544. this._setupFakeWorker();
  9545. }
  9546. }.bind(this);
  9547. var onWorkerError = function (event) {
  9548. if (!this._webWorker) {
  9549. // Worker failed to initialize due to an error. Clean up and fall
  9550. // back to the fake worker.
  9551. terminateEarly();
  9552. }
  9553. }.bind(this);
  9554. worker.addEventListener('error', onWorkerError);
  9555. messageHandler.on('test', function PDFWorker_test(data) {
  9556. worker.removeEventListener('error', onWorkerError);
  9557. if (this.destroyed) {
  9558. terminateEarly();
  9559. return;
  9560. }
  9561. // worker was destroyed
  9562. var supportTypedArray = data && data.supportTypedArray;
  9563. if (supportTypedArray) {
  9564. this._messageHandler = messageHandler;
  9565. this._port = worker;
  9566. this._webWorker = worker;
  9567. if (!data.supportTransfers) {
  9568. isPostMessageTransfersDisabled = true;
  9569. }
  9570. this._readyCapability.resolve();
  9571. // Send global setting, e.g. verbosity level.
  9572. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  9573. } else {
  9574. this._setupFakeWorker();
  9575. messageHandler.destroy();
  9576. worker.terminate();
  9577. }
  9578. }.bind(this));
  9579. messageHandler.on('console_log', function (data) {
  9580. console.log.apply(console, data);
  9581. });
  9582. messageHandler.on('console_error', function (data) {
  9583. console.error.apply(console, data);
  9584. });
  9585. messageHandler.on('ready', function (data) {
  9586. worker.removeEventListener('error', onWorkerError);
  9587. if (this.destroyed) {
  9588. terminateEarly();
  9589. return;
  9590. }
  9591. // worker was destroyed
  9592. try {
  9593. sendTest();
  9594. } catch (e) {
  9595. // We need fallback to a faked worker.
  9596. this._setupFakeWorker();
  9597. }
  9598. }.bind(this));
  9599. var sendTest = function () {
  9600. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  9601. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9602. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9603. // typed array. Also, checking if we can use transfers.
  9604. try {
  9605. messageHandler.send('test', testObj, [testObj.buffer]);
  9606. } catch (ex) {
  9607. info('Cannot use postMessage transfers');
  9608. testObj[0] = 0;
  9609. messageHandler.send('test', testObj);
  9610. }
  9611. };
  9612. // It might take time for worker to initialize (especially when AMD
  9613. // loader is used). We will try to send test immediately, and then
  9614. // when 'ready' message will arrive. The worker shall process only
  9615. // first received 'test'.
  9616. sendTest();
  9617. return;
  9618. } catch (e) {
  9619. info('The worker has been disabled.');
  9620. }
  9621. }
  9622. // Either workers are disabled, not supported or have thrown an exception.
  9623. // Thus, we fallback to a faked worker.
  9624. this._setupFakeWorker();
  9625. },
  9626. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9627. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9628. warn('Setting up fake worker.');
  9629. isWorkerDisabled = true;
  9630. }
  9631. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9632. if (this.destroyed) {
  9633. this._readyCapability.reject(new Error('Worker was destroyed'));
  9634. return;
  9635. }
  9636. // We cannot turn on proper fake port simulation (this includes
  9637. // structured cloning) when typed arrays are not supported. Relying
  9638. // on a chance that messages will be sent in proper order.
  9639. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9640. var port = new FakeWorkerPort(isTypedArraysPresent);
  9641. this._port = port;
  9642. // All fake workers use the same port, making id unique.
  9643. var id = 'fake' + nextFakeWorkerId++;
  9644. // If the main thread is our worker, setup the handling for the
  9645. // messages -- the main thread sends to it self.
  9646. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9647. WorkerMessageHandler.setup(workerHandler, port);
  9648. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9649. this._messageHandler = messageHandler;
  9650. this._readyCapability.resolve();
  9651. }.bind(this));
  9652. },
  9653. /**
  9654. * Destroys the worker instance.
  9655. */
  9656. destroy: function PDFWorker_destroy() {
  9657. this.destroyed = true;
  9658. if (this._webWorker) {
  9659. // We need to terminate only web worker created resource.
  9660. this._webWorker.terminate();
  9661. this._webWorker = null;
  9662. }
  9663. this._port = null;
  9664. if (this._messageHandler) {
  9665. this._messageHandler.destroy();
  9666. this._messageHandler = null;
  9667. }
  9668. }
  9669. };
  9670. return PDFWorker;
  9671. }();
  9672. /**
  9673. * For internal use only.
  9674. * @ignore
  9675. */
  9676. var WorkerTransport = function WorkerTransportClosure() {
  9677. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9678. this.messageHandler = messageHandler;
  9679. this.loadingTask = loadingTask;
  9680. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9681. this.commonObjs = new PDFObjects();
  9682. this.fontLoader = new FontLoader(loadingTask.docId);
  9683. this.destroyed = false;
  9684. this.destroyCapability = null;
  9685. this.pageCache = [];
  9686. this.pagePromises = [];
  9687. this.downloadInfoCapability = createPromiseCapability();
  9688. this.setupMessageHandler();
  9689. }
  9690. WorkerTransport.prototype = {
  9691. destroy: function WorkerTransport_destroy() {
  9692. if (this.destroyCapability) {
  9693. return this.destroyCapability.promise;
  9694. }
  9695. this.destroyed = true;
  9696. this.destroyCapability = createPromiseCapability();
  9697. var waitOn = [];
  9698. // We need to wait for all renderings to be completed, e.g.
  9699. // timeout/rAF can take a long time.
  9700. this.pageCache.forEach(function (page) {
  9701. if (page) {
  9702. waitOn.push(page._destroy());
  9703. }
  9704. });
  9705. this.pageCache = [];
  9706. this.pagePromises = [];
  9707. var self = this;
  9708. // We also need to wait for the worker to finish its long running tasks.
  9709. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9710. waitOn.push(terminated);
  9711. Promise.all(waitOn).then(function () {
  9712. self.fontLoader.clear();
  9713. if (self.pdfDataRangeTransport) {
  9714. self.pdfDataRangeTransport.abort();
  9715. self.pdfDataRangeTransport = null;
  9716. }
  9717. if (self.messageHandler) {
  9718. self.messageHandler.destroy();
  9719. self.messageHandler = null;
  9720. }
  9721. self.destroyCapability.resolve();
  9722. }, this.destroyCapability.reject);
  9723. return this.destroyCapability.promise;
  9724. },
  9725. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  9726. var messageHandler = this.messageHandler;
  9727. function updatePassword(password) {
  9728. messageHandler.send('UpdatePassword', password);
  9729. }
  9730. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9731. if (pdfDataRangeTransport) {
  9732. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  9733. messageHandler.send('OnDataRange', {
  9734. begin: begin,
  9735. chunk: chunk
  9736. });
  9737. });
  9738. pdfDataRangeTransport.addProgressListener(function (loaded) {
  9739. messageHandler.send('OnDataProgress', { loaded: loaded });
  9740. });
  9741. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  9742. messageHandler.send('OnDataRange', { chunk: chunk });
  9743. });
  9744. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  9745. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9746. }, this);
  9747. }
  9748. messageHandler.on('GetDoc', function transportDoc(data) {
  9749. var pdfInfo = data.pdfInfo;
  9750. this.numPages = data.pdfInfo.numPages;
  9751. var loadingTask = this.loadingTask;
  9752. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9753. this.pdfDocument = pdfDocument;
  9754. loadingTask._capability.resolve(pdfDocument);
  9755. }, this);
  9756. messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
  9757. var loadingTask = this.loadingTask;
  9758. if (loadingTask.onPassword) {
  9759. return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
  9760. }
  9761. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9762. }, this);
  9763. messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
  9764. var loadingTask = this.loadingTask;
  9765. if (loadingTask.onPassword) {
  9766. return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
  9767. }
  9768. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9769. }, this);
  9770. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9771. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  9772. }, this);
  9773. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9774. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  9775. }, this);
  9776. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  9777. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  9778. }, this);
  9779. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  9780. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  9781. }, this);
  9782. messageHandler.on('DataLoaded', function transportPage(data) {
  9783. this.downloadInfoCapability.resolve(data);
  9784. }, this);
  9785. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9786. if (this.pdfDataRangeTransport) {
  9787. this.pdfDataRangeTransport.transportReady();
  9788. }
  9789. }, this);
  9790. messageHandler.on('StartRenderPage', function transportRender(data) {
  9791. if (this.destroyed) {
  9792. return;
  9793. }
  9794. // Ignore any pending requests if the worker was terminated.
  9795. var page = this.pageCache[data.pageIndex];
  9796. page.stats.timeEnd('Page Request');
  9797. page._startRenderPage(data.transparency, data.intent);
  9798. }, this);
  9799. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9800. if (this.destroyed) {
  9801. return;
  9802. }
  9803. // Ignore any pending requests if the worker was terminated.
  9804. var page = this.pageCache[data.pageIndex];
  9805. page._renderPageChunk(data.operatorList, data.intent);
  9806. }, this);
  9807. messageHandler.on('commonobj', function transportObj(data) {
  9808. if (this.destroyed) {
  9809. return;
  9810. }
  9811. // Ignore any pending requests if the worker was terminated.
  9812. var id = data[0];
  9813. var type = data[1];
  9814. if (this.commonObjs.hasData(id)) {
  9815. return;
  9816. }
  9817. switch (type) {
  9818. case 'Font':
  9819. var exportedData = data[2];
  9820. if ('error' in exportedData) {
  9821. var exportedError = exportedData.error;
  9822. warn('Error during font loading: ' + exportedError);
  9823. this.commonObjs.resolve(id, exportedError);
  9824. break;
  9825. }
  9826. var fontRegistry = null;
  9827. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  9828. fontRegistry = {
  9829. registerFont: function (font, url) {
  9830. globalScope['FontInspector'].fontAdded(font, url);
  9831. }
  9832. };
  9833. }
  9834. var font = new FontFaceObject(exportedData, {
  9835. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9836. disableFontFace: getDefaultSetting('disableFontFace'),
  9837. fontRegistry: fontRegistry
  9838. });
  9839. this.fontLoader.bind([font], function fontReady(fontObjs) {
  9840. this.commonObjs.resolve(id, font);
  9841. }.bind(this));
  9842. break;
  9843. case 'FontPath':
  9844. this.commonObjs.resolve(id, data[2]);
  9845. break;
  9846. default:
  9847. error('Got unknown common object type ' + type);
  9848. }
  9849. }, this);
  9850. messageHandler.on('obj', function transportObj(data) {
  9851. if (this.destroyed) {
  9852. return;
  9853. }
  9854. // Ignore any pending requests if the worker was terminated.
  9855. var id = data[0];
  9856. var pageIndex = data[1];
  9857. var type = data[2];
  9858. var pageProxy = this.pageCache[pageIndex];
  9859. var imageData;
  9860. if (pageProxy.objs.hasData(id)) {
  9861. return;
  9862. }
  9863. switch (type) {
  9864. case 'JpegStream':
  9865. imageData = data[3];
  9866. loadJpegStream(id, imageData, pageProxy.objs);
  9867. break;
  9868. case 'Image':
  9869. imageData = data[3];
  9870. pageProxy.objs.resolve(id, imageData);
  9871. // heuristics that will allow not to store large data
  9872. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9873. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9874. pageProxy.cleanupAfterRender = true;
  9875. }
  9876. break;
  9877. default:
  9878. error('Got unknown object type ' + type);
  9879. }
  9880. }, this);
  9881. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9882. if (this.destroyed) {
  9883. return;
  9884. }
  9885. // Ignore any pending requests if the worker was terminated.
  9886. var loadingTask = this.loadingTask;
  9887. if (loadingTask.onProgress) {
  9888. loadingTask.onProgress({
  9889. loaded: data.loaded,
  9890. total: data.total
  9891. });
  9892. }
  9893. }, this);
  9894. messageHandler.on('PageError', function transportError(data) {
  9895. if (this.destroyed) {
  9896. return;
  9897. }
  9898. // Ignore any pending requests if the worker was terminated.
  9899. var page = this.pageCache[data.pageNum - 1];
  9900. var intentState = page.intentStates[data.intent];
  9901. if (intentState.displayReadyCapability) {
  9902. intentState.displayReadyCapability.reject(data.error);
  9903. } else {
  9904. error(data.error);
  9905. }
  9906. if (intentState.operatorList) {
  9907. // Mark operator list as complete.
  9908. intentState.operatorList.lastChunk = true;
  9909. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9910. intentState.renderTasks[i].operatorListChanged();
  9911. }
  9912. }
  9913. }, this);
  9914. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  9915. if (this.destroyed) {
  9916. return;
  9917. }
  9918. // Ignore any pending requests if the worker was terminated.
  9919. var featureId = data.featureId;
  9920. var loadingTask = this.loadingTask;
  9921. if (loadingTask.onUnsupportedFeature) {
  9922. loadingTask.onUnsupportedFeature(featureId);
  9923. }
  9924. _UnsupportedManager.notify(featureId);
  9925. }, this);
  9926. messageHandler.on('JpegDecode', function (data) {
  9927. if (this.destroyed) {
  9928. return Promise.reject(new Error('Worker was destroyed'));
  9929. }
  9930. var imageUrl = data[0];
  9931. var components = data[1];
  9932. if (components !== 3 && components !== 1) {
  9933. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  9934. }
  9935. return new Promise(function (resolve, reject) {
  9936. var img = new Image();
  9937. img.onload = function () {
  9938. var width = img.width;
  9939. var height = img.height;
  9940. var size = width * height;
  9941. var rgbaLength = size * 4;
  9942. var buf = new Uint8Array(size * components);
  9943. var tmpCanvas = createScratchCanvas(width, height);
  9944. var tmpCtx = tmpCanvas.getContext('2d');
  9945. tmpCtx.drawImage(img, 0, 0);
  9946. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9947. var i, j;
  9948. if (components === 3) {
  9949. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9950. buf[j] = data[i];
  9951. buf[j + 1] = data[i + 1];
  9952. buf[j + 2] = data[i + 2];
  9953. }
  9954. } else if (components === 1) {
  9955. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9956. buf[j] = data[i];
  9957. }
  9958. }
  9959. resolve({
  9960. data: buf,
  9961. width: width,
  9962. height: height
  9963. });
  9964. };
  9965. img.onerror = function () {
  9966. reject(new Error('JpegDecode failed to load image'));
  9967. };
  9968. img.src = imageUrl;
  9969. });
  9970. }, this);
  9971. },
  9972. getData: function WorkerTransport_getData() {
  9973. return this.messageHandler.sendWithPromise('GetData', null);
  9974. },
  9975. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9976. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9977. return Promise.reject(new Error('Invalid page request'));
  9978. }
  9979. var pageIndex = pageNumber - 1;
  9980. if (pageIndex in this.pagePromises) {
  9981. return this.pagePromises[pageIndex];
  9982. }
  9983. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  9984. if (this.destroyed) {
  9985. throw new Error('Transport destroyed');
  9986. }
  9987. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9988. this.pageCache[pageIndex] = page;
  9989. return page;
  9990. }.bind(this));
  9991. this.pagePromises[pageIndex] = promise;
  9992. return promise;
  9993. },
  9994. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9995. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  9996. return Promise.reject(new Error(reason));
  9997. });
  9998. },
  9999. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  10000. return this.messageHandler.sendWithPromise('GetAnnotations', {
  10001. pageIndex: pageIndex,
  10002. intent: intent
  10003. });
  10004. },
  10005. getDestinations: function WorkerTransport_getDestinations() {
  10006. return this.messageHandler.sendWithPromise('GetDestinations', null);
  10007. },
  10008. getDestination: function WorkerTransport_getDestination(id) {
  10009. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  10010. },
  10011. getPageLabels: function WorkerTransport_getPageLabels() {
  10012. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  10013. },
  10014. getAttachments: function WorkerTransport_getAttachments() {
  10015. return this.messageHandler.sendWithPromise('GetAttachments', null);
  10016. },
  10017. getJavaScript: function WorkerTransport_getJavaScript() {
  10018. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  10019. },
  10020. getOutline: function WorkerTransport_getOutline() {
  10021. return this.messageHandler.sendWithPromise('GetOutline', null);
  10022. },
  10023. getMetadata: function WorkerTransport_getMetadata() {
  10024. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  10025. return {
  10026. info: results[0],
  10027. metadata: results[1] ? new Metadata(results[1]) : null
  10028. };
  10029. });
  10030. },
  10031. getStats: function WorkerTransport_getStats() {
  10032. return this.messageHandler.sendWithPromise('GetStats', null);
  10033. },
  10034. startCleanup: function WorkerTransport_startCleanup() {
  10035. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  10036. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  10037. var page = this.pageCache[i];
  10038. if (page) {
  10039. page.cleanup();
  10040. }
  10041. }
  10042. this.commonObjs.clear();
  10043. this.fontLoader.clear();
  10044. }.bind(this));
  10045. }
  10046. };
  10047. return WorkerTransport;
  10048. }();
  10049. /**
  10050. * A PDF document and page is built of many objects. E.g. there are objects
  10051. * for fonts, images, rendering code and such. These objects might get processed
  10052. * inside of a worker. The `PDFObjects` implements some basic functions to
  10053. * manage these objects.
  10054. * @ignore
  10055. */
  10056. var PDFObjects = function PDFObjectsClosure() {
  10057. function PDFObjects() {
  10058. this.objs = Object.create(null);
  10059. }
  10060. PDFObjects.prototype = {
  10061. /**
  10062. * Internal function.
  10063. * Ensures there is an object defined for `objId`.
  10064. */
  10065. ensureObj: function PDFObjects_ensureObj(objId) {
  10066. if (this.objs[objId]) {
  10067. return this.objs[objId];
  10068. }
  10069. var obj = {
  10070. capability: createPromiseCapability(),
  10071. data: null,
  10072. resolved: false
  10073. };
  10074. this.objs[objId] = obj;
  10075. return obj;
  10076. },
  10077. /**
  10078. * If called *without* callback, this returns the data of `objId` but the
  10079. * object needs to be resolved. If it isn't, this function throws.
  10080. *
  10081. * If called *with* a callback, the callback is called with the data of the
  10082. * object once the object is resolved. That means, if you call this
  10083. * function and the object is already resolved, the callback gets called
  10084. * right away.
  10085. */
  10086. get: function PDFObjects_get(objId, callback) {
  10087. // If there is a callback, then the get can be async and the object is
  10088. // not required to be resolved right now
  10089. if (callback) {
  10090. this.ensureObj(objId).capability.promise.then(callback);
  10091. return null;
  10092. }
  10093. // If there isn't a callback, the user expects to get the resolved data
  10094. // directly.
  10095. var obj = this.objs[objId];
  10096. // If there isn't an object yet or the object isn't resolved, then the
  10097. // data isn't ready yet!
  10098. if (!obj || !obj.resolved) {
  10099. error('Requesting object that isn\'t resolved yet ' + objId);
  10100. }
  10101. return obj.data;
  10102. },
  10103. /**
  10104. * Resolves the object `objId` with optional `data`.
  10105. */
  10106. resolve: function PDFObjects_resolve(objId, data) {
  10107. var obj = this.ensureObj(objId);
  10108. obj.resolved = true;
  10109. obj.data = data;
  10110. obj.capability.resolve(data);
  10111. },
  10112. isResolved: function PDFObjects_isResolved(objId) {
  10113. var objs = this.objs;
  10114. if (!objs[objId]) {
  10115. return false;
  10116. } else {
  10117. return objs[objId].resolved;
  10118. }
  10119. },
  10120. hasData: function PDFObjects_hasData(objId) {
  10121. return this.isResolved(objId);
  10122. },
  10123. /**
  10124. * Returns the data of `objId` if object exists, null otherwise.
  10125. */
  10126. getData: function PDFObjects_getData(objId) {
  10127. var objs = this.objs;
  10128. if (!objs[objId] || !objs[objId].resolved) {
  10129. return null;
  10130. } else {
  10131. return objs[objId].data;
  10132. }
  10133. },
  10134. clear: function PDFObjects_clear() {
  10135. this.objs = Object.create(null);
  10136. }
  10137. };
  10138. return PDFObjects;
  10139. }();
  10140. /**
  10141. * Allows controlling of the rendering tasks.
  10142. * @class
  10143. * @alias RenderTask
  10144. */
  10145. var RenderTask = function RenderTaskClosure() {
  10146. function RenderTask(internalRenderTask) {
  10147. this._internalRenderTask = internalRenderTask;
  10148. /**
  10149. * Callback for incremental rendering -- a function that will be called
  10150. * each time the rendering is paused. To continue rendering call the
  10151. * function that is the first argument to the callback.
  10152. * @type {function}
  10153. */
  10154. this.onContinue = null;
  10155. }
  10156. RenderTask.prototype = /** @lends RenderTask.prototype */
  10157. {
  10158. /**
  10159. * Promise for rendering task completion.
  10160. * @return {Promise}
  10161. */
  10162. get promise() {
  10163. return this._internalRenderTask.capability.promise;
  10164. },
  10165. /**
  10166. * Cancels the rendering task. If the task is currently rendering it will
  10167. * not be cancelled until graphics pauses with a timeout. The promise that
  10168. * this object extends will resolved when cancelled.
  10169. */
  10170. cancel: function RenderTask_cancel() {
  10171. this._internalRenderTask.cancel();
  10172. },
  10173. /**
  10174. * Registers callbacks to indicate the rendering task completion.
  10175. *
  10176. * @param {function} onFulfilled The callback for the rendering completion.
  10177. * @param {function} onRejected The callback for the rendering failure.
  10178. * @return {Promise} A promise that is resolved after the onFulfilled or
  10179. * onRejected callback.
  10180. */
  10181. then: function RenderTask_then(onFulfilled, onRejected) {
  10182. return this.promise.then.apply(this.promise, arguments);
  10183. }
  10184. };
  10185. return RenderTask;
  10186. }();
  10187. /**
  10188. * For internal use only.
  10189. * @ignore
  10190. */
  10191. var InternalRenderTask = function InternalRenderTaskClosure() {
  10192. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  10193. this.callback = callback;
  10194. this.params = params;
  10195. this.objs = objs;
  10196. this.commonObjs = commonObjs;
  10197. this.operatorListIdx = null;
  10198. this.operatorList = operatorList;
  10199. this.pageNumber = pageNumber;
  10200. this.running = false;
  10201. this.graphicsReadyCallback = null;
  10202. this.graphicsReady = false;
  10203. this.useRequestAnimationFrame = false;
  10204. this.cancelled = false;
  10205. this.capability = createPromiseCapability();
  10206. this.task = new RenderTask(this);
  10207. // caching this-bound methods
  10208. this._continueBound = this._continue.bind(this);
  10209. this._scheduleNextBound = this._scheduleNext.bind(this);
  10210. this._nextBound = this._next.bind(this);
  10211. }
  10212. InternalRenderTask.prototype = {
  10213. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  10214. if (this.cancelled) {
  10215. return;
  10216. }
  10217. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  10218. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  10219. this.stepper.init(this.operatorList);
  10220. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  10221. }
  10222. var params = this.params;
  10223. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  10224. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  10225. this.operatorListIdx = 0;
  10226. this.graphicsReady = true;
  10227. if (this.graphicsReadyCallback) {
  10228. this.graphicsReadyCallback();
  10229. }
  10230. },
  10231. cancel: function InternalRenderTask_cancel() {
  10232. this.running = false;
  10233. this.cancelled = true;
  10234. this.callback('cancelled');
  10235. },
  10236. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  10237. if (!this.graphicsReady) {
  10238. if (!this.graphicsReadyCallback) {
  10239. this.graphicsReadyCallback = this._continueBound;
  10240. }
  10241. return;
  10242. }
  10243. if (this.stepper) {
  10244. this.stepper.updateOperatorList(this.operatorList);
  10245. }
  10246. if (this.running) {
  10247. return;
  10248. }
  10249. this._continue();
  10250. },
  10251. _continue: function InternalRenderTask__continue() {
  10252. this.running = true;
  10253. if (this.cancelled) {
  10254. return;
  10255. }
  10256. if (this.task.onContinue) {
  10257. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10258. } else {
  10259. this._scheduleNext();
  10260. }
  10261. },
  10262. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10263. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10264. window.requestAnimationFrame(this._nextBound);
  10265. } else {
  10266. Promise.resolve(undefined).then(this._nextBound);
  10267. }
  10268. },
  10269. _next: function InternalRenderTask__next() {
  10270. if (this.cancelled) {
  10271. return;
  10272. }
  10273. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  10274. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10275. this.running = false;
  10276. if (this.operatorList.lastChunk) {
  10277. this.gfx.endDrawing();
  10278. this.callback();
  10279. }
  10280. }
  10281. }
  10282. };
  10283. return InternalRenderTask;
  10284. }();
  10285. /**
  10286. * (Deprecated) Global observer of unsupported feature usages. Use
  10287. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10288. */
  10289. var _UnsupportedManager = function UnsupportedManagerClosure() {
  10290. var listeners = [];
  10291. return {
  10292. listen: function (cb) {
  10293. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10294. listeners.push(cb);
  10295. },
  10296. notify: function (featureId) {
  10297. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10298. listeners[i](featureId);
  10299. }
  10300. }
  10301. };
  10302. }();
  10303. if (typeof pdfjsVersion !== 'undefined') {
  10304. exports.version = pdfjsVersion;
  10305. }
  10306. if (typeof pdfjsBuild !== 'undefined') {
  10307. exports.build = pdfjsBuild;
  10308. }
  10309. exports.getDocument = getDocument;
  10310. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10311. exports.PDFWorker = PDFWorker;
  10312. exports.PDFDocumentProxy = PDFDocumentProxy;
  10313. exports.PDFPageProxy = PDFPageProxy;
  10314. exports._UnsupportedManager = _UnsupportedManager;
  10315. }));
  10316. (function (root, factory) {
  10317. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10318. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  10319. var globalScope = sharedUtil.globalScope;
  10320. var deprecated = sharedUtil.deprecated;
  10321. var warn = sharedUtil.warn;
  10322. var LinkTarget = displayDOMUtils.LinkTarget;
  10323. var isWorker = typeof window === 'undefined';
  10324. // The global PDFJS object is now deprecated and will not be supported in
  10325. // the future. The members below are maintained for backward compatibility
  10326. // and shall not be extended or modified. If the global.js is included as
  10327. // a module, we will create a global PDFJS object instance or use existing.
  10328. if (!globalScope.PDFJS) {
  10329. globalScope.PDFJS = {};
  10330. }
  10331. var PDFJS = globalScope.PDFJS;
  10332. if (typeof pdfjsVersion !== 'undefined') {
  10333. PDFJS.version = pdfjsVersion;
  10334. }
  10335. if (typeof pdfjsBuild !== 'undefined') {
  10336. PDFJS.build = pdfjsBuild;
  10337. }
  10338. PDFJS.pdfBug = false;
  10339. if (PDFJS.verbosity !== undefined) {
  10340. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10341. }
  10342. delete PDFJS.verbosity;
  10343. Object.defineProperty(PDFJS, 'verbosity', {
  10344. get: function () {
  10345. return sharedUtil.getVerbosityLevel();
  10346. },
  10347. set: function (level) {
  10348. sharedUtil.setVerbosityLevel(level);
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10354. PDFJS.OPS = sharedUtil.OPS;
  10355. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10356. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10357. PDFJS.shadow = sharedUtil.shadow;
  10358. PDFJS.createBlob = sharedUtil.createBlob;
  10359. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10360. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  10361. };
  10362. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10363. configurable: true,
  10364. get: function PDFJS_isLittleEndian() {
  10365. var value = sharedUtil.isLittleEndian();
  10366. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10367. }
  10368. });
  10369. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10370. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10371. PDFJS.PasswordException = sharedUtil.PasswordException;
  10372. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10373. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10374. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10375. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10376. PDFJS.Util = sharedUtil.Util;
  10377. PDFJS.PageViewport = sharedUtil.PageViewport;
  10378. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10379. /**
  10380. * The maximum allowed image size in total pixels e.g. width * height. Images
  10381. * above this value will not be drawn. Use -1 for no limit.
  10382. * @var {number}
  10383. */
  10384. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  10385. /**
  10386. * The url of where the predefined Adobe CMaps are located. Include trailing
  10387. * slash.
  10388. * @var {string}
  10389. */
  10390. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  10391. /**
  10392. * Specifies if CMaps are binary packed.
  10393. * @var {boolean}
  10394. */
  10395. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10396. /**
  10397. * By default fonts are converted to OpenType fonts and loaded via font face
  10398. * rules. If disabled, the font will be rendered using a built in font
  10399. * renderer that constructs the glyphs with primitive path commands.
  10400. * @var {boolean}
  10401. */
  10402. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  10403. /**
  10404. * Path for image resources, mainly for annotation icons. Include trailing
  10405. * slash.
  10406. * @var {string}
  10407. */
  10408. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  10409. /**
  10410. * Disable the web worker and run all code on the main thread. This will
  10411. * happen automatically if the browser doesn't support workers or sending
  10412. * typed arrays to workers.
  10413. * @var {boolean}
  10414. */
  10415. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  10416. /**
  10417. * Path and filename of the worker file. Required when the worker is enabled
  10418. * in development mode. If unspecified in the production build, the worker
  10419. * will be loaded based on the location of the pdf.js file. It is recommended
  10420. * that the workerSrc is set in a custom application to prevent issues caused
  10421. * by third-party frameworks and libraries.
  10422. * @var {string}
  10423. */
  10424. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  10425. /**
  10426. * Disable range request loading of PDF files. When enabled and if the server
  10427. * supports partial content requests then the PDF will be fetched in chunks.
  10428. * Enabled (false) by default.
  10429. * @var {boolean}
  10430. */
  10431. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  10432. /**
  10433. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10434. * in chunks. This default behavior can be disabled.
  10435. * @var {boolean}
  10436. */
  10437. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  10438. /**
  10439. * Disable pre-fetching of PDF file data. When range requests are enabled
  10440. * PDF.js will automatically keep fetching more data even if it isn't needed
  10441. * to display the current page. This default behavior can be disabled.
  10442. *
  10443. * NOTE: It is also necessary to disable streaming, see above,
  10444. * in order for disabling of pre-fetching to work correctly.
  10445. * @var {boolean}
  10446. */
  10447. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  10448. /**
  10449. * Enables special hooks for debugging PDF.js.
  10450. * @var {boolean}
  10451. */
  10452. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  10453. /**
  10454. * Enables transfer usage in postMessage for ArrayBuffers.
  10455. * @var {boolean}
  10456. */
  10457. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  10458. /**
  10459. * Disables URL.createObjectURL usage.
  10460. * @var {boolean}
  10461. */
  10462. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  10463. /**
  10464. * Disables WebGL usage.
  10465. * @var {boolean}
  10466. */
  10467. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  10468. /**
  10469. * Specifies the |target| attribute for external links.
  10470. * The constants from PDFJS.LinkTarget should be used:
  10471. * - NONE [default]
  10472. * - SELF
  10473. * - BLANK
  10474. * - PARENT
  10475. * - TOP
  10476. * @var {number}
  10477. */
  10478. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  10479. /**
  10480. * Specifies the |rel| attribute for external links. Defaults to stripping
  10481. * the referrer.
  10482. * @var {string}
  10483. */
  10484. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel;
  10485. /**
  10486. * Determines if we can eval strings as JS. Primarily used to improve
  10487. * performance for font rendering.
  10488. * @var {boolean}
  10489. */
  10490. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  10491. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10492. delete PDFJS.openExternalLinksInNewWindow;
  10493. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10494. get: function () {
  10495. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10496. },
  10497. set: function (value) {
  10498. if (value) {
  10499. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10500. }
  10501. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10502. warn('PDFJS.externalLinkTarget is already initialized');
  10503. return;
  10504. }
  10505. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10506. },
  10507. enumerable: true,
  10508. configurable: true
  10509. });
  10510. if (savedOpenExternalLinksInNewWindow) {
  10511. /**
  10512. * (Deprecated) Opens external links in a new window if enabled.
  10513. * The default behavior opens external links in the PDF.js window.
  10514. *
  10515. * NOTE: This property has been deprecated, please use
  10516. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10517. * @var {boolean}
  10518. */
  10519. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10520. }
  10521. PDFJS.getDocument = displayAPI.getDocument;
  10522. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10523. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10524. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10525. configurable: true,
  10526. get: function PDFJS_hasCanvasTypedArrays() {
  10527. var value = displayDOMUtils.hasCanvasTypedArrays();
  10528. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10529. }
  10530. });
  10531. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10532. PDFJS.LinkTarget = LinkTarget;
  10533. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10534. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10535. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10536. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10537. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10538. PDFJS.Metadata = displayMetadata.Metadata;
  10539. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10540. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10541. exports.globalScope = globalScope;
  10542. exports.isWorker = isWorker;
  10543. exports.PDFJS = globalScope.PDFJS;
  10544. }));
  10545. }.call(pdfjsLibs));
  10546. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10547. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10548. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10549. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10550. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10551. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10552. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10553. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10554. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10555. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10556. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10557. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10558. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10559. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10560. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10561. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10562. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10563. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10564. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10565. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10566. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10567. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10568. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10569. }));