2
0

pdf.js 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. // Initializing PDFJS global object (if still undefined)
  19. if (typeof PDFJS === 'undefined') {
  20. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  21. }
  22. PDFJS.version = '1.0.355';
  23. PDFJS.build = '2efbdfe';
  24. (function pdfjsWrapper() {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  28. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  29. /* Copyright 2012 Mozilla Foundation
  30. *
  31. * Licensed under the Apache License, Version 2.0 (the "License");
  32. * you may not use this file except in compliance with the License.
  33. * You may obtain a copy of the License at
  34. *
  35. * http://www.apache.org/licenses/LICENSE-2.0
  36. *
  37. * Unless required by applicable law or agreed to in writing, software
  38. * distributed under the License is distributed on an "AS IS" BASIS,
  39. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. * See the License for the specific language governing permissions and
  41. * limitations under the License.
  42. */
  43. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  44. Promise */
  45. 'use strict';
  46. var globalScope = (typeof window === 'undefined') ? this : window;
  47. var isWorker = (typeof window == 'undefined');
  48. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  49. var TextRenderingMode = {
  50. FILL: 0,
  51. STROKE: 1,
  52. FILL_STROKE: 2,
  53. INVISIBLE: 3,
  54. FILL_ADD_TO_PATH: 4,
  55. STROKE_ADD_TO_PATH: 5,
  56. FILL_STROKE_ADD_TO_PATH: 6,
  57. ADD_TO_PATH: 7,
  58. FILL_STROKE_MASK: 3,
  59. ADD_TO_PATH_FLAG: 4
  60. };
  61. var ImageKind = {
  62. GRAYSCALE_1BPP: 1,
  63. RGB_24BPP: 2,
  64. RGBA_32BPP: 3
  65. };
  66. // The global PDFJS object exposes the API
  67. // In production, it will be declared outside a global wrapper
  68. // In development, it will be declared here
  69. if (!globalScope.PDFJS) {
  70. globalScope.PDFJS = {};
  71. }
  72. globalScope.PDFJS.pdfBug = false;
  73. PDFJS.VERBOSITY_LEVELS = {
  74. errors: 0,
  75. warnings: 1,
  76. infos: 5
  77. };
  78. // All the possible operations for an operator list.
  79. var OPS = PDFJS.OPS = {
  80. // Intentionally start from 1 so it is easy to spot bad operators that will be
  81. // 0's.
  82. dependency: 1,
  83. setLineWidth: 2,
  84. setLineCap: 3,
  85. setLineJoin: 4,
  86. setMiterLimit: 5,
  87. setDash: 6,
  88. setRenderingIntent: 7,
  89. setFlatness: 8,
  90. setGState: 9,
  91. save: 10,
  92. restore: 11,
  93. transform: 12,
  94. moveTo: 13,
  95. lineTo: 14,
  96. curveTo: 15,
  97. curveTo2: 16,
  98. curveTo3: 17,
  99. closePath: 18,
  100. rectangle: 19,
  101. stroke: 20,
  102. closeStroke: 21,
  103. fill: 22,
  104. eoFill: 23,
  105. fillStroke: 24,
  106. eoFillStroke: 25,
  107. closeFillStroke: 26,
  108. closeEOFillStroke: 27,
  109. endPath: 28,
  110. clip: 29,
  111. eoClip: 30,
  112. beginText: 31,
  113. endText: 32,
  114. setCharSpacing: 33,
  115. setWordSpacing: 34,
  116. setHScale: 35,
  117. setLeading: 36,
  118. setFont: 37,
  119. setTextRenderingMode: 38,
  120. setTextRise: 39,
  121. moveText: 40,
  122. setLeadingMoveText: 41,
  123. setTextMatrix: 42,
  124. nextLine: 43,
  125. showText: 44,
  126. showSpacedText: 45,
  127. nextLineShowText: 46,
  128. nextLineSetSpacingShowText: 47,
  129. setCharWidth: 48,
  130. setCharWidthAndBounds: 49,
  131. setStrokeColorSpace: 50,
  132. setFillColorSpace: 51,
  133. setStrokeColor: 52,
  134. setStrokeColorN: 53,
  135. setFillColor: 54,
  136. setFillColorN: 55,
  137. setStrokeGray: 56,
  138. setFillGray: 57,
  139. setStrokeRGBColor: 58,
  140. setFillRGBColor: 59,
  141. setStrokeCMYKColor: 60,
  142. setFillCMYKColor: 61,
  143. shadingFill: 62,
  144. beginInlineImage: 63,
  145. beginImageData: 64,
  146. endInlineImage: 65,
  147. paintXObject: 66,
  148. markPoint: 67,
  149. markPointProps: 68,
  150. beginMarkedContent: 69,
  151. beginMarkedContentProps: 70,
  152. endMarkedContent: 71,
  153. beginCompat: 72,
  154. endCompat: 73,
  155. paintFormXObjectBegin: 74,
  156. paintFormXObjectEnd: 75,
  157. beginGroup: 76,
  158. endGroup: 77,
  159. beginAnnotations: 78,
  160. endAnnotations: 79,
  161. beginAnnotation: 80,
  162. endAnnotation: 81,
  163. paintJpegXObject: 82,
  164. paintImageMaskXObject: 83,
  165. paintImageMaskXObjectGroup: 84,
  166. paintImageXObject: 85,
  167. paintInlineImageXObject: 86,
  168. paintInlineImageXObjectGroup: 87,
  169. paintImageXObjectRepeat: 88,
  170. paintImageMaskXObjectRepeat: 89,
  171. paintSolidColorImageMask: 90,
  172. constructPath: 91
  173. };
  174. // A notice for devs. These are good for things that are helpful to devs, such
  175. // as warning that Workers were disabled, which is important to devs but not
  176. // end users.
  177. function info(msg) {
  178. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  179. console.log('Info: ' + msg);
  180. }
  181. }
  182. // Non-fatal warnings.
  183. function warn(msg) {
  184. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  185. console.log('Warning: ' + msg);
  186. }
  187. }
  188. // Fatal errors that should trigger the fallback UI and halt execution by
  189. // throwing an exception.
  190. function error(msg) {
  191. // If multiple arguments were passed, pass them all to the log function.
  192. if (arguments.length > 1) {
  193. var logArguments = ['Error:'];
  194. logArguments.push.apply(logArguments, arguments);
  195. console.log.apply(console, logArguments);
  196. // Join the arguments into a single string for the lines below.
  197. msg = [].join.call(arguments, ' ');
  198. } else {
  199. console.log('Error: ' + msg);
  200. }
  201. console.log(backtrace());
  202. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  203. throw new Error(msg);
  204. }
  205. function backtrace() {
  206. try {
  207. throw new Error();
  208. } catch (e) {
  209. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  210. }
  211. }
  212. function assert(cond, msg) {
  213. if (!cond) {
  214. error(msg);
  215. }
  216. }
  217. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  218. unknown: 'unknown',
  219. forms: 'forms',
  220. javaScript: 'javaScript',
  221. smask: 'smask',
  222. shadingPattern: 'shadingPattern',
  223. font: 'font'
  224. };
  225. var UnsupportedManager = PDFJS.UnsupportedManager =
  226. (function UnsupportedManagerClosure() {
  227. var listeners = [];
  228. return {
  229. listen: function (cb) {
  230. listeners.push(cb);
  231. },
  232. notify: function (featureId) {
  233. warn('Unsupported feature "' + featureId + '"');
  234. for (var i = 0, ii = listeners.length; i < ii; i++) {
  235. listeners[i](featureId);
  236. }
  237. }
  238. };
  239. })();
  240. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  241. // absolute URL, it will be returned as is.
  242. function combineUrl(baseUrl, url) {
  243. if (!url) {
  244. return baseUrl;
  245. }
  246. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  247. return url;
  248. }
  249. var i;
  250. if (url.charAt(0) == '/') {
  251. // absolute path
  252. i = baseUrl.indexOf('://');
  253. if (url.charAt(1) === '/') {
  254. ++i;
  255. } else {
  256. i = baseUrl.indexOf('/', i + 3);
  257. }
  258. return baseUrl.substring(0, i) + url;
  259. } else {
  260. // relative path
  261. var pathLength = baseUrl.length;
  262. i = baseUrl.lastIndexOf('#');
  263. pathLength = i >= 0 ? i : pathLength;
  264. i = baseUrl.lastIndexOf('?', pathLength);
  265. pathLength = i >= 0 ? i : pathLength;
  266. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  267. return baseUrl.substring(0, prefixLength + 1) + url;
  268. }
  269. }
  270. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  271. function isValidUrl(url, allowRelative) {
  272. if (!url) {
  273. return false;
  274. }
  275. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  276. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  277. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  278. if (!protocol) {
  279. return allowRelative;
  280. }
  281. protocol = protocol[0].toLowerCase();
  282. switch (protocol) {
  283. case 'http':
  284. case 'https':
  285. case 'ftp':
  286. case 'mailto':
  287. return true;
  288. default:
  289. return false;
  290. }
  291. }
  292. PDFJS.isValidUrl = isValidUrl;
  293. function shadow(obj, prop, value) {
  294. Object.defineProperty(obj, prop, { value: value,
  295. enumerable: true,
  296. configurable: true,
  297. writable: false });
  298. return value;
  299. }
  300. var PasswordResponses = PDFJS.PasswordResponses = {
  301. NEED_PASSWORD: 1,
  302. INCORRECT_PASSWORD: 2
  303. };
  304. var PasswordException = (function PasswordExceptionClosure() {
  305. function PasswordException(msg, code) {
  306. this.name = 'PasswordException';
  307. this.message = msg;
  308. this.code = code;
  309. }
  310. PasswordException.prototype = new Error();
  311. PasswordException.constructor = PasswordException;
  312. return PasswordException;
  313. })();
  314. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  315. function UnknownErrorException(msg, details) {
  316. this.name = 'UnknownErrorException';
  317. this.message = msg;
  318. this.details = details;
  319. }
  320. UnknownErrorException.prototype = new Error();
  321. UnknownErrorException.constructor = UnknownErrorException;
  322. return UnknownErrorException;
  323. })();
  324. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  325. function InvalidPDFException(msg) {
  326. this.name = 'InvalidPDFException';
  327. this.message = msg;
  328. }
  329. InvalidPDFException.prototype = new Error();
  330. InvalidPDFException.constructor = InvalidPDFException;
  331. return InvalidPDFException;
  332. })();
  333. var MissingPDFException = (function MissingPDFExceptionClosure() {
  334. function MissingPDFException(msg) {
  335. this.name = 'MissingPDFException';
  336. this.message = msg;
  337. }
  338. MissingPDFException.prototype = new Error();
  339. MissingPDFException.constructor = MissingPDFException;
  340. return MissingPDFException;
  341. })();
  342. var NotImplementedException = (function NotImplementedExceptionClosure() {
  343. function NotImplementedException(msg) {
  344. this.message = msg;
  345. }
  346. NotImplementedException.prototype = new Error();
  347. NotImplementedException.prototype.name = 'NotImplementedException';
  348. NotImplementedException.constructor = NotImplementedException;
  349. return NotImplementedException;
  350. })();
  351. var MissingDataException = (function MissingDataExceptionClosure() {
  352. function MissingDataException(begin, end) {
  353. this.begin = begin;
  354. this.end = end;
  355. this.message = 'Missing data [' + begin + ', ' + end + ')';
  356. }
  357. MissingDataException.prototype = new Error();
  358. MissingDataException.prototype.name = 'MissingDataException';
  359. MissingDataException.constructor = MissingDataException;
  360. return MissingDataException;
  361. })();
  362. var XRefParseException = (function XRefParseExceptionClosure() {
  363. function XRefParseException(msg) {
  364. this.message = msg;
  365. }
  366. XRefParseException.prototype = new Error();
  367. XRefParseException.prototype.name = 'XRefParseException';
  368. XRefParseException.constructor = XRefParseException;
  369. return XRefParseException;
  370. })();
  371. function bytesToString(bytes) {
  372. var length = bytes.length;
  373. var MAX_ARGUMENT_COUNT = 8192;
  374. if (length < MAX_ARGUMENT_COUNT) {
  375. return String.fromCharCode.apply(null, bytes);
  376. }
  377. var strBuf = [];
  378. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  379. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  380. var chunk = bytes.subarray(i, chunkEnd);
  381. strBuf.push(String.fromCharCode.apply(null, chunk));
  382. }
  383. return strBuf.join('');
  384. }
  385. function stringToArray(str) {
  386. var length = str.length;
  387. var array = [];
  388. for (var i = 0; i < length; ++i) {
  389. array[i] = str.charCodeAt(i);
  390. }
  391. return array;
  392. }
  393. function stringToBytes(str) {
  394. var length = str.length;
  395. var bytes = new Uint8Array(length);
  396. for (var i = 0; i < length; ++i) {
  397. bytes[i] = str.charCodeAt(i) & 0xFF;
  398. }
  399. return bytes;
  400. }
  401. function string32(value) {
  402. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  403. (value >> 8) & 0xff, value & 0xff);
  404. }
  405. function log2(x) {
  406. var n = 1, i = 0;
  407. while (x > n) {
  408. n <<= 1;
  409. i++;
  410. }
  411. return i;
  412. }
  413. function readInt8(data, start) {
  414. return (data[start] << 24) >> 24;
  415. }
  416. function readUint16(data, offset) {
  417. return (data[offset] << 8) | data[offset + 1];
  418. }
  419. function readUint32(data, offset) {
  420. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  421. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  422. }
  423. // Lazy test the endianness of the platform
  424. // NOTE: This will be 'true' for simulated TypedArrays
  425. function isLittleEndian() {
  426. var buffer8 = new Uint8Array(2);
  427. buffer8[0] = 1;
  428. var buffer16 = new Uint16Array(buffer8.buffer);
  429. return (buffer16[0] === 1);
  430. }
  431. Object.defineProperty(PDFJS, 'isLittleEndian', {
  432. configurable: true,
  433. get: function PDFJS_isLittleEndian() {
  434. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  435. }
  436. });
  437. // Lazy test if the userAgant support CanvasTypedArrays
  438. function hasCanvasTypedArrays() {
  439. var canvas = document.createElement('canvas');
  440. canvas.width = canvas.height = 1;
  441. var ctx = canvas.getContext('2d');
  442. var imageData = ctx.createImageData(1, 1);
  443. return (typeof imageData.data.buffer !== 'undefined');
  444. }
  445. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  446. configurable: true,
  447. get: function PDFJS_hasCanvasTypedArrays() {
  448. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  449. }
  450. });
  451. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  452. function Uint32ArrayView(buffer, length) {
  453. this.buffer = buffer;
  454. this.byteLength = buffer.length;
  455. this.length = length === undefined ? (this.byteLength >> 2) : length;
  456. ensureUint32ArrayViewProps(this.length);
  457. }
  458. Uint32ArrayView.prototype = Object.create(null);
  459. var uint32ArrayViewSetters = 0;
  460. function createUint32ArrayProp(index) {
  461. return {
  462. get: function () {
  463. var buffer = this.buffer, offset = index << 2;
  464. return (buffer[offset] | (buffer[offset + 1] << 8) |
  465. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  466. },
  467. set: function (value) {
  468. var buffer = this.buffer, offset = index << 2;
  469. buffer[offset] = value & 255;
  470. buffer[offset + 1] = (value >> 8) & 255;
  471. buffer[offset + 2] = (value >> 16) & 255;
  472. buffer[offset + 3] = (value >>> 24) & 255;
  473. }
  474. };
  475. }
  476. function ensureUint32ArrayViewProps(length) {
  477. while (uint32ArrayViewSetters < length) {
  478. Object.defineProperty(Uint32ArrayView.prototype,
  479. uint32ArrayViewSetters,
  480. createUint32ArrayProp(uint32ArrayViewSetters));
  481. uint32ArrayViewSetters++;
  482. }
  483. }
  484. return Uint32ArrayView;
  485. })();
  486. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  487. var Util = PDFJS.Util = (function UtilClosure() {
  488. function Util() {}
  489. Util.makeCssRgb = function Util_makeCssRgb(rgb) {
  490. return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  491. };
  492. // Concatenates two transformation matrices together and returns the result.
  493. Util.transform = function Util_transform(m1, m2) {
  494. return [
  495. m1[0] * m2[0] + m1[2] * m2[1],
  496. m1[1] * m2[0] + m1[3] * m2[1],
  497. m1[0] * m2[2] + m1[2] * m2[3],
  498. m1[1] * m2[2] + m1[3] * m2[3],
  499. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  500. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  501. ];
  502. };
  503. // For 2d affine transforms
  504. Util.applyTransform = function Util_applyTransform(p, m) {
  505. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  506. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  507. return [xt, yt];
  508. };
  509. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  510. var d = m[0] * m[3] - m[1] * m[2];
  511. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  512. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  513. return [xt, yt];
  514. };
  515. // Applies the transform to the rectangle and finds the minimum axially
  516. // aligned bounding box.
  517. Util.getAxialAlignedBoundingBox =
  518. function Util_getAxialAlignedBoundingBox(r, m) {
  519. var p1 = Util.applyTransform(r, m);
  520. var p2 = Util.applyTransform(r.slice(2, 4), m);
  521. var p3 = Util.applyTransform([r[0], r[3]], m);
  522. var p4 = Util.applyTransform([r[2], r[1]], m);
  523. return [
  524. Math.min(p1[0], p2[0], p3[0], p4[0]),
  525. Math.min(p1[1], p2[1], p3[1], p4[1]),
  526. Math.max(p1[0], p2[0], p3[0], p4[0]),
  527. Math.max(p1[1], p2[1], p3[1], p4[1])
  528. ];
  529. };
  530. Util.inverseTransform = function Util_inverseTransform(m) {
  531. var d = m[0] * m[3] - m[1] * m[2];
  532. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  533. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  534. };
  535. // Apply a generic 3d matrix M on a 3-vector v:
  536. // | a b c | | X |
  537. // | d e f | x | Y |
  538. // | g h i | | Z |
  539. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  540. // with v as [X,Y,Z]
  541. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  542. return [
  543. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  544. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  545. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  546. ];
  547. };
  548. // This calculation uses Singular Value Decomposition.
  549. // The SVD can be represented with formula A = USV. We are interested in the
  550. // matrix S here because it represents the scale values.
  551. Util.singularValueDecompose2dScale =
  552. function Util_singularValueDecompose2dScale(m) {
  553. var transpose = [m[0], m[2], m[1], m[3]];
  554. // Multiply matrix m with its transpose.
  555. var a = m[0] * transpose[0] + m[1] * transpose[2];
  556. var b = m[0] * transpose[1] + m[1] * transpose[3];
  557. var c = m[2] * transpose[0] + m[3] * transpose[2];
  558. var d = m[2] * transpose[1] + m[3] * transpose[3];
  559. // Solve the second degree polynomial to get roots.
  560. var first = (a + d) / 2;
  561. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  562. var sx = first + second || 1;
  563. var sy = first - second || 1;
  564. // Scale values are the square roots of the eigenvalues.
  565. return [Math.sqrt(sx), Math.sqrt(sy)];
  566. };
  567. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  568. // For coordinate systems whose origin lies in the bottom-left, this
  569. // means normalization to (BL,TR) ordering. For systems with origin in the
  570. // top-left, this means (TL,BR) ordering.
  571. Util.normalizeRect = function Util_normalizeRect(rect) {
  572. var r = rect.slice(0); // clone rect
  573. if (rect[0] > rect[2]) {
  574. r[0] = rect[2];
  575. r[2] = rect[0];
  576. }
  577. if (rect[1] > rect[3]) {
  578. r[1] = rect[3];
  579. r[3] = rect[1];
  580. }
  581. return r;
  582. };
  583. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  584. // intersection of rect1 and rect2. If no intersection, returns 'false'
  585. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  586. Util.intersect = function Util_intersect(rect1, rect2) {
  587. function compare(a, b) {
  588. return a - b;
  589. }
  590. // Order points along the axes
  591. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  592. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  593. result = [];
  594. rect1 = Util.normalizeRect(rect1);
  595. rect2 = Util.normalizeRect(rect2);
  596. // X: first and second points belong to different rectangles?
  597. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  598. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  599. // Intersection must be between second and third points
  600. result[0] = orderedX[1];
  601. result[2] = orderedX[2];
  602. } else {
  603. return false;
  604. }
  605. // Y: first and second points belong to different rectangles?
  606. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  607. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  608. // Intersection must be between second and third points
  609. result[1] = orderedY[1];
  610. result[3] = orderedY[2];
  611. } else {
  612. return false;
  613. }
  614. return result;
  615. };
  616. Util.sign = function Util_sign(num) {
  617. return num < 0 ? -1 : 1;
  618. };
  619. // TODO(mack): Rename appendToArray
  620. Util.concatenateToArray = function concatenateToArray(arr1, arr2) {
  621. Array.prototype.push.apply(arr1, arr2);
  622. };
  623. Util.prependToArray = function concatenateToArray(arr1, arr2) {
  624. Array.prototype.unshift.apply(arr1, arr2);
  625. };
  626. Util.extendObj = function extendObj(obj1, obj2) {
  627. for (var key in obj2) {
  628. obj1[key] = obj2[key];
  629. }
  630. };
  631. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  632. name) {
  633. while (dict && !dict.has(name)) {
  634. dict = dict.get('Parent');
  635. }
  636. if (!dict) {
  637. return null;
  638. }
  639. return dict.get(name);
  640. };
  641. Util.inherit = function Util_inherit(sub, base, prototype) {
  642. sub.prototype = Object.create(base.prototype);
  643. sub.prototype.constructor = sub;
  644. for (var prop in prototype) {
  645. sub.prototype[prop] = prototype[prop];
  646. }
  647. };
  648. Util.loadScript = function Util_loadScript(src, callback) {
  649. var script = document.createElement('script');
  650. var loaded = false;
  651. script.setAttribute('src', src);
  652. if (callback) {
  653. script.onload = function() {
  654. if (!loaded) {
  655. callback();
  656. }
  657. loaded = true;
  658. };
  659. }
  660. document.getElementsByTagName('head')[0].appendChild(script);
  661. };
  662. return Util;
  663. })();
  664. /**
  665. * PDF page viewport created based on scale, rotation and offset.
  666. * @class
  667. * @alias PDFJS.PageViewport
  668. */
  669. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  670. /**
  671. * @constructor
  672. * @private
  673. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  674. * @param scale {number} scale of the viewport.
  675. * @param rotation {number} rotations of the viewport in degrees.
  676. * @param offsetX {number} offset X
  677. * @param offsetY {number} offset Y
  678. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  679. */
  680. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  681. this.viewBox = viewBox;
  682. this.scale = scale;
  683. this.rotation = rotation;
  684. this.offsetX = offsetX;
  685. this.offsetY = offsetY;
  686. // creating transform to convert pdf coordinate system to the normal
  687. // canvas like coordinates taking in account scale and rotation
  688. var centerX = (viewBox[2] + viewBox[0]) / 2;
  689. var centerY = (viewBox[3] + viewBox[1]) / 2;
  690. var rotateA, rotateB, rotateC, rotateD;
  691. rotation = rotation % 360;
  692. rotation = rotation < 0 ? rotation + 360 : rotation;
  693. switch (rotation) {
  694. case 180:
  695. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  696. break;
  697. case 90:
  698. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  699. break;
  700. case 270:
  701. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  702. break;
  703. //case 0:
  704. default:
  705. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  706. break;
  707. }
  708. if (dontFlip) {
  709. rotateC = -rotateC; rotateD = -rotateD;
  710. }
  711. var offsetCanvasX, offsetCanvasY;
  712. var width, height;
  713. if (rotateA === 0) {
  714. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  715. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  716. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  717. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  718. } else {
  719. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  720. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  721. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  722. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  723. }
  724. // creating transform for the following operations:
  725. // translate(-centerX, -centerY), rotate and flip vertically,
  726. // scale, and translate(offsetCanvasX, offsetCanvasY)
  727. this.transform = [
  728. rotateA * scale,
  729. rotateB * scale,
  730. rotateC * scale,
  731. rotateD * scale,
  732. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  733. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  734. ];
  735. this.width = width;
  736. this.height = height;
  737. this.fontScale = scale;
  738. }
  739. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  740. /**
  741. * Clones viewport with additional properties.
  742. * @param args {Object} (optional) If specified, may contain the 'scale' or
  743. * 'rotation' properties to override the corresponding properties in
  744. * the cloned viewport.
  745. * @returns {PDFJS.PageViewport} Cloned viewport.
  746. */
  747. clone: function PageViewPort_clone(args) {
  748. args = args || {};
  749. var scale = 'scale' in args ? args.scale : this.scale;
  750. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  751. return new PageViewport(this.viewBox.slice(), scale, rotation,
  752. this.offsetX, this.offsetY, args.dontFlip);
  753. },
  754. /**
  755. * Converts PDF point to the viewport coordinates. For examples, useful for
  756. * converting PDF location into canvas pixel coordinates.
  757. * @param x {number} X coordinate.
  758. * @param y {number} Y coordinate.
  759. * @returns {Object} Object that contains 'x' and 'y' properties of the
  760. * point in the viewport coordinate space.
  761. * @see {@link convertToPdfPoint}
  762. * @see {@link convertToViewportRectangle}
  763. */
  764. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  765. return Util.applyTransform([x, y], this.transform);
  766. },
  767. /**
  768. * Converts PDF rectangle to the viewport coordinates.
  769. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  770. * @returns {Array} Contains corresponding coordinates of the rectangle
  771. * in the viewport coordinate space.
  772. * @see {@link convertToViewportPoint}
  773. */
  774. convertToViewportRectangle:
  775. function PageViewport_convertToViewportRectangle(rect) {
  776. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  777. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  778. return [tl[0], tl[1], br[0], br[1]];
  779. },
  780. /**
  781. * Converts viewport coordinates to the PDF location. For examples, useful
  782. * for converting canvas pixel location into PDF one.
  783. * @param x {number} X coordinate.
  784. * @param y {number} Y coordinate.
  785. * @returns {Object} Object that contains 'x' and 'y' properties of the
  786. * point in the PDF coordinate space.
  787. * @see {@link convertToViewportPoint}
  788. */
  789. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  790. return Util.applyInverseTransform([x, y], this.transform);
  791. }
  792. };
  793. return PageViewport;
  794. })();
  795. var PDFStringTranslateTable = [
  796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  797. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  802. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  803. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  804. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  805. ];
  806. function stringToPDFString(str) {
  807. var i, n = str.length, strBuf = [];
  808. if (str[0] === '\xFE' && str[1] === '\xFF') {
  809. // UTF16BE BOM
  810. for (i = 2; i < n; i += 2) {
  811. strBuf.push(String.fromCharCode(
  812. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  813. }
  814. } else {
  815. for (i = 0; i < n; ++i) {
  816. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  817. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  818. }
  819. }
  820. return strBuf.join('');
  821. }
  822. function stringToUTF8String(str) {
  823. return decodeURIComponent(escape(str));
  824. }
  825. function isEmptyObj(obj) {
  826. for (var key in obj) {
  827. return false;
  828. }
  829. return true;
  830. }
  831. function isBool(v) {
  832. return typeof v == 'boolean';
  833. }
  834. function isInt(v) {
  835. return typeof v === 'number' && ((v | 0) === v);
  836. }
  837. function isNum(v) {
  838. return typeof v === 'number';
  839. }
  840. function isString(v) {
  841. return typeof v === 'string';
  842. }
  843. function isNull(v) {
  844. return v === null;
  845. }
  846. function isName(v) {
  847. return v instanceof Name;
  848. }
  849. function isCmd(v, cmd) {
  850. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  851. }
  852. function isDict(v, type) {
  853. if (!(v instanceof Dict)) {
  854. return false;
  855. }
  856. if (!type) {
  857. return true;
  858. }
  859. var dictType = v.get('Type');
  860. return isName(dictType) && dictType.name === type;
  861. }
  862. function isArray(v) {
  863. return v instanceof Array;
  864. }
  865. function isStream(v) {
  866. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  867. }
  868. function isArrayBuffer(v) {
  869. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  870. }
  871. function isRef(v) {
  872. return v instanceof Ref;
  873. }
  874. /**
  875. * Promise Capability object.
  876. *
  877. * @typedef {Object} PromiseCapability
  878. * @property {Promise} promise - A promise object.
  879. * @property {function} resolve - Fullfills the promise.
  880. * @property {function} reject - Rejects the promise.
  881. */
  882. /**
  883. * Creates a promise capability object.
  884. * @alias PDFJS.createPromiseCapability
  885. *
  886. * @return {PromiseCapability} A capability object contains:
  887. * - a Promise, resolve and reject methods.
  888. */
  889. function createPromiseCapability() {
  890. var capability = {};
  891. capability.promise = new Promise(function (resolve, reject) {
  892. capability.resolve = resolve;
  893. capability.reject = reject;
  894. });
  895. return capability;
  896. }
  897. PDFJS.createPromiseCapability = createPromiseCapability;
  898. /**
  899. * Polyfill for Promises:
  900. * The following promise implementation tries to generally implement the
  901. * Promise/A+ spec. Some notable differences from other promise libaries are:
  902. * - There currently isn't a seperate deferred and promise object.
  903. * - Unhandled rejections eventually show an error if they aren't handled.
  904. *
  905. * Based off of the work in:
  906. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  907. */
  908. (function PromiseClosure() {
  909. if (globalScope.Promise) {
  910. // Promises existing in the DOM/Worker, checking presence of all/resolve
  911. if (typeof globalScope.Promise.all !== 'function') {
  912. globalScope.Promise.all = function (iterable) {
  913. var count = 0, results = [], resolve, reject;
  914. var promise = new globalScope.Promise(function (resolve_, reject_) {
  915. resolve = resolve_;
  916. reject = reject_;
  917. });
  918. iterable.forEach(function (p, i) {
  919. count++;
  920. p.then(function (result) {
  921. results[i] = result;
  922. count--;
  923. if (count === 0) {
  924. resolve(results);
  925. }
  926. }, reject);
  927. });
  928. if (count === 0) {
  929. resolve(results);
  930. }
  931. return promise;
  932. };
  933. }
  934. if (typeof globalScope.Promise.resolve !== 'function') {
  935. globalScope.Promise.resolve = function (value) {
  936. return new globalScope.Promise(function (resolve) { resolve(value); });
  937. };
  938. }
  939. if (typeof globalScope.Promise.reject !== 'function') {
  940. globalScope.Promise.reject = function (reason) {
  941. return new globalScope.Promise(function (resolve, reject) {
  942. reject(reason);
  943. });
  944. };
  945. }
  946. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  947. globalScope.Promise.prototype.catch = function (onReject) {
  948. return globalScope.Promise.prototype.then(undefined, onReject);
  949. };
  950. }
  951. return;
  952. }
  953. var STATUS_PENDING = 0;
  954. var STATUS_RESOLVED = 1;
  955. var STATUS_REJECTED = 2;
  956. // In an attempt to avoid silent exceptions, unhandled rejections are
  957. // tracked and if they aren't handled in a certain amount of time an
  958. // error is logged.
  959. var REJECTION_TIMEOUT = 500;
  960. var HandlerManager = {
  961. handlers: [],
  962. running: false,
  963. unhandledRejections: [],
  964. pendingRejectionCheck: false,
  965. scheduleHandlers: function scheduleHandlers(promise) {
  966. if (promise._status == STATUS_PENDING) {
  967. return;
  968. }
  969. this.handlers = this.handlers.concat(promise._handlers);
  970. promise._handlers = [];
  971. if (this.running) {
  972. return;
  973. }
  974. this.running = true;
  975. setTimeout(this.runHandlers.bind(this), 0);
  976. },
  977. runHandlers: function runHandlers() {
  978. var RUN_TIMEOUT = 1; // ms
  979. var timeoutAt = Date.now() + RUN_TIMEOUT;
  980. while (this.handlers.length > 0) {
  981. var handler = this.handlers.shift();
  982. var nextStatus = handler.thisPromise._status;
  983. var nextValue = handler.thisPromise._value;
  984. try {
  985. if (nextStatus === STATUS_RESOLVED) {
  986. if (typeof(handler.onResolve) == 'function') {
  987. nextValue = handler.onResolve(nextValue);
  988. }
  989. } else if (typeof(handler.onReject) === 'function') {
  990. nextValue = handler.onReject(nextValue);
  991. nextStatus = STATUS_RESOLVED;
  992. if (handler.thisPromise._unhandledRejection) {
  993. this.removeUnhandeledRejection(handler.thisPromise);
  994. }
  995. }
  996. } catch (ex) {
  997. nextStatus = STATUS_REJECTED;
  998. nextValue = ex;
  999. }
  1000. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1001. if (Date.now() >= timeoutAt) {
  1002. break;
  1003. }
  1004. }
  1005. if (this.handlers.length > 0) {
  1006. setTimeout(this.runHandlers.bind(this), 0);
  1007. return;
  1008. }
  1009. this.running = false;
  1010. },
  1011. addUnhandledRejection: function addUnhandledRejection(promise) {
  1012. this.unhandledRejections.push({
  1013. promise: promise,
  1014. time: Date.now()
  1015. });
  1016. this.scheduleRejectionCheck();
  1017. },
  1018. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1019. promise._unhandledRejection = false;
  1020. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1021. if (this.unhandledRejections[i].promise === promise) {
  1022. this.unhandledRejections.splice(i);
  1023. i--;
  1024. }
  1025. }
  1026. },
  1027. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1028. if (this.pendingRejectionCheck) {
  1029. return;
  1030. }
  1031. this.pendingRejectionCheck = true;
  1032. setTimeout(function rejectionCheck() {
  1033. this.pendingRejectionCheck = false;
  1034. var now = Date.now();
  1035. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1036. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1037. var unhandled = this.unhandledRejections[i].promise._value;
  1038. var msg = 'Unhandled rejection: ' + unhandled;
  1039. if (unhandled.stack) {
  1040. msg += '\n' + unhandled.stack;
  1041. }
  1042. warn(msg);
  1043. this.unhandledRejections.splice(i);
  1044. i--;
  1045. }
  1046. }
  1047. if (this.unhandledRejections.length) {
  1048. this.scheduleRejectionCheck();
  1049. }
  1050. }.bind(this), REJECTION_TIMEOUT);
  1051. }
  1052. };
  1053. function Promise(resolver) {
  1054. this._status = STATUS_PENDING;
  1055. this._handlers = [];
  1056. try {
  1057. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1058. } catch (e) {
  1059. this._reject(e);
  1060. }
  1061. }
  1062. /**
  1063. * Builds a promise that is resolved when all the passed in promises are
  1064. * resolved.
  1065. * @param {array} array of data and/or promises to wait for.
  1066. * @return {Promise} New dependant promise.
  1067. */
  1068. Promise.all = function Promise_all(promises) {
  1069. var resolveAll, rejectAll;
  1070. var deferred = new Promise(function (resolve, reject) {
  1071. resolveAll = resolve;
  1072. rejectAll = reject;
  1073. });
  1074. var unresolved = promises.length;
  1075. var results = [];
  1076. if (unresolved === 0) {
  1077. resolveAll(results);
  1078. return deferred;
  1079. }
  1080. function reject(reason) {
  1081. if (deferred._status === STATUS_REJECTED) {
  1082. return;
  1083. }
  1084. results = [];
  1085. rejectAll(reason);
  1086. }
  1087. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1088. var promise = promises[i];
  1089. var resolve = (function(i) {
  1090. return function(value) {
  1091. if (deferred._status === STATUS_REJECTED) {
  1092. return;
  1093. }
  1094. results[i] = value;
  1095. unresolved--;
  1096. if (unresolved === 0) {
  1097. resolveAll(results);
  1098. }
  1099. };
  1100. })(i);
  1101. if (Promise.isPromise(promise)) {
  1102. promise.then(resolve, reject);
  1103. } else {
  1104. resolve(promise);
  1105. }
  1106. }
  1107. return deferred;
  1108. };
  1109. /**
  1110. * Checks if the value is likely a promise (has a 'then' function).
  1111. * @return {boolean} true if value is thenable
  1112. */
  1113. Promise.isPromise = function Promise_isPromise(value) {
  1114. return value && typeof value.then === 'function';
  1115. };
  1116. /**
  1117. * Creates resolved promise
  1118. * @param value resolve value
  1119. * @returns {Promise}
  1120. */
  1121. Promise.resolve = function Promise_resolve(value) {
  1122. return new Promise(function (resolve) { resolve(value); });
  1123. };
  1124. /**
  1125. * Creates rejected promise
  1126. * @param reason rejection value
  1127. * @returns {Promise}
  1128. */
  1129. Promise.reject = function Promise_reject(reason) {
  1130. return new Promise(function (resolve, reject) { reject(reason); });
  1131. };
  1132. Promise.prototype = {
  1133. _status: null,
  1134. _value: null,
  1135. _handlers: null,
  1136. _unhandledRejection: null,
  1137. _updateStatus: function Promise__updateStatus(status, value) {
  1138. if (this._status === STATUS_RESOLVED ||
  1139. this._status === STATUS_REJECTED) {
  1140. return;
  1141. }
  1142. if (status == STATUS_RESOLVED &&
  1143. Promise.isPromise(value)) {
  1144. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1145. this._updateStatus.bind(this, STATUS_REJECTED));
  1146. return;
  1147. }
  1148. this._status = status;
  1149. this._value = value;
  1150. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1151. this._unhandledRejection = true;
  1152. HandlerManager.addUnhandledRejection(this);
  1153. }
  1154. HandlerManager.scheduleHandlers(this);
  1155. },
  1156. _resolve: function Promise_resolve(value) {
  1157. this._updateStatus(STATUS_RESOLVED, value);
  1158. },
  1159. _reject: function Promise_reject(reason) {
  1160. this._updateStatus(STATUS_REJECTED, reason);
  1161. },
  1162. then: function Promise_then(onResolve, onReject) {
  1163. var nextPromise = new Promise(function (resolve, reject) {
  1164. this.resolve = reject;
  1165. this.reject = reject;
  1166. });
  1167. this._handlers.push({
  1168. thisPromise: this,
  1169. onResolve: onResolve,
  1170. onReject: onReject,
  1171. nextPromise: nextPromise
  1172. });
  1173. HandlerManager.scheduleHandlers(this);
  1174. return nextPromise;
  1175. },
  1176. catch: function Promise_catch(onReject) {
  1177. return this.then(undefined, onReject);
  1178. }
  1179. };
  1180. globalScope.Promise = Promise;
  1181. })();
  1182. var StatTimer = (function StatTimerClosure() {
  1183. function rpad(str, pad, length) {
  1184. while (str.length < length) {
  1185. str += pad;
  1186. }
  1187. return str;
  1188. }
  1189. function StatTimer() {
  1190. this.started = {};
  1191. this.times = [];
  1192. this.enabled = true;
  1193. }
  1194. StatTimer.prototype = {
  1195. time: function StatTimer_time(name) {
  1196. if (!this.enabled) {
  1197. return;
  1198. }
  1199. if (name in this.started) {
  1200. warn('Timer is already running for ' + name);
  1201. }
  1202. this.started[name] = Date.now();
  1203. },
  1204. timeEnd: function StatTimer_timeEnd(name) {
  1205. if (!this.enabled) {
  1206. return;
  1207. }
  1208. if (!(name in this.started)) {
  1209. warn('Timer has not been started for ' + name);
  1210. }
  1211. this.times.push({
  1212. 'name': name,
  1213. 'start': this.started[name],
  1214. 'end': Date.now()
  1215. });
  1216. // Remove timer from started so it can be called again.
  1217. delete this.started[name];
  1218. },
  1219. toString: function StatTimer_toString() {
  1220. var i, ii;
  1221. var times = this.times;
  1222. var out = '';
  1223. // Find the longest name for padding purposes.
  1224. var longest = 0;
  1225. for (i = 0, ii = times.length; i < ii; ++i) {
  1226. var name = times[i]['name'];
  1227. if (name.length > longest) {
  1228. longest = name.length;
  1229. }
  1230. }
  1231. for (i = 0, ii = times.length; i < ii; ++i) {
  1232. var span = times[i];
  1233. var duration = span.end - span.start;
  1234. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1235. }
  1236. return out;
  1237. }
  1238. };
  1239. return StatTimer;
  1240. })();
  1241. PDFJS.createBlob = function createBlob(data, contentType) {
  1242. if (typeof Blob !== 'undefined') {
  1243. return new Blob([data], { type: contentType });
  1244. }
  1245. // Blob builder is deprecated in FF14 and removed in FF18.
  1246. var bb = new MozBlobBuilder();
  1247. bb.append(data);
  1248. return bb.getBlob(contentType);
  1249. };
  1250. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1251. // Blob/createObjectURL is not available, falling back to data schema.
  1252. var digits =
  1253. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1254. return function createObjectURL(data, contentType) {
  1255. if (!PDFJS.disableCreateObjectURL &&
  1256. typeof URL !== 'undefined' && URL.createObjectURL) {
  1257. var blob = PDFJS.createBlob(data, contentType);
  1258. return URL.createObjectURL(blob);
  1259. }
  1260. var buffer = 'data:' + contentType + ';base64,';
  1261. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1262. var b1 = data[i] & 0xFF;
  1263. var b2 = data[i + 1] & 0xFF;
  1264. var b3 = data[i + 2] & 0xFF;
  1265. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1266. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1267. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1268. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1269. }
  1270. return buffer;
  1271. };
  1272. })();
  1273. function MessageHandler(name, comObj) {
  1274. this.name = name;
  1275. this.comObj = comObj;
  1276. this.callbackIndex = 1;
  1277. this.postMessageTransfers = true;
  1278. var callbacksCapabilities = this.callbacksCapabilities = {};
  1279. var ah = this.actionHandler = {};
  1280. ah['console_log'] = [function ahConsoleLog(data) {
  1281. console.log.apply(console, data);
  1282. }];
  1283. ah['console_error'] = [function ahConsoleError(data) {
  1284. console.error.apply(console, data);
  1285. }];
  1286. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1287. UnsupportedManager.notify(data);
  1288. }];
  1289. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1290. var data = event.data;
  1291. if (data.isReply) {
  1292. var callbackId = data.callbackId;
  1293. if (data.callbackId in callbacksCapabilities) {
  1294. var callback = callbacksCapabilities[callbackId];
  1295. delete callbacksCapabilities[callbackId];
  1296. if ('error' in data) {
  1297. callback.reject(data.error);
  1298. } else {
  1299. callback.resolve(data.data);
  1300. }
  1301. } else {
  1302. error('Cannot resolve callback ' + callbackId);
  1303. }
  1304. } else if (data.action in ah) {
  1305. var action = ah[data.action];
  1306. if (data.callbackId) {
  1307. Promise.resolve().then(function () {
  1308. return action[0].call(action[1], data.data);
  1309. }).then(function (result) {
  1310. comObj.postMessage({
  1311. isReply: true,
  1312. callbackId: data.callbackId,
  1313. data: result
  1314. });
  1315. }, function (reason) {
  1316. comObj.postMessage({
  1317. isReply: true,
  1318. callbackId: data.callbackId,
  1319. error: reason
  1320. });
  1321. });
  1322. } else {
  1323. action[0].call(action[1], data.data);
  1324. }
  1325. } else {
  1326. error('Unknown action from worker: ' + data.action);
  1327. }
  1328. };
  1329. }
  1330. MessageHandler.prototype = {
  1331. on: function messageHandlerOn(actionName, handler, scope) {
  1332. var ah = this.actionHandler;
  1333. if (ah[actionName]) {
  1334. error('There is already an actionName called "' + actionName + '"');
  1335. }
  1336. ah[actionName] = [handler, scope];
  1337. },
  1338. /**
  1339. * Sends a message to the comObj to invoke the action with the supplied data.
  1340. * @param {String} actionName Action to call.
  1341. * @param {JSON} data JSON data to send.
  1342. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1343. */
  1344. send: function messageHandlerSend(actionName, data, transfers) {
  1345. var message = {
  1346. action: actionName,
  1347. data: data
  1348. };
  1349. this.postMessage(message, transfers);
  1350. },
  1351. /**
  1352. * Sends a message to the comObj to invoke the action with the supplied data.
  1353. * Expects that other side will callback with the response.
  1354. * @param {String} actionName Action to call.
  1355. * @param {JSON} data JSON data to send.
  1356. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1357. * @returns {Promise} Promise to be resolved with response data.
  1358. */
  1359. sendWithPromise:
  1360. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1361. var callbackId = this.callbackIndex++;
  1362. var message = {
  1363. action: actionName,
  1364. data: data,
  1365. callbackId: callbackId
  1366. };
  1367. var capability = createPromiseCapability();
  1368. this.callbacksCapabilities[callbackId] = capability;
  1369. try {
  1370. this.postMessage(message, transfers);
  1371. } catch (e) {
  1372. capability.reject(e);
  1373. }
  1374. return capability.promise;
  1375. },
  1376. /**
  1377. * Sends raw message to the comObj.
  1378. * @private
  1379. * @param message {Object} Raw message.
  1380. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1381. */
  1382. postMessage: function (message, transfers) {
  1383. if (transfers && this.postMessageTransfers) {
  1384. this.comObj.postMessage(message, transfers);
  1385. } else {
  1386. this.comObj.postMessage(message);
  1387. }
  1388. }
  1389. };
  1390. function loadJpegStream(id, imageUrl, objs) {
  1391. var img = new Image();
  1392. img.onload = (function loadJpegStream_onloadClosure() {
  1393. objs.resolve(id, img);
  1394. });
  1395. img.src = imageUrl;
  1396. }
  1397. var DEFAULT_ICON_SIZE = 22; // px
  1398. var HIGHLIGHT_OFFSET = 4; // px
  1399. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  1400. var Annotation = (function AnnotationClosure() {
  1401. // 12.5.5: Algorithm: Appearance streams
  1402. function getTransformMatrix(rect, bbox, matrix) {
  1403. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  1404. var minX = bounds[0];
  1405. var minY = bounds[1];
  1406. var maxX = bounds[2];
  1407. var maxY = bounds[3];
  1408. if (minX === maxX || minY === maxY) {
  1409. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  1410. // just apply the transform for rect
  1411. return [1, 0, 0, 1, rect[0], rect[1]];
  1412. }
  1413. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  1414. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  1415. return [
  1416. xRatio,
  1417. 0,
  1418. 0,
  1419. yRatio,
  1420. rect[0] - minX * xRatio,
  1421. rect[1] - minY * yRatio
  1422. ];
  1423. }
  1424. function getDefaultAppearance(dict) {
  1425. var appearanceState = dict.get('AP');
  1426. if (!isDict(appearanceState)) {
  1427. return;
  1428. }
  1429. var appearance;
  1430. var appearances = appearanceState.get('N');
  1431. if (isDict(appearances)) {
  1432. var as = dict.get('AS');
  1433. if (as && appearances.has(as.name)) {
  1434. appearance = appearances.get(as.name);
  1435. }
  1436. } else {
  1437. appearance = appearances;
  1438. }
  1439. return appearance;
  1440. }
  1441. function Annotation(params) {
  1442. if (params.data) {
  1443. this.data = params.data;
  1444. return;
  1445. }
  1446. var dict = params.dict;
  1447. var data = this.data = {};
  1448. data.subtype = dict.get('Subtype').name;
  1449. var rect = dict.get('Rect') || [0, 0, 0, 0];
  1450. data.rect = Util.normalizeRect(rect);
  1451. data.annotationFlags = dict.get('F');
  1452. var color = dict.get('C');
  1453. if (isArray(color) && color.length === 3) {
  1454. // TODO(mack): currently only supporting rgb; need support different
  1455. // colorspaces
  1456. data.color = color;
  1457. } else {
  1458. data.color = [0, 0, 0];
  1459. }
  1460. // Some types of annotations have border style dict which has more
  1461. // info than the border array
  1462. if (dict.has('BS')) {
  1463. var borderStyle = dict.get('BS');
  1464. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  1465. } else {
  1466. var borderArray = dict.get('Border') || [0, 0, 1];
  1467. data.borderWidth = borderArray[2] || 0;
  1468. // TODO: implement proper support for annotations with line dash patterns.
  1469. var dashArray = borderArray[3];
  1470. if (data.borderWidth > 0 && dashArray) {
  1471. if (!isArray(dashArray)) {
  1472. // Ignore the border if dashArray is not actually an array,
  1473. // this is consistent with the behaviour in Adobe Reader.
  1474. data.borderWidth = 0;
  1475. } else {
  1476. var dashArrayLength = dashArray.length;
  1477. if (dashArrayLength > 0) {
  1478. // According to the PDF specification: the elements in a dashArray
  1479. // shall be numbers that are nonnegative and not all equal to zero.
  1480. var isInvalid = false;
  1481. var numPositive = 0;
  1482. for (var i = 0; i < dashArrayLength; i++) {
  1483. var validNumber = (+dashArray[i] >= 0);
  1484. if (!validNumber) {
  1485. isInvalid = true;
  1486. break;
  1487. } else if (dashArray[i] > 0) {
  1488. numPositive++;
  1489. }
  1490. }
  1491. if (isInvalid || numPositive === 0) {
  1492. data.borderWidth = 0;
  1493. }
  1494. }
  1495. }
  1496. }
  1497. }
  1498. this.appearance = getDefaultAppearance(dict);
  1499. data.hasAppearance = !!this.appearance;
  1500. data.id = params.ref.num;
  1501. }
  1502. Annotation.prototype = {
  1503. getData: function Annotation_getData() {
  1504. return this.data;
  1505. },
  1506. hasHtml: function Annotation_hasHtml() {
  1507. return false;
  1508. },
  1509. getHtmlElement: function Annotation_getHtmlElement(commonObjs) {
  1510. throw new NotImplementedException(
  1511. 'getHtmlElement() should be implemented in subclass');
  1512. },
  1513. // TODO(mack): Remove this, it's not really that helpful.
  1514. getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect,
  1515. borderWidth) {
  1516. assert(!isWorker,
  1517. 'getEmptyContainer() should be called from main thread');
  1518. var bWidth = borderWidth || 0;
  1519. rect = rect || this.data.rect;
  1520. var element = document.createElement(tagName);
  1521. element.style.borderWidth = bWidth + 'px';
  1522. var width = rect[2] - rect[0] - 2 * bWidth;
  1523. var height = rect[3] - rect[1] - 2 * bWidth;
  1524. element.style.width = width + 'px';
  1525. element.style.height = height + 'px';
  1526. return element;
  1527. },
  1528. isInvisible: function Annotation_isInvisible() {
  1529. var data = this.data;
  1530. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  1531. return false;
  1532. } else {
  1533. return !!(data &&
  1534. data.annotationFlags && // Default: not invisible
  1535. data.annotationFlags & 0x1); // Invisible
  1536. }
  1537. },
  1538. isViewable: function Annotation_isViewable() {
  1539. var data = this.data;
  1540. return !!(!this.isInvisible() &&
  1541. data &&
  1542. (!data.annotationFlags ||
  1543. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  1544. data.rect); // rectangle is necessary
  1545. },
  1546. isPrintable: function Annotation_isPrintable() {
  1547. var data = this.data;
  1548. return !!(!this.isInvisible() &&
  1549. data &&
  1550. data.annotationFlags && // Default: not printable
  1551. data.annotationFlags & 0x4 && // Print
  1552. !(data.annotationFlags & 0x2) && // Hidden
  1553. data.rect); // rectangle is necessary
  1554. },
  1555. loadResources: function Annotation_loadResources(keys) {
  1556. return new Promise(function (resolve, reject) {
  1557. this.appearance.dict.getAsync('Resources').then(function (resources) {
  1558. if (!resources) {
  1559. resolve();
  1560. return;
  1561. }
  1562. var objectLoader = new ObjectLoader(resources.map,
  1563. keys,
  1564. resources.xref);
  1565. objectLoader.load().then(function() {
  1566. resolve(resources);
  1567. }, reject);
  1568. }, reject);
  1569. }.bind(this));
  1570. },
  1571. getOperatorList: function Annotation_getOperatorList(evaluator) {
  1572. if (!this.appearance) {
  1573. return Promise.resolve(new OperatorList());
  1574. }
  1575. var data = this.data;
  1576. var appearanceDict = this.appearance.dict;
  1577. var resourcesPromise = this.loadResources([
  1578. 'ExtGState',
  1579. 'ColorSpace',
  1580. 'Pattern',
  1581. 'Shading',
  1582. 'XObject',
  1583. 'Font'
  1584. // ProcSet
  1585. // Properties
  1586. ]);
  1587. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  1588. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  1589. var transform = getTransformMatrix(data.rect, bbox, matrix);
  1590. var self = this;
  1591. return resourcesPromise.then(function(resources) {
  1592. var opList = new OperatorList();
  1593. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  1594. return evaluator.getOperatorList(self.appearance, resources, opList).
  1595. then(function () {
  1596. opList.addOp(OPS.endAnnotation, []);
  1597. self.appearance.reset();
  1598. return opList;
  1599. });
  1600. });
  1601. }
  1602. };
  1603. Annotation.getConstructor =
  1604. function Annotation_getConstructor(subtype, fieldType) {
  1605. if (!subtype) {
  1606. return;
  1607. }
  1608. // TODO(mack): Implement FreeText annotations
  1609. if (subtype === 'Link') {
  1610. return LinkAnnotation;
  1611. } else if (subtype === 'Text') {
  1612. return TextAnnotation;
  1613. } else if (subtype === 'Widget') {
  1614. if (!fieldType) {
  1615. return;
  1616. }
  1617. if (fieldType === 'Tx') {
  1618. return TextWidgetAnnotation;
  1619. } else {
  1620. return WidgetAnnotation;
  1621. }
  1622. } else {
  1623. return Annotation;
  1624. }
  1625. };
  1626. // TODO(mack): Support loading annotation from data
  1627. Annotation.fromData = function Annotation_fromData(data) {
  1628. var subtype = data.subtype;
  1629. var fieldType = data.fieldType;
  1630. var Constructor = Annotation.getConstructor(subtype, fieldType);
  1631. if (Constructor) {
  1632. return new Constructor({ data: data });
  1633. }
  1634. };
  1635. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  1636. var dict = xref.fetchIfRef(ref);
  1637. if (!isDict(dict)) {
  1638. return;
  1639. }
  1640. var subtype = dict.get('Subtype');
  1641. subtype = isName(subtype) ? subtype.name : '';
  1642. if (!subtype) {
  1643. return;
  1644. }
  1645. var fieldType = Util.getInheritableProperty(dict, 'FT');
  1646. fieldType = isName(fieldType) ? fieldType.name : '';
  1647. var Constructor = Annotation.getConstructor(subtype, fieldType);
  1648. if (!Constructor) {
  1649. return;
  1650. }
  1651. var params = {
  1652. dict: dict,
  1653. ref: ref,
  1654. };
  1655. var annotation = new Constructor(params);
  1656. if (annotation.isViewable() || annotation.isPrintable()) {
  1657. return annotation;
  1658. } else {
  1659. if (SUPPORTED_TYPES.indexOf(subtype) === -1) {
  1660. warn('unimplemented annotation type: ' + subtype);
  1661. }
  1662. }
  1663. };
  1664. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  1665. annotations, opList, pdfManager, partialEvaluator, intent) {
  1666. function reject(e) {
  1667. annotationsReadyCapability.reject(e);
  1668. }
  1669. var annotationsReadyCapability = createPromiseCapability();
  1670. var annotationPromises = [];
  1671. for (var i = 0, n = annotations.length; i < n; ++i) {
  1672. if (intent === 'display' && annotations[i].isViewable() ||
  1673. intent === 'print' && annotations[i].isPrintable()) {
  1674. annotationPromises.push(
  1675. annotations[i].getOperatorList(partialEvaluator));
  1676. }
  1677. }
  1678. Promise.all(annotationPromises).then(function(datas) {
  1679. opList.addOp(OPS.beginAnnotations, []);
  1680. for (var i = 0, n = datas.length; i < n; ++i) {
  1681. var annotOpList = datas[i];
  1682. opList.addOpList(annotOpList);
  1683. }
  1684. opList.addOp(OPS.endAnnotations, []);
  1685. annotationsReadyCapability.resolve();
  1686. }, reject);
  1687. return annotationsReadyCapability.promise;
  1688. };
  1689. return Annotation;
  1690. })();
  1691. PDFJS.Annotation = Annotation;
  1692. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  1693. function WidgetAnnotation(params) {
  1694. Annotation.call(this, params);
  1695. if (params.data) {
  1696. return;
  1697. }
  1698. var dict = params.dict;
  1699. var data = this.data;
  1700. data.fieldValue = stringToPDFString(
  1701. Util.getInheritableProperty(dict, 'V') || '');
  1702. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  1703. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  1704. var fieldType = Util.getInheritableProperty(dict, 'FT');
  1705. data.fieldType = isName(fieldType) ? fieldType.name : '';
  1706. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  1707. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  1708. // Building the full field name by collecting the field and
  1709. // its ancestors 'T' data and joining them using '.'.
  1710. var fieldName = [];
  1711. var namedItem = dict;
  1712. var ref = params.ref;
  1713. while (namedItem) {
  1714. var parent = namedItem.get('Parent');
  1715. var parentRef = namedItem.getRaw('Parent');
  1716. var name = namedItem.get('T');
  1717. if (name) {
  1718. fieldName.unshift(stringToPDFString(name));
  1719. } else {
  1720. // The field name is absent, that means more than one field
  1721. // with the same name may exist. Replacing the empty name
  1722. // with the '`' plus index in the parent's 'Kids' array.
  1723. // This is not in the PDF spec but necessary to id the
  1724. // the input controls.
  1725. var kids = parent.get('Kids');
  1726. var j, jj;
  1727. for (j = 0, jj = kids.length; j < jj; j++) {
  1728. var kidRef = kids[j];
  1729. if (kidRef.num == ref.num && kidRef.gen == ref.gen) {
  1730. break;
  1731. }
  1732. }
  1733. fieldName.unshift('`' + j);
  1734. }
  1735. namedItem = parent;
  1736. ref = parentRef;
  1737. }
  1738. data.fullName = fieldName.join('.');
  1739. }
  1740. var parent = Annotation.prototype;
  1741. Util.inherit(WidgetAnnotation, Annotation, {
  1742. isViewable: function WidgetAnnotation_isViewable() {
  1743. if (this.data.fieldType === 'Sig') {
  1744. warn('unimplemented annotation type: Widget signature');
  1745. return false;
  1746. }
  1747. return parent.isViewable.call(this);
  1748. }
  1749. });
  1750. return WidgetAnnotation;
  1751. })();
  1752. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  1753. function TextWidgetAnnotation(params) {
  1754. WidgetAnnotation.call(this, params);
  1755. if (params.data) {
  1756. return;
  1757. }
  1758. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  1759. }
  1760. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  1761. function setTextStyles(element, item, fontObj) {
  1762. var style = element.style;
  1763. style.fontSize = item.fontSize + 'px';
  1764. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  1765. if (!fontObj) {
  1766. return;
  1767. }
  1768. style.fontWeight = fontObj.black ?
  1769. (fontObj.bold ? 'bolder' : 'bold') :
  1770. (fontObj.bold ? 'bold' : 'normal');
  1771. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  1772. var fontName = fontObj.loadedName;
  1773. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  1774. // Use a reasonable default font if the font doesn't specify a fallback
  1775. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  1776. style.fontFamily = fontFamily + fallbackName;
  1777. }
  1778. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  1779. hasHtml: function TextWidgetAnnotation_hasHtml() {
  1780. return !this.data.hasAppearance && !!this.data.fieldValue;
  1781. },
  1782. getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {
  1783. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  1784. var item = this.data;
  1785. var element = this.getEmptyContainer('div');
  1786. element.style.display = 'table';
  1787. var content = document.createElement('div');
  1788. content.textContent = item.fieldValue;
  1789. var textAlignment = item.textAlignment;
  1790. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  1791. content.style.verticalAlign = 'middle';
  1792. content.style.display = 'table-cell';
  1793. var fontObj = item.fontRefName ?
  1794. commonObjs.getData(item.fontRefName) : null;
  1795. setTextStyles(content, item, fontObj);
  1796. element.appendChild(content);
  1797. return element;
  1798. },
  1799. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  1800. if (this.appearance) {
  1801. return Annotation.prototype.getOperatorList.call(this, evaluator);
  1802. }
  1803. var opList = new OperatorList();
  1804. var data = this.data;
  1805. // Even if there is an appearance stream, ignore it. This is the
  1806. // behaviour used by Adobe Reader.
  1807. if (!data.defaultAppearance) {
  1808. return Promise.resolve(opList);
  1809. }
  1810. var stream = new Stream(stringToBytes(data.defaultAppearance));
  1811. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  1812. then(function () {
  1813. return opList;
  1814. });
  1815. }
  1816. });
  1817. return TextWidgetAnnotation;
  1818. })();
  1819. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  1820. function InteractiveAnnotation(params) {
  1821. Annotation.call(this, params);
  1822. }
  1823. Util.inherit(InteractiveAnnotation, Annotation, {
  1824. hasHtml: function InteractiveAnnotation_hasHtml() {
  1825. return true;
  1826. },
  1827. highlight: function InteractiveAnnotation_highlight() {
  1828. if (this.highlightElement &&
  1829. this.highlightElement.hasAttribute('hidden')) {
  1830. this.highlightElement.removeAttribute('hidden');
  1831. }
  1832. },
  1833. unhighlight: function InteractiveAnnotation_unhighlight() {
  1834. if (this.highlightElement &&
  1835. !this.highlightElement.hasAttribute('hidden')) {
  1836. this.highlightElement.setAttribute('hidden', true);
  1837. }
  1838. },
  1839. initContainer: function InteractiveAnnotation_initContainer() {
  1840. var item = this.data;
  1841. var rect = item.rect;
  1842. var container = this.getEmptyContainer('section', rect, item.borderWidth);
  1843. container.style.backgroundColor = item.color;
  1844. var color = item.color;
  1845. var rgb = [];
  1846. for (var i = 0; i < 3; ++i) {
  1847. rgb[i] = Math.round(color[i] * 255);
  1848. }
  1849. item.colorCssRgb = Util.makeCssRgb(rgb);
  1850. var highlight = document.createElement('div');
  1851. highlight.className = 'annotationHighlight';
  1852. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  1853. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  1854. highlight.setAttribute('hidden', true);
  1855. this.highlightElement = highlight;
  1856. container.appendChild(this.highlightElement);
  1857. return container;
  1858. }
  1859. });
  1860. return InteractiveAnnotation;
  1861. })();
  1862. var TextAnnotation = (function TextAnnotationClosure() {
  1863. function TextAnnotation(params) {
  1864. InteractiveAnnotation.call(this, params);
  1865. if (params.data) {
  1866. return;
  1867. }
  1868. var dict = params.dict;
  1869. var data = this.data;
  1870. var content = dict.get('Contents');
  1871. var title = dict.get('T');
  1872. data.content = stringToPDFString(content || '');
  1873. data.title = stringToPDFString(title || '');
  1874. if (data.hasAppearance) {
  1875. data.name = 'NoIcon';
  1876. } else {
  1877. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  1878. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  1879. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  1880. }
  1881. if (dict.has('C')) {
  1882. data.hasBgColor = true;
  1883. }
  1884. }
  1885. var ANNOT_MIN_SIZE = 10;
  1886. Util.inherit(TextAnnotation, InteractiveAnnotation, {
  1887. getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {
  1888. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  1889. var item = this.data;
  1890. var rect = item.rect;
  1891. // sanity check because of OOo-generated PDFs
  1892. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  1893. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  1894. }
  1895. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  1896. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  1897. }
  1898. var container = this.initContainer();
  1899. container.className = 'annotText';
  1900. var image = document.createElement('img');
  1901. image.style.height = container.style.height;
  1902. image.style.width = container.style.width;
  1903. var iconName = item.name;
  1904. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  1905. iconName.toLowerCase() + '.svg';
  1906. image.alt = '[{{type}} Annotation]';
  1907. image.dataset.l10nId = 'text_annotation_type';
  1908. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  1909. var contentWrapper = document.createElement('div');
  1910. contentWrapper.className = 'annotTextContentWrapper';
  1911. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  1912. contentWrapper.style.top = '-10px';
  1913. var content = document.createElement('div');
  1914. content.className = 'annotTextContent';
  1915. content.setAttribute('hidden', true);
  1916. var i, ii;
  1917. if (item.hasBgColor) {
  1918. var color = item.color;
  1919. var rgb = [];
  1920. for (i = 0; i < 3; ++i) {
  1921. // Enlighten the color (70%)
  1922. var c = Math.round(color[i] * 255);
  1923. rgb[i] = Math.round((255 - c) * 0.7) + c;
  1924. }
  1925. content.style.backgroundColor = Util.makeCssRgb(rgb);
  1926. }
  1927. var title = document.createElement('h1');
  1928. var text = document.createElement('p');
  1929. title.textContent = item.title;
  1930. if (!item.content && !item.title) {
  1931. content.setAttribute('hidden', true);
  1932. } else {
  1933. var e = document.createElement('span');
  1934. var lines = item.content.split(/(?:\r\n?|\n)/);
  1935. for (i = 0, ii = lines.length; i < ii; ++i) {
  1936. var line = lines[i];
  1937. e.appendChild(document.createTextNode(line));
  1938. if (i < (ii - 1)) {
  1939. e.appendChild(document.createElement('br'));
  1940. }
  1941. }
  1942. text.appendChild(e);
  1943. var pinned = false;
  1944. var showAnnotation = function showAnnotation(pin) {
  1945. if (pin) {
  1946. pinned = true;
  1947. }
  1948. if (content.hasAttribute('hidden')) {
  1949. container.style.zIndex += 1;
  1950. content.removeAttribute('hidden');
  1951. }
  1952. };
  1953. var hideAnnotation = function hideAnnotation(unpin) {
  1954. if (unpin) {
  1955. pinned = false;
  1956. }
  1957. if (!content.hasAttribute('hidden') && !pinned) {
  1958. container.style.zIndex -= 1;
  1959. content.setAttribute('hidden', true);
  1960. }
  1961. };
  1962. var toggleAnnotation = function toggleAnnotation() {
  1963. if (pinned) {
  1964. hideAnnotation(true);
  1965. } else {
  1966. showAnnotation(true);
  1967. }
  1968. };
  1969. image.addEventListener('click', function image_clickHandler() {
  1970. toggleAnnotation();
  1971. }, false);
  1972. image.addEventListener('mouseover', function image_mouseOverHandler() {
  1973. showAnnotation();
  1974. }, false);
  1975. image.addEventListener('mouseout', function image_mouseOutHandler() {
  1976. hideAnnotation();
  1977. }, false);
  1978. content.addEventListener('click', function content_clickHandler() {
  1979. hideAnnotation(true);
  1980. }, false);
  1981. }
  1982. content.appendChild(title);
  1983. content.appendChild(text);
  1984. contentWrapper.appendChild(content);
  1985. container.appendChild(image);
  1986. container.appendChild(contentWrapper);
  1987. return container;
  1988. }
  1989. });
  1990. return TextAnnotation;
  1991. })();
  1992. var LinkAnnotation = (function LinkAnnotationClosure() {
  1993. function LinkAnnotation(params) {
  1994. InteractiveAnnotation.call(this, params);
  1995. if (params.data) {
  1996. return;
  1997. }
  1998. var dict = params.dict;
  1999. var data = this.data;
  2000. var action = dict.get('A');
  2001. if (action) {
  2002. var linkType = action.get('S').name;
  2003. if (linkType === 'URI') {
  2004. var url = action.get('URI');
  2005. if (isName(url)) {
  2006. // Some bad PDFs do not put parentheses around relative URLs.
  2007. url = '/' + url.name;
  2008. } else if (url) {
  2009. url = addDefaultProtocolToUrl(url);
  2010. }
  2011. // TODO: pdf spec mentions urls can be relative to a Base
  2012. // entry in the dictionary.
  2013. if (!isValidUrl(url, false)) {
  2014. url = '';
  2015. }
  2016. data.url = url;
  2017. } else if (linkType === 'GoTo') {
  2018. data.dest = action.get('D');
  2019. } else if (linkType === 'GoToR') {
  2020. var urlDict = action.get('F');
  2021. if (isDict(urlDict)) {
  2022. // We assume that the 'url' is a Filspec dictionary
  2023. // and fetch the url without checking any further
  2024. url = urlDict.get('F') || '';
  2025. }
  2026. // TODO: pdf reference says that GoToR
  2027. // can also have 'NewWindow' attribute
  2028. if (!isValidUrl(url, false)) {
  2029. url = '';
  2030. }
  2031. data.url = url;
  2032. data.dest = action.get('D');
  2033. } else if (linkType === 'Named') {
  2034. data.action = action.get('N').name;
  2035. } else {
  2036. warn('unrecognized link type: ' + linkType);
  2037. }
  2038. } else if (dict.has('Dest')) {
  2039. // simple destination link
  2040. var dest = dict.get('Dest');
  2041. data.dest = isName(dest) ? dest.name : dest;
  2042. }
  2043. }
  2044. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  2045. function addDefaultProtocolToUrl(url) {
  2046. if (url && url.indexOf('www.') === 0) {
  2047. return ('http://' + url);
  2048. }
  2049. return url;
  2050. }
  2051. Util.inherit(LinkAnnotation, InteractiveAnnotation, {
  2052. hasOperatorList: function LinkAnnotation_hasOperatorList() {
  2053. return false;
  2054. },
  2055. getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {
  2056. var container = this.initContainer();
  2057. container.className = 'annotLink';
  2058. var item = this.data;
  2059. container.style.borderColor = item.colorCssRgb;
  2060. container.style.borderStyle = 'solid';
  2061. var link = document.createElement('a');
  2062. link.href = link.title = this.data.url || '';
  2063. container.appendChild(link);
  2064. return container;
  2065. }
  2066. });
  2067. return LinkAnnotation;
  2068. })();
  2069. /**
  2070. * The maximum allowed image size in total pixels e.g. width * height. Images
  2071. * above this value will not be drawn. Use -1 for no limit.
  2072. * @var {number}
  2073. */
  2074. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  2075. -1 : PDFJS.maxImageSize);
  2076. /**
  2077. * The url of where the predefined Adobe CMaps are located. Include trailing
  2078. * slash.
  2079. * @var {string}
  2080. */
  2081. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  2082. /**
  2083. * Specifies if CMaps are binary packed.
  2084. * @var {boolean}
  2085. */
  2086. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  2087. /*
  2088. * By default fonts are converted to OpenType fonts and loaded via font face
  2089. * rules. If disabled, the font will be rendered using a built in font renderer
  2090. * that constructs the glyphs with primitive path commands.
  2091. * @var {boolean}
  2092. */
  2093. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  2094. false : PDFJS.disableFontFace);
  2095. /**
  2096. * Path for image resources, mainly for annotation icons. Include trailing
  2097. * slash.
  2098. * @var {string}
  2099. */
  2100. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  2101. '' : PDFJS.imageResourcesPath);
  2102. /**
  2103. * Disable the web worker and run all code on the main thread. This will happen
  2104. * automatically if the browser doesn't support workers or sending typed arrays
  2105. * to workers.
  2106. * @var {boolean}
  2107. */
  2108. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  2109. false : PDFJS.disableWorker);
  2110. /**
  2111. * Path and filename of the worker file. Required when the worker is enabled in
  2112. * development mode. If unspecified in the production build, the worker will be
  2113. * loaded based on the location of the pdf.js file.
  2114. * @var {string}
  2115. */
  2116. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  2117. /**
  2118. * Disable range request loading of PDF files. When enabled and if the server
  2119. * supports partial content requests then the PDF will be fetched in chunks.
  2120. * Enabled (false) by default.
  2121. * @var {boolean}
  2122. */
  2123. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  2124. false : PDFJS.disableRange);
  2125. /**
  2126. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  2127. * will automatically keep fetching more data even if it isn't needed to display
  2128. * the current page. This default behavior can be disabled.
  2129. * @var {boolean}
  2130. */
  2131. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  2132. false : PDFJS.disableAutoFetch);
  2133. /**
  2134. * Enables special hooks for debugging PDF.js.
  2135. * @var {boolean}
  2136. */
  2137. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  2138. /**
  2139. * Enables transfer usage in postMessage for ArrayBuffers.
  2140. * @var {boolean}
  2141. */
  2142. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  2143. true : PDFJS.postMessageTransfers);
  2144. /**
  2145. * Disables URL.createObjectURL usage.
  2146. * @var {boolean}
  2147. */
  2148. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  2149. false : PDFJS.disableCreateObjectURL);
  2150. /**
  2151. * Disables WebGL usage.
  2152. * @var {boolean}
  2153. */
  2154. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  2155. true : PDFJS.disableWebGL);
  2156. /**
  2157. * Enables CSS only zooming.
  2158. * @var {boolean}
  2159. */
  2160. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  2161. false : PDFJS.useOnlyCssZoom);
  2162. /**
  2163. * Controls the logging level.
  2164. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  2165. * - errors
  2166. * - warnings [default]
  2167. * - infos
  2168. * @var {number}
  2169. */
  2170. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  2171. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  2172. /**
  2173. * The maximum supported canvas size in total pixels e.g. width * height.
  2174. * The default value is 4096 * 4096. Use -1 for no limit.
  2175. * @var {number}
  2176. */
  2177. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  2178. 16777216 : PDFJS.maxCanvasPixels);
  2179. /**
  2180. * Document initialization / loading parameters object.
  2181. *
  2182. * @typedef {Object} DocumentInitParameters
  2183. * @property {string} url - The URL of the PDF.
  2184. * @property {TypedArray} data - A typed array with PDF data.
  2185. * @property {Object} httpHeaders - Basic authentication headers.
  2186. * @property {boolean} withCredentials - Indicates whether or not cross-site
  2187. * Access-Control requests should be made using credentials such as cookies
  2188. * or authorization headers. The default is false.
  2189. * @property {string} password - For decrypting password-protected PDFs.
  2190. * @property {TypedArray} initialData - A typed array with the first portion or
  2191. * all of the pdf data. Used by the extension since some data is already
  2192. * loaded before the switch to range requests.
  2193. */
  2194. /**
  2195. * This is the main entry point for loading a PDF and interacting with it.
  2196. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  2197. * is used, which means it must follow the same origin rules that any XHR does
  2198. * e.g. No cross domain requests without CORS.
  2199. *
  2200. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  2201. * where a PDF is located, a typed array (Uint8Array) already populated with
  2202. * data or parameter object.
  2203. *
  2204. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  2205. * to manually serve range requests for data in the PDF. See viewer.js for
  2206. * an example of pdfDataRangeTransport's interface.
  2207. *
  2208. * @param {function} passwordCallback is optional. It is used to request a
  2209. * password if wrong or no password was provided. The callback receives two
  2210. * parameters: function that needs to be called with new password and reason
  2211. * (see {PasswordResponses}).
  2212. *
  2213. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  2214. * object.
  2215. */
  2216. PDFJS.getDocument = function getDocument(source,
  2217. pdfDataRangeTransport,
  2218. passwordCallback,
  2219. progressCallback) {
  2220. var workerInitializedCapability, workerReadyCapability, transport;
  2221. if (typeof source === 'string') {
  2222. source = { url: source };
  2223. } else if (isArrayBuffer(source)) {
  2224. source = { data: source };
  2225. } else if (typeof source !== 'object') {
  2226. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  2227. 'string or a parameter object');
  2228. }
  2229. if (!source.url && !source.data) {
  2230. error('Invalid parameter array, need either .data or .url');
  2231. }
  2232. // copy/use all keys as is except 'url' -- full path is required
  2233. var params = {};
  2234. for (var key in source) {
  2235. if (key === 'url' && typeof window !== 'undefined') {
  2236. params[key] = combineUrl(window.location.href, source[key]);
  2237. continue;
  2238. }
  2239. params[key] = source[key];
  2240. }
  2241. workerInitializedCapability = createPromiseCapability();
  2242. workerReadyCapability = createPromiseCapability();
  2243. transport = new WorkerTransport(workerInitializedCapability,
  2244. workerReadyCapability, pdfDataRangeTransport,
  2245. progressCallback);
  2246. workerInitializedCapability.promise.then(function transportInitialized() {
  2247. transport.passwordCallback = passwordCallback;
  2248. transport.fetchDocument(params);
  2249. });
  2250. return workerReadyCapability.promise;
  2251. };
  2252. /**
  2253. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  2254. * properties that can be read synchronously.
  2255. * @class
  2256. */
  2257. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  2258. function PDFDocumentProxy(pdfInfo, transport) {
  2259. this.pdfInfo = pdfInfo;
  2260. this.transport = transport;
  2261. }
  2262. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  2263. /**
  2264. * @return {number} Total number of pages the PDF contains.
  2265. */
  2266. get numPages() {
  2267. return this.pdfInfo.numPages;
  2268. },
  2269. /**
  2270. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  2271. * unique.
  2272. */
  2273. get fingerprint() {
  2274. return this.pdfInfo.fingerprint;
  2275. },
  2276. /**
  2277. * @param {number} pageNumber The page number to get. The first page is 1.
  2278. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  2279. * object.
  2280. */
  2281. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  2282. return this.transport.getPage(pageNumber);
  2283. },
  2284. /**
  2285. * @param {{num: number, gen: number}} ref The page reference. Must have
  2286. * the 'num' and 'gen' properties.
  2287. * @return {Promise} A promise that is resolved with the page index that is
  2288. * associated with the reference.
  2289. */
  2290. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  2291. return this.transport.getPageIndex(ref);
  2292. },
  2293. /**
  2294. * @return {Promise} A promise that is resolved with a lookup table for
  2295. * mapping named destinations to reference numbers.
  2296. */
  2297. getDestinations: function PDFDocumentProxy_getDestinations() {
  2298. return this.transport.getDestinations();
  2299. },
  2300. /**
  2301. * @return {Promise} A promise that is resolved with a lookup table for
  2302. * mapping named attachments to their content.
  2303. */
  2304. getAttachments: function PDFDocumentProxy_getAttachments() {
  2305. return this.transport.getAttachments();
  2306. },
  2307. /**
  2308. * @return {Promise} A promise that is resolved with an array of all the
  2309. * JavaScript strings in the name tree.
  2310. */
  2311. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  2312. return this.transport.getJavaScript();
  2313. },
  2314. /**
  2315. * @return {Promise} A promise that is resolved with an {Array} that is a
  2316. * tree outline (if it has one) of the PDF. The tree is in the format of:
  2317. * [
  2318. * {
  2319. * title: string,
  2320. * bold: boolean,
  2321. * italic: boolean,
  2322. * color: rgb array,
  2323. * dest: dest obj,
  2324. * items: array of more items like this
  2325. * },
  2326. * ...
  2327. * ].
  2328. */
  2329. getOutline: function PDFDocumentProxy_getOutline() {
  2330. return this.transport.getOutline();
  2331. },
  2332. /**
  2333. * @return {Promise} A promise that is resolved with an {Object} that has
  2334. * info and metadata properties. Info is an {Object} filled with anything
  2335. * available in the information dictionary and similarly metadata is a
  2336. * {Metadata} object with information from the metadata section of the PDF.
  2337. */
  2338. getMetadata: function PDFDocumentProxy_getMetadata() {
  2339. return this.transport.getMetadata();
  2340. },
  2341. /**
  2342. * @return {Promise} A promise that is resolved with a TypedArray that has
  2343. * the raw data from the PDF.
  2344. */
  2345. getData: function PDFDocumentProxy_getData() {
  2346. return this.transport.getData();
  2347. },
  2348. /**
  2349. * @return {Promise} A promise that is resolved when the document's data
  2350. * is loaded. It is resolved with an {Object} that contains the length
  2351. * property that indicates size of the PDF data in bytes.
  2352. */
  2353. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  2354. return this.transport.downloadInfoCapability.promise;
  2355. },
  2356. /**
  2357. * Cleans up resources allocated by the document, e.g. created @font-face.
  2358. */
  2359. cleanup: function PDFDocumentProxy_cleanup() {
  2360. this.transport.startCleanup();
  2361. },
  2362. /**
  2363. * Destroys current document instance and terminates worker.
  2364. */
  2365. destroy: function PDFDocumentProxy_destroy() {
  2366. this.transport.destroy();
  2367. }
  2368. };
  2369. return PDFDocumentProxy;
  2370. })();
  2371. /**
  2372. * Page text content.
  2373. *
  2374. * @typedef {Object} TextContent
  2375. * @property {array} items - array of {@link TextItem}
  2376. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  2377. * name.
  2378. */
  2379. /**
  2380. * Page text content part.
  2381. *
  2382. * @typedef {Object} TextItem
  2383. * @property {string} str - text content.
  2384. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  2385. * @property {array} transform - transformation matrix.
  2386. * @property {number} width - width in device space.
  2387. * @property {number} height - height in device space.
  2388. * @property {string} fontName - font name used by pdf.js for converted font.
  2389. */
  2390. /**
  2391. * Text style.
  2392. *
  2393. * @typedef {Object} TextStyle
  2394. * @property {number} ascent - font ascent.
  2395. * @property {number} descent - font descent.
  2396. * @property {boolean} vertical - text is in vertical mode.
  2397. * @property {string} fontFamily - possible font family
  2398. */
  2399. /**
  2400. * Page render parameters.
  2401. *
  2402. * @typedef {Object} RenderParameters
  2403. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  2404. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  2405. * calling of PDFPage.getViewport method.
  2406. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  2407. * (default value is 'display').
  2408. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  2409. * endLayout and appendImage functions.
  2410. * @property {function} continueCallback - (optional) A function that will be
  2411. * called each time the rendering is paused. To continue
  2412. * rendering call the function that is the first argument
  2413. * to the callback.
  2414. */
  2415. /**
  2416. * Proxy to a PDFPage in the worker thread.
  2417. * @class
  2418. */
  2419. var PDFPageProxy = (function PDFPageProxyClosure() {
  2420. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2421. this.pageIndex = pageIndex;
  2422. this.pageInfo = pageInfo;
  2423. this.transport = transport;
  2424. this.stats = new StatTimer();
  2425. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2426. this.commonObjs = transport.commonObjs;
  2427. this.objs = new PDFObjects();
  2428. this.cleanupAfterRender = false;
  2429. this.pendingDestroy = false;
  2430. this.intentStates = {};
  2431. }
  2432. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2433. /**
  2434. * @return {number} Page number of the page. First page is 1.
  2435. */
  2436. get pageNumber() {
  2437. return this.pageIndex + 1;
  2438. },
  2439. /**
  2440. * @return {number} The number of degrees the page is rotated clockwise.
  2441. */
  2442. get rotate() {
  2443. return this.pageInfo.rotate;
  2444. },
  2445. /**
  2446. * @return {Object} The reference that points to this page. It has 'num' and
  2447. * 'gen' properties.
  2448. */
  2449. get ref() {
  2450. return this.pageInfo.ref;
  2451. },
  2452. /**
  2453. * @return {Array} An array of the visible portion of the PDF page in the
  2454. * user space units - [x1, y1, x2, y2].
  2455. */
  2456. get view() {
  2457. return this.pageInfo.view;
  2458. },
  2459. /**
  2460. * @param {number} scale The desired scale of the viewport.
  2461. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2462. * defaults to the page rotation.
  2463. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2464. * along with transforms required for rendering.
  2465. */
  2466. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2467. if (arguments.length < 2) {
  2468. rotate = this.rotate;
  2469. }
  2470. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2471. },
  2472. /**
  2473. * @return {Promise} A promise that is resolved with an {Array} of the
  2474. * annotation objects.
  2475. */
  2476. getAnnotations: function PDFPageProxy_getAnnotations() {
  2477. if (this.annotationsPromise) {
  2478. return this.annotationsPromise;
  2479. }
  2480. var promise = this.transport.getAnnotations(this.pageIndex);
  2481. this.annotationsPromise = promise;
  2482. return promise;
  2483. },
  2484. /**
  2485. * Begins the process of rendering a page to the desired context.
  2486. * @param {RenderParameters} params Page render parameters.
  2487. * @return {RenderTask} An object that contains the promise, which
  2488. * is resolved when the page finishes rendering.
  2489. */
  2490. render: function PDFPageProxy_render(params) {
  2491. var stats = this.stats;
  2492. stats.time('Overall');
  2493. // If there was a pending destroy cancel it so no cleanup happens during
  2494. // this call to render.
  2495. this.pendingDestroy = false;
  2496. var renderingIntent = ('intent' in params ?
  2497. (params.intent == 'print' ? 'print' : 'display') : 'display');
  2498. if (!this.intentStates[renderingIntent]) {
  2499. this.intentStates[renderingIntent] = {};
  2500. }
  2501. var intentState = this.intentStates[renderingIntent];
  2502. // If there's no displayReadyCapability yet, then the operatorList
  2503. // was never requested before. Make the request and create the promise.
  2504. if (!intentState.displayReadyCapability) {
  2505. intentState.receivingOperatorList = true;
  2506. intentState.displayReadyCapability = createPromiseCapability();
  2507. intentState.operatorList = {
  2508. fnArray: [],
  2509. argsArray: [],
  2510. lastChunk: false
  2511. };
  2512. this.stats.time('Page Request');
  2513. this.transport.messageHandler.send('RenderPageRequest', {
  2514. pageIndex: this.pageNumber - 1,
  2515. intent: renderingIntent
  2516. });
  2517. }
  2518. var internalRenderTask = new InternalRenderTask(complete, params,
  2519. this.objs,
  2520. this.commonObjs,
  2521. intentState.operatorList,
  2522. this.pageNumber);
  2523. if (!intentState.renderTasks) {
  2524. intentState.renderTasks = [];
  2525. }
  2526. intentState.renderTasks.push(internalRenderTask);
  2527. var renderTask = new RenderTask(internalRenderTask);
  2528. var self = this;
  2529. intentState.displayReadyCapability.promise.then(
  2530. function pageDisplayReadyPromise(transparency) {
  2531. if (self.pendingDestroy) {
  2532. complete();
  2533. return;
  2534. }
  2535. stats.time('Rendering');
  2536. internalRenderTask.initalizeGraphics(transparency);
  2537. internalRenderTask.operatorListChanged();
  2538. },
  2539. function pageDisplayReadPromiseError(reason) {
  2540. complete(reason);
  2541. }
  2542. );
  2543. function complete(error) {
  2544. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2545. if (i >= 0) {
  2546. intentState.renderTasks.splice(i, 1);
  2547. }
  2548. if (self.cleanupAfterRender) {
  2549. self.pendingDestroy = true;
  2550. }
  2551. self._tryDestroy();
  2552. if (error) {
  2553. internalRenderTask.capability.reject(error);
  2554. } else {
  2555. internalRenderTask.capability.resolve();
  2556. }
  2557. stats.timeEnd('Rendering');
  2558. stats.timeEnd('Overall');
  2559. }
  2560. return renderTask;
  2561. },
  2562. /**
  2563. * @return {Promise} That is resolved a {@link TextContent}
  2564. * object that represent the page text content.
  2565. */
  2566. getTextContent: function PDFPageProxy_getTextContent() {
  2567. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2568. pageIndex: this.pageNumber - 1
  2569. });
  2570. },
  2571. /**
  2572. * Destroys resources allocated by the page.
  2573. */
  2574. destroy: function PDFPageProxy_destroy() {
  2575. this.pendingDestroy = true;
  2576. this._tryDestroy();
  2577. },
  2578. /**
  2579. * For internal use only. Attempts to clean up if rendering is in a state
  2580. * where that's possible.
  2581. * @ignore
  2582. */
  2583. _tryDestroy: function PDFPageProxy__destroy() {
  2584. if (!this.pendingDestroy ||
  2585. Object.keys(this.intentStates).some(function(intent) {
  2586. var intentState = this.intentStates[intent];
  2587. return (intentState.renderTasks.length !== 0 ||
  2588. intentState.receivingOperatorList);
  2589. }, this)) {
  2590. return;
  2591. }
  2592. Object.keys(this.intentStates).forEach(function(intent) {
  2593. delete this.intentStates[intent];
  2594. }, this);
  2595. this.objs.clear();
  2596. this.annotationsPromise = null;
  2597. this.pendingDestroy = false;
  2598. },
  2599. /**
  2600. * For internal use only.
  2601. * @ignore
  2602. */
  2603. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2604. intent) {
  2605. var intentState = this.intentStates[intent];
  2606. intentState.displayReadyCapability.resolve(transparency);
  2607. },
  2608. /**
  2609. * For internal use only.
  2610. * @ignore
  2611. */
  2612. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2613. intent) {
  2614. var intentState = this.intentStates[intent];
  2615. var i, ii;
  2616. // Add the new chunk to the current operator list.
  2617. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2618. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2619. intentState.operatorList.argsArray.push(
  2620. operatorListChunk.argsArray[i]);
  2621. }
  2622. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2623. // Notify all the rendering tasks there are more operators to be consumed.
  2624. for (i = 0; i < intentState.renderTasks.length; i++) {
  2625. intentState.renderTasks[i].operatorListChanged();
  2626. }
  2627. if (operatorListChunk.lastChunk) {
  2628. intentState.receivingOperatorList = false;
  2629. this._tryDestroy();
  2630. }
  2631. }
  2632. };
  2633. return PDFPageProxy;
  2634. })();
  2635. /**
  2636. * For internal use only.
  2637. * @ignore
  2638. */
  2639. var WorkerTransport = (function WorkerTransportClosure() {
  2640. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  2641. pdfDataRangeTransport, progressCallback) {
  2642. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2643. this.workerReadyCapability = workerReadyCapability;
  2644. this.progressCallback = progressCallback;
  2645. this.commonObjs = new PDFObjects();
  2646. this.pageCache = [];
  2647. this.pagePromises = [];
  2648. this.downloadInfoCapability = createPromiseCapability();
  2649. this.passwordCallback = null;
  2650. // If worker support isn't disabled explicit and the browser has worker
  2651. // support, create a new web worker and test if it/the browser fullfills
  2652. // all requirements to run parts of pdf.js in a web worker.
  2653. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2654. // as it arrives on the worker. Chrome added this with version 15.
  2655. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  2656. var workerSrc = PDFJS.workerSrc;
  2657. if (!workerSrc) {
  2658. error('No PDFJS.workerSrc specified');
  2659. }
  2660. try {
  2661. // Some versions of FF can't create a worker on localhost, see:
  2662. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  2663. var worker = new Worker(workerSrc);
  2664. var messageHandler = new MessageHandler('main', worker);
  2665. this.messageHandler = messageHandler;
  2666. messageHandler.on('test', function transportTest(data) {
  2667. var supportTypedArray = data && data.supportTypedArray;
  2668. if (supportTypedArray) {
  2669. this.worker = worker;
  2670. if (!data.supportTransfers) {
  2671. PDFJS.postMessageTransfers = false;
  2672. }
  2673. this.setupMessageHandler(messageHandler);
  2674. workerInitializedCapability.resolve();
  2675. } else {
  2676. globalScope.PDFJS.disableWorker = true;
  2677. this.loadFakeWorkerFiles().then(function() {
  2678. this.setupFakeWorker();
  2679. workerInitializedCapability.resolve();
  2680. }.bind(this));
  2681. }
  2682. }.bind(this));
  2683. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  2684. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  2685. // typed array. Also, checking if we can use transfers.
  2686. try {
  2687. messageHandler.send('test', testObj, [testObj.buffer]);
  2688. } catch (ex) {
  2689. info('Cannot use postMessage transfers');
  2690. testObj[0] = 0;
  2691. messageHandler.send('test', testObj);
  2692. }
  2693. return;
  2694. } catch (e) {
  2695. info('The worker has been disabled.');
  2696. }
  2697. }
  2698. // Either workers are disabled, not supported or have thrown an exception.
  2699. // Thus, we fallback to a faked worker.
  2700. globalScope.PDFJS.disableWorker = true;
  2701. this.loadFakeWorkerFiles().then(function() {
  2702. this.setupFakeWorker();
  2703. workerInitializedCapability.resolve();
  2704. }.bind(this));
  2705. }
  2706. WorkerTransport.prototype = {
  2707. destroy: function WorkerTransport_destroy() {
  2708. this.pageCache = [];
  2709. this.pagePromises = [];
  2710. var self = this;
  2711. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2712. FontLoader.clear();
  2713. if (self.worker) {
  2714. self.worker.terminate();
  2715. }
  2716. });
  2717. },
  2718. loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {
  2719. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2720. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2721. // In the developer build load worker_loader which in turn loads all the
  2722. // other files and resolves the promise. In production only the
  2723. // pdf.worker.js file is needed.
  2724. Util.loadScript(PDFJS.workerSrc, function() {
  2725. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2726. });
  2727. }
  2728. return PDFJS.fakeWorkerFilesLoadedCapability.promise;
  2729. },
  2730. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2731. warn('Setting up fake worker.');
  2732. // If we don't use a worker, just post/sendMessage to the main thread.
  2733. var fakeWorker = {
  2734. postMessage: function WorkerTransport_postMessage(obj) {
  2735. fakeWorker.onmessage({data: obj});
  2736. },
  2737. terminate: function WorkerTransport_terminate() {}
  2738. };
  2739. var messageHandler = new MessageHandler('main', fakeWorker);
  2740. this.setupMessageHandler(messageHandler);
  2741. // If the main thread is our worker, setup the handling for the messages
  2742. // the main thread sends to it self.
  2743. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2744. },
  2745. setupMessageHandler:
  2746. function WorkerTransport_setupMessageHandler(messageHandler) {
  2747. this.messageHandler = messageHandler;
  2748. function updatePassword(password) {
  2749. messageHandler.send('UpdatePassword', password);
  2750. }
  2751. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2752. if (pdfDataRangeTransport) {
  2753. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2754. messageHandler.send('OnDataRange', {
  2755. begin: begin,
  2756. chunk: chunk
  2757. });
  2758. });
  2759. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2760. messageHandler.send('OnDataProgress', {
  2761. loaded: loaded
  2762. });
  2763. });
  2764. messageHandler.on('RequestDataRange',
  2765. function transportDataRange(data) {
  2766. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2767. }, this);
  2768. }
  2769. messageHandler.on('GetDoc', function transportDoc(data) {
  2770. var pdfInfo = data.pdfInfo;
  2771. this.numPages = data.pdfInfo.numPages;
  2772. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2773. this.pdfDocument = pdfDocument;
  2774. this.workerReadyCapability.resolve(pdfDocument);
  2775. }, this);
  2776. messageHandler.on('NeedPassword', function transportPassword(data) {
  2777. if (this.passwordCallback) {
  2778. return this.passwordCallback(updatePassword,
  2779. PasswordResponses.NEED_PASSWORD);
  2780. }
  2781. this.workerReadyCapability.reject(data.exception.message,
  2782. data.exception);
  2783. }, this);
  2784. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  2785. if (this.passwordCallback) {
  2786. return this.passwordCallback(updatePassword,
  2787. PasswordResponses.INCORRECT_PASSWORD);
  2788. }
  2789. this.workerReadyCapability.reject(data.exception.message,
  2790. data.exception);
  2791. }, this);
  2792. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  2793. this.workerReadyCapability.reject(data.exception.name, data.exception);
  2794. }, this);
  2795. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  2796. this.workerReadyCapability.reject(data.exception.message,
  2797. data.exception);
  2798. }, this);
  2799. messageHandler.on('UnknownError', function transportUnknownError(data) {
  2800. this.workerReadyCapability.reject(data.exception.message,
  2801. data.exception);
  2802. }, this);
  2803. messageHandler.on('DataLoaded', function transportPage(data) {
  2804. this.downloadInfoCapability.resolve(data);
  2805. }, this);
  2806. messageHandler.on('StartRenderPage', function transportRender(data) {
  2807. var page = this.pageCache[data.pageIndex];
  2808. page.stats.timeEnd('Page Request');
  2809. page._startRenderPage(data.transparency, data.intent);
  2810. }, this);
  2811. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2812. var page = this.pageCache[data.pageIndex];
  2813. page._renderPageChunk(data.operatorList, data.intent);
  2814. }, this);
  2815. messageHandler.on('commonobj', function transportObj(data) {
  2816. var id = data[0];
  2817. var type = data[1];
  2818. if (this.commonObjs.hasData(id)) {
  2819. return;
  2820. }
  2821. switch (type) {
  2822. case 'Font':
  2823. var exportedData = data[2];
  2824. var font;
  2825. if ('error' in exportedData) {
  2826. var error = exportedData.error;
  2827. warn('Error during font loading: ' + error);
  2828. this.commonObjs.resolve(id, error);
  2829. break;
  2830. } else {
  2831. font = new FontFace(exportedData);
  2832. }
  2833. FontLoader.bind(
  2834. [font],
  2835. function fontReady(fontObjs) {
  2836. this.commonObjs.resolve(id, font);
  2837. }.bind(this)
  2838. );
  2839. break;
  2840. case 'FontPath':
  2841. this.commonObjs.resolve(id, data[2]);
  2842. break;
  2843. default:
  2844. error('Got unknown common object type ' + type);
  2845. }
  2846. }, this);
  2847. messageHandler.on('obj', function transportObj(data) {
  2848. var id = data[0];
  2849. var pageIndex = data[1];
  2850. var type = data[2];
  2851. var pageProxy = this.pageCache[pageIndex];
  2852. var imageData;
  2853. if (pageProxy.objs.hasData(id)) {
  2854. return;
  2855. }
  2856. switch (type) {
  2857. case 'JpegStream':
  2858. imageData = data[3];
  2859. loadJpegStream(id, imageData, pageProxy.objs);
  2860. break;
  2861. case 'Image':
  2862. imageData = data[3];
  2863. pageProxy.objs.resolve(id, imageData);
  2864. // heuristics that will allow not to store large data
  2865. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2866. if (imageData && 'data' in imageData &&
  2867. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2868. pageProxy.cleanupAfterRender = true;
  2869. }
  2870. break;
  2871. default:
  2872. error('Got unknown object type ' + type);
  2873. }
  2874. }, this);
  2875. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2876. if (this.progressCallback) {
  2877. this.progressCallback({
  2878. loaded: data.loaded,
  2879. total: data.total
  2880. });
  2881. }
  2882. }, this);
  2883. messageHandler.on('DocError', function transportDocError(data) {
  2884. this.workerReadyCapability.reject(data);
  2885. }, this);
  2886. messageHandler.on('PageError', function transportError(data) {
  2887. var page = this.pageCache[data.pageNum - 1];
  2888. var intentState = page.intentStates[data.intent];
  2889. if (intentState.displayReadyCapability.promise) {
  2890. intentState.displayReadyCapability.reject(data.error);
  2891. } else {
  2892. error(data.error);
  2893. }
  2894. }, this);
  2895. messageHandler.on('JpegDecode', function(data) {
  2896. var imageUrl = data[0];
  2897. var components = data[1];
  2898. if (components != 3 && components != 1) {
  2899. return Promise.reject(
  2900. new Error('Only 3 components or 1 component can be returned'));
  2901. }
  2902. return new Promise(function (resolve, reject) {
  2903. var img = new Image();
  2904. img.onload = function () {
  2905. var width = img.width;
  2906. var height = img.height;
  2907. var size = width * height;
  2908. var rgbaLength = size * 4;
  2909. var buf = new Uint8Array(size * components);
  2910. var tmpCanvas = createScratchCanvas(width, height);
  2911. var tmpCtx = tmpCanvas.getContext('2d');
  2912. tmpCtx.drawImage(img, 0, 0);
  2913. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2914. var i, j;
  2915. if (components == 3) {
  2916. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2917. buf[j] = data[i];
  2918. buf[j + 1] = data[i + 1];
  2919. buf[j + 2] = data[i + 2];
  2920. }
  2921. } else if (components == 1) {
  2922. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2923. buf[j] = data[i];
  2924. }
  2925. }
  2926. resolve({ data: buf, width: width, height: height});
  2927. };
  2928. img.onerror = function () {
  2929. reject(new Error('JpegDecode failed to load image'));
  2930. };
  2931. img.src = imageUrl;
  2932. });
  2933. });
  2934. },
  2935. fetchDocument: function WorkerTransport_fetchDocument(source) {
  2936. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2937. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2938. this.messageHandler.send('GetDocRequest', {
  2939. source: source,
  2940. disableRange: PDFJS.disableRange,
  2941. maxImageSize: PDFJS.maxImageSize,
  2942. cMapUrl: PDFJS.cMapUrl,
  2943. cMapPacked: PDFJS.cMapPacked,
  2944. disableFontFace: PDFJS.disableFontFace,
  2945. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2946. verbosity: PDFJS.verbosity
  2947. });
  2948. },
  2949. getData: function WorkerTransport_getData() {
  2950. return this.messageHandler.sendWithPromise('GetData', null);
  2951. },
  2952. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2953. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2954. (pageNumber|0) !== pageNumber) {
  2955. return Promise.reject(new Error('Invalid page request'));
  2956. }
  2957. var pageIndex = pageNumber - 1;
  2958. if (pageIndex in this.pagePromises) {
  2959. return this.pagePromises[pageIndex];
  2960. }
  2961. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2962. pageIndex: pageIndex
  2963. }).then(function (pageInfo) {
  2964. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2965. this.pageCache[pageIndex] = page;
  2966. return page;
  2967. }.bind(this));
  2968. this.pagePromises[pageIndex] = promise;
  2969. return promise;
  2970. },
  2971. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2972. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2973. },
  2974. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2975. return this.messageHandler.sendWithPromise('GetAnnotations',
  2976. { pageIndex: pageIndex });
  2977. },
  2978. getDestinations: function WorkerTransport_getDestinations() {
  2979. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2980. },
  2981. getAttachments: function WorkerTransport_getAttachments() {
  2982. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2983. },
  2984. getJavaScript: function WorkerTransport_getJavaScript() {
  2985. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2986. },
  2987. getOutline: function WorkerTransport_getOutline() {
  2988. return this.messageHandler.sendWithPromise('GetOutline', null);
  2989. },
  2990. getMetadata: function WorkerTransport_getMetadata() {
  2991. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2992. then(function transportMetadata(results) {
  2993. return {
  2994. info: results[0],
  2995. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2996. };
  2997. });
  2998. },
  2999. startCleanup: function WorkerTransport_startCleanup() {
  3000. this.messageHandler.sendWithPromise('Cleanup', null).
  3001. then(function endCleanup() {
  3002. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  3003. var page = this.pageCache[i];
  3004. if (page) {
  3005. page.destroy();
  3006. }
  3007. }
  3008. this.commonObjs.clear();
  3009. FontLoader.clear();
  3010. }.bind(this));
  3011. }
  3012. };
  3013. return WorkerTransport;
  3014. })();
  3015. /**
  3016. * A PDF document and page is built of many objects. E.g. there are objects
  3017. * for fonts, images, rendering code and such. These objects might get processed
  3018. * inside of a worker. The `PDFObjects` implements some basic functions to
  3019. * manage these objects.
  3020. * @ignore
  3021. */
  3022. var PDFObjects = (function PDFObjectsClosure() {
  3023. function PDFObjects() {
  3024. this.objs = {};
  3025. }
  3026. PDFObjects.prototype = {
  3027. /**
  3028. * Internal function.
  3029. * Ensures there is an object defined for `objId`.
  3030. */
  3031. ensureObj: function PDFObjects_ensureObj(objId) {
  3032. if (this.objs[objId]) {
  3033. return this.objs[objId];
  3034. }
  3035. var obj = {
  3036. capability: createPromiseCapability(),
  3037. data: null,
  3038. resolved: false
  3039. };
  3040. this.objs[objId] = obj;
  3041. return obj;
  3042. },
  3043. /**
  3044. * If called *without* callback, this returns the data of `objId` but the
  3045. * object needs to be resolved. If it isn't, this function throws.
  3046. *
  3047. * If called *with* a callback, the callback is called with the data of the
  3048. * object once the object is resolved. That means, if you call this
  3049. * function and the object is already resolved, the callback gets called
  3050. * right away.
  3051. */
  3052. get: function PDFObjects_get(objId, callback) {
  3053. // If there is a callback, then the get can be async and the object is
  3054. // not required to be resolved right now
  3055. if (callback) {
  3056. this.ensureObj(objId).capability.promise.then(callback);
  3057. return null;
  3058. }
  3059. // If there isn't a callback, the user expects to get the resolved data
  3060. // directly.
  3061. var obj = this.objs[objId];
  3062. // If there isn't an object yet or the object isn't resolved, then the
  3063. // data isn't ready yet!
  3064. if (!obj || !obj.resolved) {
  3065. error('Requesting object that isn\'t resolved yet ' + objId);
  3066. }
  3067. return obj.data;
  3068. },
  3069. /**
  3070. * Resolves the object `objId` with optional `data`.
  3071. */
  3072. resolve: function PDFObjects_resolve(objId, data) {
  3073. var obj = this.ensureObj(objId);
  3074. obj.resolved = true;
  3075. obj.data = data;
  3076. obj.capability.resolve(data);
  3077. },
  3078. isResolved: function PDFObjects_isResolved(objId) {
  3079. var objs = this.objs;
  3080. if (!objs[objId]) {
  3081. return false;
  3082. } else {
  3083. return objs[objId].resolved;
  3084. }
  3085. },
  3086. hasData: function PDFObjects_hasData(objId) {
  3087. return this.isResolved(objId);
  3088. },
  3089. /**
  3090. * Returns the data of `objId` if object exists, null otherwise.
  3091. */
  3092. getData: function PDFObjects_getData(objId) {
  3093. var objs = this.objs;
  3094. if (!objs[objId] || !objs[objId].resolved) {
  3095. return null;
  3096. } else {
  3097. return objs[objId].data;
  3098. }
  3099. },
  3100. clear: function PDFObjects_clear() {
  3101. this.objs = {};
  3102. }
  3103. };
  3104. return PDFObjects;
  3105. })();
  3106. /**
  3107. * Allows controlling of the rendering tasks.
  3108. * @class
  3109. */
  3110. var RenderTask = (function RenderTaskClosure() {
  3111. function RenderTask(internalRenderTask) {
  3112. this.internalRenderTask = internalRenderTask;
  3113. /**
  3114. * Promise for rendering task completion.
  3115. * @type {Promise}
  3116. */
  3117. this.promise = this.internalRenderTask.capability.promise;
  3118. }
  3119. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  3120. /**
  3121. * Cancels the rendering task. If the task is currently rendering it will
  3122. * not be cancelled until graphics pauses with a timeout. The promise that
  3123. * this object extends will resolved when cancelled.
  3124. */
  3125. cancel: function RenderTask_cancel() {
  3126. this.internalRenderTask.cancel();
  3127. },
  3128. /**
  3129. * Registers callback to indicate the rendering task completion.
  3130. *
  3131. * @param {function} onFulfilled The callback for the rendering completion.
  3132. * @param {function} onRejected The callback for the rendering failure.
  3133. * @return {Promise} A promise that is resolved after the onFulfilled or
  3134. * onRejected callback.
  3135. */
  3136. then: function RenderTask_then(onFulfilled, onRejected) {
  3137. return this.promise.then(onFulfilled, onRejected);
  3138. }
  3139. };
  3140. return RenderTask;
  3141. })();
  3142. /**
  3143. * For internal use only.
  3144. * @ignore
  3145. */
  3146. var InternalRenderTask = (function InternalRenderTaskClosure() {
  3147. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  3148. pageNumber) {
  3149. this.callback = callback;
  3150. this.params = params;
  3151. this.objs = objs;
  3152. this.commonObjs = commonObjs;
  3153. this.operatorListIdx = null;
  3154. this.operatorList = operatorList;
  3155. this.pageNumber = pageNumber;
  3156. this.running = false;
  3157. this.graphicsReadyCallback = null;
  3158. this.graphicsReady = false;
  3159. this.cancelled = false;
  3160. this.capability = createPromiseCapability();
  3161. // caching this-bound methods
  3162. this._continueBound = this._continue.bind(this);
  3163. this._scheduleNextBound = this._scheduleNext.bind(this);
  3164. this._nextBound = this._next.bind(this);
  3165. }
  3166. InternalRenderTask.prototype = {
  3167. initalizeGraphics:
  3168. function InternalRenderTask_initalizeGraphics(transparency) {
  3169. if (this.cancelled) {
  3170. return;
  3171. }
  3172. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  3173. globalScope.StepperManager.enabled) {
  3174. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  3175. this.stepper.init(this.operatorList);
  3176. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  3177. }
  3178. var params = this.params;
  3179. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  3180. this.objs, params.imageLayer);
  3181. this.gfx.beginDrawing(params.viewport, transparency);
  3182. this.operatorListIdx = 0;
  3183. this.graphicsReady = true;
  3184. if (this.graphicsReadyCallback) {
  3185. this.graphicsReadyCallback();
  3186. }
  3187. },
  3188. cancel: function InternalRenderTask_cancel() {
  3189. this.running = false;
  3190. this.cancelled = true;
  3191. this.callback('cancelled');
  3192. },
  3193. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  3194. if (!this.graphicsReady) {
  3195. if (!this.graphicsReadyCallback) {
  3196. this.graphicsReadyCallback = this._continueBound;
  3197. }
  3198. return;
  3199. }
  3200. if (this.stepper) {
  3201. this.stepper.updateOperatorList(this.operatorList);
  3202. }
  3203. if (this.running) {
  3204. return;
  3205. }
  3206. this._continue();
  3207. },
  3208. _continue: function InternalRenderTask__continue() {
  3209. this.running = true;
  3210. if (this.cancelled) {
  3211. return;
  3212. }
  3213. if (this.params.continueCallback) {
  3214. this.params.continueCallback(this._scheduleNextBound);
  3215. } else {
  3216. this._scheduleNext();
  3217. }
  3218. },
  3219. _scheduleNext: function InternalRenderTask__scheduleNext() {
  3220. window.requestAnimationFrame(this._nextBound);
  3221. },
  3222. _next: function InternalRenderTask__next() {
  3223. if (this.cancelled) {
  3224. return;
  3225. }
  3226. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  3227. this.operatorListIdx,
  3228. this._continueBound,
  3229. this.stepper);
  3230. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  3231. this.running = false;
  3232. if (this.operatorList.lastChunk) {
  3233. this.gfx.endDrawing();
  3234. this.callback();
  3235. }
  3236. }
  3237. }
  3238. };
  3239. return InternalRenderTask;
  3240. })();
  3241. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  3242. function fixMetadata(meta) {
  3243. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  3244. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  3245. function(code, d1, d2, d3) {
  3246. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  3247. });
  3248. var chars = '';
  3249. for (var i = 0; i < bytes.length; i += 2) {
  3250. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  3251. chars += code >= 32 && code < 127 && code != 60 && code != 62 &&
  3252. code != 38 && false ? String.fromCharCode(code) :
  3253. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  3254. }
  3255. return '>' + chars;
  3256. });
  3257. }
  3258. function Metadata(meta) {
  3259. if (typeof meta === 'string') {
  3260. // Ghostscript produces invalid metadata
  3261. meta = fixMetadata(meta);
  3262. var parser = new DOMParser();
  3263. meta = parser.parseFromString(meta, 'application/xml');
  3264. } else if (!(meta instanceof Document)) {
  3265. error('Metadata: Invalid metadata object');
  3266. }
  3267. this.metaDocument = meta;
  3268. this.metadata = {};
  3269. this.parse();
  3270. }
  3271. Metadata.prototype = {
  3272. parse: function Metadata_parse() {
  3273. var doc = this.metaDocument;
  3274. var rdf = doc.documentElement;
  3275. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  3276. rdf = rdf.firstChild;
  3277. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3278. rdf = rdf.nextSibling;
  3279. }
  3280. }
  3281. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  3282. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3283. return;
  3284. }
  3285. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3286. for (i = 0, length = children.length; i < length; i++) {
  3287. desc = children[i];
  3288. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3289. continue;
  3290. }
  3291. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3292. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3293. entry = desc.childNodes[ii];
  3294. name = entry.nodeName.toLowerCase();
  3295. this.metadata[name] = entry.textContent.trim();
  3296. }
  3297. }
  3298. }
  3299. },
  3300. get: function Metadata_get(name) {
  3301. return this.metadata[name] || null;
  3302. },
  3303. has: function Metadata_has(name) {
  3304. return typeof this.metadata[name] !== 'undefined';
  3305. }
  3306. };
  3307. return Metadata;
  3308. })();
  3309. // <canvas> contexts store most of the state we need natively.
  3310. // However, PDF needs a bit more state, which we store here.
  3311. // Minimal font size that would be used during canvas fillText operations.
  3312. var MIN_FONT_SIZE = 16;
  3313. var MAX_GROUP_SIZE = 4096;
  3314. var COMPILE_TYPE3_GLYPHS = true;
  3315. function createScratchCanvas(width, height) {
  3316. var canvas = document.createElement('canvas');
  3317. canvas.width = width;
  3318. canvas.height = height;
  3319. return canvas;
  3320. }
  3321. function addContextCurrentTransform(ctx) {
  3322. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  3323. if (!ctx.mozCurrentTransform) {
  3324. // Store the original context
  3325. ctx._scaleX = ctx._scaleX || 1.0;
  3326. ctx._scaleY = ctx._scaleY || 1.0;
  3327. ctx._originalSave = ctx.save;
  3328. ctx._originalRestore = ctx.restore;
  3329. ctx._originalRotate = ctx.rotate;
  3330. ctx._originalScale = ctx.scale;
  3331. ctx._originalTranslate = ctx.translate;
  3332. ctx._originalTransform = ctx.transform;
  3333. ctx._originalSetTransform = ctx.setTransform;
  3334. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  3335. ctx._transformStack = [];
  3336. Object.defineProperty(ctx, 'mozCurrentTransform', {
  3337. get: function getCurrentTransform() {
  3338. return this._transformMatrix;
  3339. }
  3340. });
  3341. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  3342. get: function getCurrentTransformInverse() {
  3343. // Calculation done using WolframAlpha:
  3344. // http://www.wolframalpha.com/input/?
  3345. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  3346. var m = this._transformMatrix;
  3347. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  3348. var ad_bc = a * d - b * c;
  3349. var bc_ad = b * c - a * d;
  3350. return [
  3351. d / ad_bc,
  3352. b / bc_ad,
  3353. c / bc_ad,
  3354. a / ad_bc,
  3355. (d * e - c * f) / bc_ad,
  3356. (b * e - a * f) / ad_bc
  3357. ];
  3358. }
  3359. });
  3360. ctx.save = function ctxSave() {
  3361. var old = this._transformMatrix;
  3362. this._transformStack.push(old);
  3363. this._transformMatrix = old.slice(0, 6);
  3364. this._originalSave();
  3365. };
  3366. ctx.restore = function ctxRestore() {
  3367. var prev = this._transformStack.pop();
  3368. if (prev) {
  3369. this._transformMatrix = prev;
  3370. this._originalRestore();
  3371. }
  3372. };
  3373. ctx.translate = function ctxTranslate(x, y) {
  3374. var m = this._transformMatrix;
  3375. m[4] = m[0] * x + m[2] * y + m[4];
  3376. m[5] = m[1] * x + m[3] * y + m[5];
  3377. this._originalTranslate(x, y);
  3378. };
  3379. ctx.scale = function ctxScale(x, y) {
  3380. var m = this._transformMatrix;
  3381. m[0] = m[0] * x;
  3382. m[1] = m[1] * x;
  3383. m[2] = m[2] * y;
  3384. m[3] = m[3] * y;
  3385. this._originalScale(x, y);
  3386. };
  3387. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3388. var m = this._transformMatrix;
  3389. this._transformMatrix = [
  3390. m[0] * a + m[2] * b,
  3391. m[1] * a + m[3] * b,
  3392. m[0] * c + m[2] * d,
  3393. m[1] * c + m[3] * d,
  3394. m[0] * e + m[2] * f + m[4],
  3395. m[1] * e + m[3] * f + m[5]
  3396. ];
  3397. ctx._originalTransform(a, b, c, d, e, f);
  3398. };
  3399. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3400. this._transformMatrix = [a, b, c, d, e, f];
  3401. ctx._originalSetTransform(a, b, c, d, e, f);
  3402. };
  3403. ctx.rotate = function ctxRotate(angle) {
  3404. var cosValue = Math.cos(angle);
  3405. var sinValue = Math.sin(angle);
  3406. var m = this._transformMatrix;
  3407. this._transformMatrix = [
  3408. m[0] * cosValue + m[2] * sinValue,
  3409. m[1] * cosValue + m[3] * sinValue,
  3410. m[0] * (-sinValue) + m[2] * cosValue,
  3411. m[1] * (-sinValue) + m[3] * cosValue,
  3412. m[4],
  3413. m[5]
  3414. ];
  3415. this._originalRotate(angle);
  3416. };
  3417. }
  3418. }
  3419. var CachedCanvases = (function CachedCanvasesClosure() {
  3420. var cache = {};
  3421. return {
  3422. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3423. trackTransform) {
  3424. var canvasEntry;
  3425. if (id in cache) {
  3426. canvasEntry = cache[id];
  3427. canvasEntry.canvas.width = width;
  3428. canvasEntry.canvas.height = height;
  3429. // reset canvas transform for emulated mozCurrentTransform, if needed
  3430. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3431. } else {
  3432. var canvas = createScratchCanvas(width, height);
  3433. var ctx = canvas.getContext('2d');
  3434. if (trackTransform) {
  3435. addContextCurrentTransform(ctx);
  3436. }
  3437. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3438. }
  3439. return canvasEntry;
  3440. },
  3441. clear: function () {
  3442. cache = {};
  3443. }
  3444. };
  3445. })();
  3446. function compileType3Glyph(imgData) {
  3447. var POINT_TO_PROCESS_LIMIT = 1000;
  3448. var width = imgData.width, height = imgData.height;
  3449. var i, j, j0, width1 = width + 1;
  3450. var points = new Uint8Array(width1 * (height + 1));
  3451. var POINT_TYPES =
  3452. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3453. // decodes bit-packed mask data
  3454. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3455. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3456. for (i = 0, ii = data0.length; i < ii; i++) {
  3457. var mask = 128, elem = data0[i];
  3458. while (mask > 0) {
  3459. data[pos++] = (elem & mask) ? 0 : 255;
  3460. mask >>= 1;
  3461. }
  3462. }
  3463. // finding iteresting points: every point is located between mask pixels,
  3464. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3465. // will have flags assigned based on neighboring mask pixels:
  3466. // 4 | 8
  3467. // --P--
  3468. // 2 | 1
  3469. // We are interested only in points with the flags:
  3470. // - outside corners: 1, 2, 4, 8;
  3471. // - inside corners: 7, 11, 13, 14;
  3472. // - and, intersections: 5, 10.
  3473. var count = 0;
  3474. pos = 0;
  3475. if (data[pos] !== 0) {
  3476. points[0] = 1;
  3477. ++count;
  3478. }
  3479. for (j = 1; j < width; j++) {
  3480. if (data[pos] !== data[pos + 1]) {
  3481. points[j] = data[pos] ? 2 : 1;
  3482. ++count;
  3483. }
  3484. pos++;
  3485. }
  3486. if (data[pos] !== 0) {
  3487. points[j] = 2;
  3488. ++count;
  3489. }
  3490. for (i = 1; i < height; i++) {
  3491. pos = i * lineSize;
  3492. j0 = i * width1;
  3493. if (data[pos - lineSize] !== data[pos]) {
  3494. points[j0] = data[pos] ? 1 : 8;
  3495. ++count;
  3496. }
  3497. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3498. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3499. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3500. for (j = 1; j < width; j++) {
  3501. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3502. (data[pos - lineSize + 1] ? 8 : 0);
  3503. if (POINT_TYPES[sum]) {
  3504. points[j0 + j] = POINT_TYPES[sum];
  3505. ++count;
  3506. }
  3507. pos++;
  3508. }
  3509. if (data[pos - lineSize] !== data[pos]) {
  3510. points[j0 + j] = data[pos] ? 2 : 4;
  3511. ++count;
  3512. }
  3513. if (count > POINT_TO_PROCESS_LIMIT) {
  3514. return null;
  3515. }
  3516. }
  3517. pos = lineSize * (height - 1);
  3518. j0 = i * width1;
  3519. if (data[pos] !== 0) {
  3520. points[j0] = 8;
  3521. ++count;
  3522. }
  3523. for (j = 1; j < width; j++) {
  3524. if (data[pos] !== data[pos + 1]) {
  3525. points[j0 + j] = data[pos] ? 4 : 8;
  3526. ++count;
  3527. }
  3528. pos++;
  3529. }
  3530. if (data[pos] !== 0) {
  3531. points[j0 + j] = 4;
  3532. ++count;
  3533. }
  3534. if (count > POINT_TO_PROCESS_LIMIT) {
  3535. return null;
  3536. }
  3537. // building outlines
  3538. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3539. var outlines = [];
  3540. for (i = 0; count && i <= height; i++) {
  3541. var p = i * width1;
  3542. var end = p + width;
  3543. while (p < end && !points[p]) {
  3544. p++;
  3545. }
  3546. if (p === end) {
  3547. continue;
  3548. }
  3549. var coords = [p % width1, i];
  3550. var type = points[p], p0 = p, pp;
  3551. do {
  3552. var step = steps[type];
  3553. do {
  3554. p += step;
  3555. } while (!points[p]);
  3556. pp = points[p];
  3557. if (pp !== 5 && pp !== 10) {
  3558. // set new direction
  3559. type = pp;
  3560. // delete mark
  3561. points[p] = 0;
  3562. } else { // type is 5 or 10, ie, a crossing
  3563. // set new direction
  3564. type = pp & ((0x33 * type) >> 4);
  3565. // set new type for "future hit"
  3566. points[p] &= (type >> 2 | type << 2);
  3567. }
  3568. coords.push(p % width1);
  3569. coords.push((p / width1) | 0);
  3570. --count;
  3571. } while (p0 !== p);
  3572. outlines.push(coords);
  3573. --i;
  3574. }
  3575. var drawOutline = function(c) {
  3576. c.save();
  3577. // the path shall be painted in [0..1]x[0..1] space
  3578. c.scale(1 / width, -1 / height);
  3579. c.translate(0, -height);
  3580. c.beginPath();
  3581. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3582. var o = outlines[i];
  3583. c.moveTo(o[0], o[1]);
  3584. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3585. c.lineTo(o[j], o[j+1]);
  3586. }
  3587. }
  3588. c.fill();
  3589. c.beginPath();
  3590. c.restore();
  3591. };
  3592. return drawOutline;
  3593. }
  3594. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3595. function CanvasExtraState(old) {
  3596. // Are soft masks and alpha values shapes or opacities?
  3597. this.alphaIsShape = false;
  3598. this.fontSize = 0;
  3599. this.fontSizeScale = 1;
  3600. this.textMatrix = IDENTITY_MATRIX;
  3601. this.textMatrixScale = 1;
  3602. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3603. this.leading = 0;
  3604. // Current point (in user coordinates)
  3605. this.x = 0;
  3606. this.y = 0;
  3607. // Start of text line (in text coordinates)
  3608. this.lineX = 0;
  3609. this.lineY = 0;
  3610. // Character and word spacing
  3611. this.charSpacing = 0;
  3612. this.wordSpacing = 0;
  3613. this.textHScale = 1;
  3614. this.textRenderingMode = TextRenderingMode.FILL;
  3615. this.textRise = 0;
  3616. // Default fore and background colors
  3617. this.fillColor = '#000000';
  3618. this.strokeColor = '#000000';
  3619. // Note: fill alpha applies to all non-stroking operations
  3620. this.fillAlpha = 1;
  3621. this.strokeAlpha = 1;
  3622. this.lineWidth = 1;
  3623. this.activeSMask = null; // nonclonable field (see the save method below)
  3624. this.old = old;
  3625. }
  3626. CanvasExtraState.prototype = {
  3627. clone: function CanvasExtraState_clone() {
  3628. return Object.create(this);
  3629. },
  3630. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3631. this.x = x;
  3632. this.y = y;
  3633. }
  3634. };
  3635. return CanvasExtraState;
  3636. })();
  3637. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3638. // Defines the time the executeOperatorList is going to be executing
  3639. // before it stops and shedules a continue of execution.
  3640. var EXECUTION_TIME = 15;
  3641. // Defines the number of steps before checking the execution time
  3642. var EXECUTION_STEPS = 10;
  3643. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3644. this.ctx = canvasCtx;
  3645. this.current = new CanvasExtraState();
  3646. this.stateStack = [];
  3647. this.pendingClip = null;
  3648. this.pendingEOFill = false;
  3649. this.res = null;
  3650. this.xobjs = null;
  3651. this.commonObjs = commonObjs;
  3652. this.objs = objs;
  3653. this.imageLayer = imageLayer;
  3654. this.groupStack = [];
  3655. this.processingType3 = null;
  3656. // Patterns are painted relative to the initial page/form transform, see pdf
  3657. // spec 8.7.2 NOTE 1.
  3658. this.baseTransform = null;
  3659. this.baseTransformStack = [];
  3660. this.groupLevel = 0;
  3661. this.smaskStack = [];
  3662. this.smaskCounter = 0;
  3663. this.tempSMask = null;
  3664. if (canvasCtx) {
  3665. addContextCurrentTransform(canvasCtx);
  3666. }
  3667. }
  3668. function putBinaryImageData(ctx, imgData) {
  3669. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3670. ctx.putImageData(imgData, 0, 0);
  3671. return;
  3672. }
  3673. // Put the image data to the canvas in chunks, rather than putting the
  3674. // whole image at once. This saves JS memory, because the ImageData object
  3675. // is smaller. It also possibly saves C++ memory within the implementation
  3676. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3677. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3678. // because too many putImageData() calls will slow things down.
  3679. //
  3680. // Note: as written, if the last chunk is partial, the putImageData() call
  3681. // will (conceptually) put pixels past the bounds of the canvas. But
  3682. // that's ok; any such pixels are ignored.
  3683. var height = imgData.height, width = imgData.width;
  3684. var fullChunkHeight = 16;
  3685. var fracChunks = height / fullChunkHeight;
  3686. var fullChunks = Math.floor(fracChunks);
  3687. var totalChunks = Math.ceil(fracChunks);
  3688. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3689. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3690. var srcPos = 0, destPos;
  3691. var src = imgData.data;
  3692. var dest = chunkImgData.data;
  3693. var i, j, thisChunkHeight, elemsInThisChunk;
  3694. // There are multiple forms in which the pixel data can be passed, and
  3695. // imgData.kind tells us which one this is.
  3696. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3697. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3698. var srcLength = src.byteLength;
  3699. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3700. new Uint32ArrayView(dest);
  3701. var dest32DataLength = dest32.length;
  3702. var fullSrcDiff = (width + 7) >> 3;
  3703. var white = 0xFFFFFFFF;
  3704. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3705. 0xFF000000 : 0x000000FF;
  3706. for (i = 0; i < totalChunks; i++) {
  3707. thisChunkHeight =
  3708. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3709. destPos = 0;
  3710. for (j = 0; j < thisChunkHeight; j++) {
  3711. var srcDiff = srcLength - srcPos;
  3712. var k = 0;
  3713. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3714. var kEndUnrolled = kEnd & ~7;
  3715. var mask = 0;
  3716. var srcByte = 0;
  3717. for (; k < kEndUnrolled; k += 8) {
  3718. srcByte = src[srcPos++];
  3719. dest32[destPos++] = (srcByte & 128) ? white : black;
  3720. dest32[destPos++] = (srcByte & 64) ? white : black;
  3721. dest32[destPos++] = (srcByte & 32) ? white : black;
  3722. dest32[destPos++] = (srcByte & 16) ? white : black;
  3723. dest32[destPos++] = (srcByte & 8) ? white : black;
  3724. dest32[destPos++] = (srcByte & 4) ? white : black;
  3725. dest32[destPos++] = (srcByte & 2) ? white : black;
  3726. dest32[destPos++] = (srcByte & 1) ? white : black;
  3727. }
  3728. for (; k < kEnd; k++) {
  3729. if (mask === 0) {
  3730. srcByte = src[srcPos++];
  3731. mask = 128;
  3732. }
  3733. dest32[destPos++] = (srcByte & mask) ? white : black;
  3734. mask >>= 1;
  3735. }
  3736. }
  3737. // We ran out of input. Make all remaining pixels transparent.
  3738. while (destPos < dest32DataLength) {
  3739. dest32[destPos++] = 0;
  3740. }
  3741. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3742. }
  3743. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3744. // RGBA, 32-bits per pixel.
  3745. j = 0;
  3746. elemsInThisChunk = width * fullChunkHeight * 4;
  3747. for (i = 0; i < fullChunks; i++) {
  3748. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3749. srcPos += elemsInThisChunk;
  3750. ctx.putImageData(chunkImgData, 0, j);
  3751. j += fullChunkHeight;
  3752. }
  3753. if (i < totalChunks) {
  3754. elemsInThisChunk = width * partialChunkHeight * 4;
  3755. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3756. ctx.putImageData(chunkImgData, 0, j);
  3757. }
  3758. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3759. // RGB, 24-bits per pixel.
  3760. thisChunkHeight = fullChunkHeight;
  3761. elemsInThisChunk = width * thisChunkHeight;
  3762. for (i = 0; i < totalChunks; i++) {
  3763. if (i >= fullChunks) {
  3764. thisChunkHeight =partialChunkHeight;
  3765. elemsInThisChunk = width * thisChunkHeight;
  3766. }
  3767. destPos = 0;
  3768. for (j = elemsInThisChunk; j--;) {
  3769. dest[destPos++] = src[srcPos++];
  3770. dest[destPos++] = src[srcPos++];
  3771. dest[destPos++] = src[srcPos++];
  3772. dest[destPos++] = 255;
  3773. }
  3774. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3775. }
  3776. } else {
  3777. error('bad image kind: ' + imgData.kind);
  3778. }
  3779. }
  3780. function putBinaryImageMask(ctx, imgData) {
  3781. var height = imgData.height, width = imgData.width;
  3782. var fullChunkHeight = 16;
  3783. var fracChunks = height / fullChunkHeight;
  3784. var fullChunks = Math.floor(fracChunks);
  3785. var totalChunks = Math.ceil(fracChunks);
  3786. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  3787. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  3788. var srcPos = 0;
  3789. var src = imgData.data;
  3790. var dest = chunkImgData.data;
  3791. for (var i = 0; i < totalChunks; i++) {
  3792. var thisChunkHeight =
  3793. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  3794. // Expand the mask so it can be used by the canvas. Any required
  3795. // inversion has already been handled.
  3796. var destPos = 3; // alpha component offset
  3797. for (var j = 0; j < thisChunkHeight; j++) {
  3798. var mask = 0;
  3799. for (var k = 0; k < width; k++) {
  3800. if (!mask) {
  3801. var elem = src[srcPos++];
  3802. mask = 128;
  3803. }
  3804. dest[destPos] = (elem & mask) ? 0 : 255;
  3805. destPos += 4;
  3806. mask >>= 1;
  3807. }
  3808. }
  3809. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  3810. }
  3811. }
  3812. function copyCtxState(sourceCtx, destCtx) {
  3813. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3814. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3815. 'globalCompositeOperation', 'font'];
  3816. for (var i = 0, ii = properties.length; i < ii; i++) {
  3817. var property = properties[i];
  3818. if (property in sourceCtx) {
  3819. destCtx[property] = sourceCtx[property];
  3820. }
  3821. }
  3822. if ('setLineDash' in sourceCtx) {
  3823. destCtx.setLineDash(sourceCtx.getLineDash());
  3824. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3825. } else if ('mozDash' in sourceCtx) {
  3826. destCtx.mozDash = sourceCtx.mozDash;
  3827. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3828. }
  3829. }
  3830. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3831. var length = bytes.length;
  3832. for (var i = 3; i < length; i += 4) {
  3833. var alpha = bytes[i];
  3834. if (alpha === 0) {
  3835. bytes[i - 3] = r0;
  3836. bytes[i - 2] = g0;
  3837. bytes[i - 1] = b0;
  3838. } else if (alpha < 255) {
  3839. var alpha_ = 255 - alpha;
  3840. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3841. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3842. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3843. }
  3844. }
  3845. }
  3846. function composeSMaskAlpha(maskData, layerData) {
  3847. var length = maskData.length;
  3848. var scale = 1 / 255;
  3849. for (var i = 3; i < length; i += 4) {
  3850. var alpha = maskData[i];
  3851. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3852. }
  3853. }
  3854. function composeSMaskLuminosity(maskData, layerData) {
  3855. var length = maskData.length;
  3856. for (var i = 3; i < length; i += 4) {
  3857. var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3858. (maskData[i - 2] * 152) + // * 0.59 ....
  3859. (maskData[i - 1] * 28)) | 0; // * 0.11 ....
  3860. layerData[i] = (layerData[i] * y) >> 16;
  3861. }
  3862. }
  3863. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3864. subtype, backdrop) {
  3865. var hasBackdrop = !!backdrop;
  3866. var r0 = hasBackdrop ? backdrop[0] : 0;
  3867. var g0 = hasBackdrop ? backdrop[1] : 0;
  3868. var b0 = hasBackdrop ? backdrop[2] : 0;
  3869. var composeFn;
  3870. if (subtype === 'Luminosity') {
  3871. composeFn = composeSMaskLuminosity;
  3872. } else {
  3873. composeFn = composeSMaskAlpha;
  3874. }
  3875. // processing image in chunks to save memory
  3876. var PIXELS_TO_PROCESS = 65536;
  3877. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3878. for (var row = 0; row < height; row += chunkSize) {
  3879. var chunkHeight = Math.min(chunkSize, height - row);
  3880. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3881. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3882. if (hasBackdrop) {
  3883. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3884. }
  3885. composeFn(maskData.data, layerData.data);
  3886. maskCtx.putImageData(layerData, 0, row);
  3887. }
  3888. }
  3889. function composeSMask(ctx, smask, layerCtx) {
  3890. var mask = smask.canvas;
  3891. var maskCtx = smask.context;
  3892. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3893. smask.offsetX, smask.offsetY);
  3894. var backdrop = smask.backdrop || null;
  3895. if (WebGLUtils.isEnabled) {
  3896. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3897. {subtype: smask.subtype, backdrop: backdrop});
  3898. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3899. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3900. return;
  3901. }
  3902. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3903. smask.subtype, backdrop);
  3904. ctx.drawImage(mask, 0, 0);
  3905. }
  3906. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3907. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3908. var NORMAL_CLIP = {};
  3909. var EO_CLIP = {};
  3910. CanvasGraphics.prototype = {
  3911. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3912. // For pdfs that use blend modes we have to clear the canvas else certain
  3913. // blend modes can look wrong since we'd be blending with a white
  3914. // backdrop. The problem with a transparent backdrop though is we then
  3915. // don't get sub pixel anti aliasing on text, so we fill with white if
  3916. // we can.
  3917. var width = this.ctx.canvas.width;
  3918. var height = this.ctx.canvas.height;
  3919. if (transparency) {
  3920. this.ctx.clearRect(0, 0, width, height);
  3921. } else {
  3922. this.ctx.mozOpaque = true;
  3923. this.ctx.save();
  3924. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3925. this.ctx.fillRect(0, 0, width, height);
  3926. this.ctx.restore();
  3927. }
  3928. var transform = viewport.transform;
  3929. this.ctx.save();
  3930. this.ctx.transform.apply(this.ctx, transform);
  3931. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3932. if (this.imageLayer) {
  3933. this.imageLayer.beginLayout();
  3934. }
  3935. },
  3936. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3937. operatorList,
  3938. executionStartIdx, continueCallback,
  3939. stepper) {
  3940. var argsArray = operatorList.argsArray;
  3941. var fnArray = operatorList.fnArray;
  3942. var i = executionStartIdx || 0;
  3943. var argsArrayLen = argsArray.length;
  3944. // Sometimes the OperatorList to execute is empty.
  3945. if (argsArrayLen === i) {
  3946. return i;
  3947. }
  3948. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3949. typeof continueCallback === 'function');
  3950. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3951. var steps = 0;
  3952. var commonObjs = this.commonObjs;
  3953. var objs = this.objs;
  3954. var fnId;
  3955. while (true) {
  3956. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3957. stepper.breakIt(i, continueCallback);
  3958. return i;
  3959. }
  3960. fnId = fnArray[i];
  3961. if (fnId !== OPS.dependency) {
  3962. this[fnId].apply(this, argsArray[i]);
  3963. } else {
  3964. var deps = argsArray[i];
  3965. for (var n = 0, nn = deps.length; n < nn; n++) {
  3966. var depObjId = deps[n];
  3967. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3968. var objsPool = common ? commonObjs : objs;
  3969. // If the promise isn't resolved yet, add the continueCallback
  3970. // to the promise and bail out.
  3971. if (!objsPool.isResolved(depObjId)) {
  3972. objsPool.get(depObjId, continueCallback);
  3973. return i;
  3974. }
  3975. }
  3976. }
  3977. i++;
  3978. // If the entire operatorList was executed, stop as were done.
  3979. if (i === argsArrayLen) {
  3980. return i;
  3981. }
  3982. // If the execution took longer then a certain amount of time and
  3983. // `continueCallback` is specified, interrupt the execution.
  3984. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3985. if (Date.now() > endTime) {
  3986. continueCallback();
  3987. return i;
  3988. }
  3989. steps = 0;
  3990. }
  3991. // If the operatorList isn't executed completely yet OR the execution
  3992. // time was short enough, do another execution round.
  3993. }
  3994. },
  3995. endDrawing: function CanvasGraphics_endDrawing() {
  3996. this.ctx.restore();
  3997. CachedCanvases.clear();
  3998. WebGLUtils.clear();
  3999. if (this.imageLayer) {
  4000. this.imageLayer.endLayout();
  4001. }
  4002. },
  4003. // Graphics state
  4004. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  4005. this.current.lineWidth = width;
  4006. this.ctx.lineWidth = width;
  4007. },
  4008. setLineCap: function CanvasGraphics_setLineCap(style) {
  4009. this.ctx.lineCap = LINE_CAP_STYLES[style];
  4010. },
  4011. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  4012. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  4013. },
  4014. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  4015. this.ctx.miterLimit = limit;
  4016. },
  4017. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  4018. var ctx = this.ctx;
  4019. if ('setLineDash' in ctx) {
  4020. ctx.setLineDash(dashArray);
  4021. ctx.lineDashOffset = dashPhase;
  4022. } else {
  4023. ctx.mozDash = dashArray;
  4024. ctx.mozDashOffset = dashPhase;
  4025. }
  4026. },
  4027. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  4028. // Maybe if we one day fully support color spaces this will be important
  4029. // for now we can ignore.
  4030. // TODO set rendering intent?
  4031. },
  4032. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  4033. // There's no way to control this with canvas, but we can safely ignore.
  4034. // TODO set flatness?
  4035. },
  4036. setGState: function CanvasGraphics_setGState(states) {
  4037. for (var i = 0, ii = states.length; i < ii; i++) {
  4038. var state = states[i];
  4039. var key = state[0];
  4040. var value = state[1];
  4041. switch (key) {
  4042. case 'LW':
  4043. this.setLineWidth(value);
  4044. break;
  4045. case 'LC':
  4046. this.setLineCap(value);
  4047. break;
  4048. case 'LJ':
  4049. this.setLineJoin(value);
  4050. break;
  4051. case 'ML':
  4052. this.setMiterLimit(value);
  4053. break;
  4054. case 'D':
  4055. this.setDash(value[0], value[1]);
  4056. break;
  4057. case 'RI':
  4058. this.setRenderingIntent(value);
  4059. break;
  4060. case 'FL':
  4061. this.setFlatness(value);
  4062. break;
  4063. case 'Font':
  4064. this.setFont(value[0], value[1]);
  4065. break;
  4066. case 'CA':
  4067. this.current.strokeAlpha = state[1];
  4068. break;
  4069. case 'ca':
  4070. this.current.fillAlpha = state[1];
  4071. this.ctx.globalAlpha = state[1];
  4072. break;
  4073. case 'BM':
  4074. if (value && value.name && (value.name !== 'Normal')) {
  4075. var mode = value.name.replace(/([A-Z])/g,
  4076. function(c) {
  4077. return '-' + c.toLowerCase();
  4078. }
  4079. ).substring(1);
  4080. this.ctx.globalCompositeOperation = mode;
  4081. if (this.ctx.globalCompositeOperation !== mode) {
  4082. warn('globalCompositeOperation "' + mode +
  4083. '" is not supported');
  4084. }
  4085. } else {
  4086. this.ctx.globalCompositeOperation = 'source-over';
  4087. }
  4088. break;
  4089. case 'SMask':
  4090. if (this.current.activeSMask) {
  4091. this.endSMaskGroup();
  4092. }
  4093. this.current.activeSMask = value ? this.tempSMask : null;
  4094. if (this.current.activeSMask) {
  4095. this.beginSMaskGroup();
  4096. }
  4097. this.tempSMask = null;
  4098. break;
  4099. }
  4100. }
  4101. },
  4102. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  4103. var activeSMask = this.current.activeSMask;
  4104. var drawnWidth = activeSMask.canvas.width;
  4105. var drawnHeight = activeSMask.canvas.height;
  4106. var cacheId = 'smaskGroupAt' + this.groupLevel;
  4107. var scratchCanvas = CachedCanvases.getCanvas(
  4108. cacheId, drawnWidth, drawnHeight, true);
  4109. var currentCtx = this.ctx;
  4110. var currentTransform = currentCtx.mozCurrentTransform;
  4111. this.ctx.save();
  4112. var groupCtx = scratchCanvas.context;
  4113. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  4114. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  4115. groupCtx.transform.apply(groupCtx, currentTransform);
  4116. copyCtxState(currentCtx, groupCtx);
  4117. this.ctx = groupCtx;
  4118. this.setGState([
  4119. ['BM', 'Normal'],
  4120. ['ca', 1],
  4121. ['CA', 1]
  4122. ]);
  4123. this.groupStack.push(currentCtx);
  4124. this.groupLevel++;
  4125. },
  4126. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  4127. var groupCtx = this.ctx;
  4128. this.groupLevel--;
  4129. this.ctx = this.groupStack.pop();
  4130. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  4131. this.ctx.restore();
  4132. },
  4133. save: function CanvasGraphics_save() {
  4134. this.ctx.save();
  4135. var old = this.current;
  4136. this.stateStack.push(old);
  4137. this.current = old.clone();
  4138. this.current.activeSMask = null;
  4139. },
  4140. restore: function CanvasGraphics_restore() {
  4141. if (this.stateStack.length !== 0) {
  4142. if (this.current.activeSMask !== null) {
  4143. this.endSMaskGroup();
  4144. }
  4145. this.current = this.stateStack.pop();
  4146. this.ctx.restore();
  4147. }
  4148. },
  4149. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  4150. this.ctx.transform(a, b, c, d, e, f);
  4151. },
  4152. // Path
  4153. constructPath: function CanvasGraphics_constructPath(ops, args) {
  4154. var ctx = this.ctx;
  4155. var current = this.current;
  4156. var x = current.x, y = current.y;
  4157. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  4158. switch (ops[i] | 0) {
  4159. case OPS.moveTo:
  4160. x = args[j++];
  4161. y = args[j++];
  4162. ctx.moveTo(x, y);
  4163. break;
  4164. case OPS.lineTo:
  4165. x = args[j++];
  4166. y = args[j++];
  4167. ctx.lineTo(x, y);
  4168. break;
  4169. case OPS.curveTo:
  4170. x = args[j + 4];
  4171. y = args[j + 5];
  4172. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  4173. x, y);
  4174. j += 6;
  4175. break;
  4176. case OPS.curveTo2:
  4177. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  4178. args[j + 2], args[j + 3]);
  4179. x = args[j + 2];
  4180. y = args[j + 3];
  4181. j += 4;
  4182. break;
  4183. case OPS.curveTo3:
  4184. x = args[j + 2];
  4185. y = args[j + 3];
  4186. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  4187. j += 4;
  4188. break;
  4189. case OPS.closePath:
  4190. ctx.closePath();
  4191. break;
  4192. }
  4193. }
  4194. current.setCurrentPoint(x, y);
  4195. },
  4196. closePath: function CanvasGraphics_closePath() {
  4197. this.ctx.closePath();
  4198. },
  4199. rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
  4200. if (width === 0) {
  4201. width = this.getSinglePixelWidth();
  4202. }
  4203. if (height === 0) {
  4204. height = this.getSinglePixelWidth();
  4205. }
  4206. this.ctx.rect(x, y, width, height);
  4207. },
  4208. stroke: function CanvasGraphics_stroke(consumePath) {
  4209. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4210. var ctx = this.ctx;
  4211. var strokeColor = this.current.strokeColor;
  4212. if (this.current.lineWidth === 0) {
  4213. ctx.lineWidth = this.getSinglePixelWidth();
  4214. }
  4215. // For stroke we want to temporarily change the global alpha to the
  4216. // stroking alpha.
  4217. ctx.globalAlpha = this.current.strokeAlpha;
  4218. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  4219. strokeColor.type === 'Pattern') {
  4220. // for patterns, we transform to pattern space, calculate
  4221. // the pattern, call stroke, and restore to user space
  4222. ctx.save();
  4223. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  4224. ctx.stroke();
  4225. ctx.restore();
  4226. } else {
  4227. ctx.stroke();
  4228. }
  4229. if (consumePath) {
  4230. this.consumePath();
  4231. }
  4232. // Restore the global alpha to the fill alpha
  4233. ctx.globalAlpha = this.current.fillAlpha;
  4234. },
  4235. closeStroke: function CanvasGraphics_closeStroke() {
  4236. this.closePath();
  4237. this.stroke();
  4238. },
  4239. fill: function CanvasGraphics_fill(consumePath) {
  4240. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  4241. var ctx = this.ctx;
  4242. var fillColor = this.current.fillColor;
  4243. var needRestore = false;
  4244. if (fillColor && fillColor.hasOwnProperty('type') &&
  4245. fillColor.type === 'Pattern') {
  4246. ctx.save();
  4247. ctx.fillStyle = fillColor.getPattern(ctx, this);
  4248. needRestore = true;
  4249. }
  4250. if (this.pendingEOFill) {
  4251. if (ctx.mozFillRule !== undefined) {
  4252. ctx.mozFillRule = 'evenodd';
  4253. ctx.fill();
  4254. ctx.mozFillRule = 'nonzero';
  4255. } else {
  4256. try {
  4257. ctx.fill('evenodd');
  4258. } catch (ex) {
  4259. // shouldn't really happen, but browsers might think differently
  4260. ctx.fill();
  4261. }
  4262. }
  4263. this.pendingEOFill = false;
  4264. } else {
  4265. ctx.fill();
  4266. }
  4267. if (needRestore) {
  4268. ctx.restore();
  4269. }
  4270. if (consumePath) {
  4271. this.consumePath();
  4272. }
  4273. },
  4274. eoFill: function CanvasGraphics_eoFill() {
  4275. this.pendingEOFill = true;
  4276. this.fill();
  4277. },
  4278. fillStroke: function CanvasGraphics_fillStroke() {
  4279. this.fill(false);
  4280. this.stroke(false);
  4281. this.consumePath();
  4282. },
  4283. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  4284. this.pendingEOFill = true;
  4285. this.fillStroke();
  4286. },
  4287. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  4288. this.closePath();
  4289. this.fillStroke();
  4290. },
  4291. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  4292. this.pendingEOFill = true;
  4293. this.closePath();
  4294. this.fillStroke();
  4295. },
  4296. endPath: function CanvasGraphics_endPath() {
  4297. this.consumePath();
  4298. },
  4299. // Clipping
  4300. clip: function CanvasGraphics_clip() {
  4301. this.pendingClip = NORMAL_CLIP;
  4302. },
  4303. eoClip: function CanvasGraphics_eoClip() {
  4304. this.pendingClip = EO_CLIP;
  4305. },
  4306. // Text
  4307. beginText: function CanvasGraphics_beginText() {
  4308. this.current.textMatrix = IDENTITY_MATRIX;
  4309. this.current.textMatrixScale = 1;
  4310. this.current.x = this.current.lineX = 0;
  4311. this.current.y = this.current.lineY = 0;
  4312. },
  4313. endText: function CanvasGraphics_endText() {
  4314. var paths = this.pendingTextPaths;
  4315. var ctx = this.ctx;
  4316. if (paths === undefined) {
  4317. ctx.beginPath();
  4318. return;
  4319. }
  4320. ctx.save();
  4321. ctx.beginPath();
  4322. for (var i = 0; i < paths.length; i++) {
  4323. var path = paths[i];
  4324. ctx.setTransform.apply(ctx, path.transform);
  4325. ctx.translate(path.x, path.y);
  4326. path.addToPath(ctx, path.fontSize);
  4327. }
  4328. ctx.restore();
  4329. ctx.clip();
  4330. ctx.beginPath();
  4331. delete this.pendingTextPaths;
  4332. },
  4333. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  4334. this.current.charSpacing = spacing;
  4335. },
  4336. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  4337. this.current.wordSpacing = spacing;
  4338. },
  4339. setHScale: function CanvasGraphics_setHScale(scale) {
  4340. this.current.textHScale = scale / 100;
  4341. },
  4342. setLeading: function CanvasGraphics_setLeading(leading) {
  4343. this.current.leading = -leading;
  4344. },
  4345. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  4346. var fontObj = this.commonObjs.get(fontRefName);
  4347. var current = this.current;
  4348. if (!fontObj) {
  4349. error('Can\'t find font for ' + fontRefName);
  4350. }
  4351. current.fontMatrix = (fontObj.fontMatrix ?
  4352. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4353. // A valid matrix needs all main diagonal elements to be non-zero
  4354. // This also ensures we bypass FF bugzilla bug #719844.
  4355. if (current.fontMatrix[0] === 0 ||
  4356. current.fontMatrix[3] === 0) {
  4357. warn('Invalid font matrix for font ' + fontRefName);
  4358. }
  4359. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4360. // and in some docs this can be negative (inverted x-y axes).
  4361. if (size < 0) {
  4362. size = -size;
  4363. current.fontDirection = -1;
  4364. } else {
  4365. current.fontDirection = 1;
  4366. }
  4367. this.current.font = fontObj;
  4368. this.current.fontSize = size;
  4369. if (fontObj.isType3Font) {
  4370. return; // we don't need ctx.font for Type3 fonts
  4371. }
  4372. var name = fontObj.loadedName || 'sans-serif';
  4373. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  4374. (fontObj.bold ? 'bold' : 'normal');
  4375. var italic = fontObj.italic ? 'italic' : 'normal';
  4376. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4377. // Some font backends cannot handle fonts below certain size.
  4378. // Keeping the font at minimal size and using the fontSizeScale to change
  4379. // the current transformation matrix before the fillText/strokeText.
  4380. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4381. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  4382. this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
  4383. size / MIN_FONT_SIZE;
  4384. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4385. this.ctx.font = rule;
  4386. },
  4387. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4388. this.current.textRenderingMode = mode;
  4389. },
  4390. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4391. this.current.textRise = rise;
  4392. },
  4393. moveText: function CanvasGraphics_moveText(x, y) {
  4394. this.current.x = this.current.lineX += x;
  4395. this.current.y = this.current.lineY += y;
  4396. },
  4397. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4398. this.setLeading(-y);
  4399. this.moveText(x, y);
  4400. },
  4401. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4402. this.current.textMatrix = [a, b, c, d, e, f];
  4403. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4404. this.current.x = this.current.lineX = 0;
  4405. this.current.y = this.current.lineY = 0;
  4406. },
  4407. nextLine: function CanvasGraphics_nextLine() {
  4408. this.moveText(0, this.current.leading);
  4409. },
  4410. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4411. var ctx = this.ctx;
  4412. var current = this.current;
  4413. var font = current.font;
  4414. var textRenderingMode = current.textRenderingMode;
  4415. var fontSize = current.fontSize / current.fontSizeScale;
  4416. var fillStrokeMode = textRenderingMode &
  4417. TextRenderingMode.FILL_STROKE_MASK;
  4418. var isAddToPathSet = !!(textRenderingMode &
  4419. TextRenderingMode.ADD_TO_PATH_FLAG);
  4420. var addToPath;
  4421. if (font.disableFontFace || isAddToPathSet) {
  4422. addToPath = font.getPathGenerator(this.commonObjs, character);
  4423. }
  4424. if (font.disableFontFace) {
  4425. ctx.save();
  4426. ctx.translate(x, y);
  4427. ctx.beginPath();
  4428. addToPath(ctx, fontSize);
  4429. if (fillStrokeMode === TextRenderingMode.FILL ||
  4430. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4431. ctx.fill();
  4432. }
  4433. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4434. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4435. ctx.stroke();
  4436. }
  4437. ctx.restore();
  4438. } else {
  4439. if (fillStrokeMode === TextRenderingMode.FILL ||
  4440. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4441. ctx.fillText(character, x, y);
  4442. }
  4443. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4444. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4445. ctx.strokeText(character, x, y);
  4446. }
  4447. }
  4448. if (isAddToPathSet) {
  4449. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4450. paths.push({
  4451. transform: ctx.mozCurrentTransform,
  4452. x: x,
  4453. y: y,
  4454. fontSize: fontSize,
  4455. addToPath: addToPath
  4456. });
  4457. }
  4458. },
  4459. get isFontSubpixelAAEnabled() {
  4460. // Checks if anti-aliasing is enabled when scaled text is painted.
  4461. // On Windows GDI scaled fonts looks bad.
  4462. var ctx = document.createElement('canvas').getContext('2d');
  4463. ctx.scale(1.5, 1);
  4464. ctx.fillText('I', 0, 10);
  4465. var data = ctx.getImageData(0, 0, 10, 10).data;
  4466. var enabled = false;
  4467. for (var i = 3; i < data.length; i += 4) {
  4468. if (data[i] > 0 && data[i] < 255) {
  4469. enabled = true;
  4470. break;
  4471. }
  4472. }
  4473. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4474. },
  4475. showText: function CanvasGraphics_showText(glyphs) {
  4476. var current = this.current;
  4477. var font = current.font;
  4478. if (font.isType3Font) {
  4479. return this.showType3Text(glyphs);
  4480. }
  4481. var fontSize = current.fontSize;
  4482. if (fontSize === 0) {
  4483. return;
  4484. }
  4485. var ctx = this.ctx;
  4486. var fontSizeScale = current.fontSizeScale;
  4487. var charSpacing = current.charSpacing;
  4488. var wordSpacing = current.wordSpacing;
  4489. var fontDirection = current.fontDirection;
  4490. var textHScale = current.textHScale * fontDirection;
  4491. var glyphsLength = glyphs.length;
  4492. var vertical = font.vertical;
  4493. var defaultVMetrics = font.defaultVMetrics;
  4494. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4495. var simpleFillText =
  4496. current.textRenderingMode === TextRenderingMode.FILL &&
  4497. !font.disableFontFace;
  4498. ctx.save();
  4499. ctx.transform.apply(ctx, current.textMatrix);
  4500. ctx.translate(current.x, current.y + current.textRise);
  4501. if (fontDirection > 0) {
  4502. ctx.scale(textHScale, -1);
  4503. } else {
  4504. ctx.scale(textHScale, 1);
  4505. }
  4506. var lineWidth = current.lineWidth;
  4507. var scale = current.textMatrixScale;
  4508. if (scale === 0 || lineWidth === 0) {
  4509. lineWidth = this.getSinglePixelWidth();
  4510. } else {
  4511. lineWidth /= scale;
  4512. }
  4513. if (fontSizeScale != 1.0) {
  4514. ctx.scale(fontSizeScale, fontSizeScale);
  4515. lineWidth /= fontSizeScale;
  4516. }
  4517. ctx.lineWidth = lineWidth;
  4518. var x = 0, i;
  4519. for (i = 0; i < glyphsLength; ++i) {
  4520. var glyph = glyphs[i];
  4521. if (glyph === null) {
  4522. // word break
  4523. x += fontDirection * wordSpacing;
  4524. continue;
  4525. } else if (isNum(glyph)) {
  4526. x += -glyph * fontSize * 0.001;
  4527. continue;
  4528. }
  4529. var restoreNeeded = false;
  4530. var character = glyph.fontChar;
  4531. var accent = glyph.accent;
  4532. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4533. var width = glyph.width;
  4534. if (vertical) {
  4535. var vmetric, vx, vy;
  4536. vmetric = glyph.vmetric || defaultVMetrics;
  4537. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4538. vx = -vx * widthAdvanceScale;
  4539. vy = vmetric[2] * widthAdvanceScale;
  4540. width = vmetric ? -vmetric[0] : width;
  4541. scaledX = vx / fontSizeScale;
  4542. scaledY = (x + vy) / fontSizeScale;
  4543. } else {
  4544. scaledX = x / fontSizeScale;
  4545. scaledY = 0;
  4546. }
  4547. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4548. // some standard fonts may not have the exact width, trying to
  4549. // rescale per character
  4550. var measuredWidth = ctx.measureText(character).width * 1000 /
  4551. fontSize * fontSizeScale;
  4552. var characterScaleX = width / measuredWidth;
  4553. restoreNeeded = true;
  4554. ctx.save();
  4555. ctx.scale(characterScaleX, 1);
  4556. scaledX /= characterScaleX;
  4557. }
  4558. if (simpleFillText && !accent) {
  4559. // common case
  4560. ctx.fillText(character, scaledX, scaledY);
  4561. } else {
  4562. this.paintChar(character, scaledX, scaledY);
  4563. if (accent) {
  4564. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4565. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4566. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4567. }
  4568. }
  4569. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4570. x += charWidth;
  4571. if (restoreNeeded) {
  4572. ctx.restore();
  4573. }
  4574. }
  4575. if (vertical) {
  4576. current.y -= x * textHScale;
  4577. } else {
  4578. current.x += x * textHScale;
  4579. }
  4580. ctx.restore();
  4581. },
  4582. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4583. // Type3 fonts - each glyph is a "mini-PDF"
  4584. var ctx = this.ctx;
  4585. var current = this.current;
  4586. var font = current.font;
  4587. var fontSize = current.fontSize;
  4588. var fontDirection = current.fontDirection;
  4589. var charSpacing = current.charSpacing;
  4590. var wordSpacing = current.wordSpacing;
  4591. var textHScale = current.textHScale * fontDirection;
  4592. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4593. var glyphsLength = glyphs.length;
  4594. var i, glyph, width;
  4595. if (fontSize === 0) {
  4596. return;
  4597. }
  4598. ctx.save();
  4599. ctx.transform.apply(ctx, current.textMatrix);
  4600. ctx.translate(current.x, current.y);
  4601. ctx.scale(textHScale, 1);
  4602. for (i = 0; i < glyphsLength; ++i) {
  4603. glyph = glyphs[i];
  4604. if (glyph === null) {
  4605. // word break
  4606. this.ctx.translate(wordSpacing, 0);
  4607. current.x += wordSpacing * textHScale;
  4608. continue;
  4609. } else if (isNum(glyph)) {
  4610. var spacingLength = -glyph * 0.001 * fontSize;
  4611. this.ctx.translate(spacingLength, 0);
  4612. current.x += spacingLength * textHScale;
  4613. continue;
  4614. }
  4615. this.processingType3 = glyph;
  4616. this.save();
  4617. ctx.scale(fontSize, fontSize);
  4618. ctx.transform.apply(ctx, fontMatrix);
  4619. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4620. this.executeOperatorList(operatorList);
  4621. this.restore();
  4622. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4623. width = ((transformed[0] * fontSize + charSpacing) * fontDirection);
  4624. ctx.translate(width, 0);
  4625. current.x += width * textHScale;
  4626. }
  4627. ctx.restore();
  4628. this.processingType3 = null;
  4629. },
  4630. // Type3 fonts
  4631. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4632. // We can safely ignore this since the width should be the same
  4633. // as the width in the Widths array.
  4634. },
  4635. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4636. yWidth,
  4637. llx,
  4638. lly,
  4639. urx,
  4640. ury) {
  4641. // TODO According to the spec we're also suppose to ignore any operators
  4642. // that set color or include images while processing this type3 font.
  4643. this.rectangle(llx, lly, urx - llx, ury - lly);
  4644. this.clip();
  4645. this.endPath();
  4646. },
  4647. // Color
  4648. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4649. var pattern;
  4650. if (IR[0] === 'TilingPattern') {
  4651. var color = IR[1];
  4652. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4653. this.commonObjs, this.baseTransform);
  4654. } else {
  4655. pattern = getShadingPatternFromIR(IR);
  4656. }
  4657. return pattern;
  4658. },
  4659. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4660. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4661. },
  4662. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4663. this.current.fillColor = this.getColorN_Pattern(arguments);
  4664. },
  4665. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4666. var color = Util.makeCssRgb(arguments);
  4667. this.ctx.strokeStyle = color;
  4668. this.current.strokeColor = color;
  4669. },
  4670. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4671. var color = Util.makeCssRgb(arguments);
  4672. this.ctx.fillStyle = color;
  4673. this.current.fillColor = color;
  4674. },
  4675. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4676. var ctx = this.ctx;
  4677. this.save();
  4678. var pattern = getShadingPatternFromIR(patternIR);
  4679. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4680. var inv = ctx.mozCurrentTransformInverse;
  4681. if (inv) {
  4682. var canvas = ctx.canvas;
  4683. var width = canvas.width;
  4684. var height = canvas.height;
  4685. var bl = Util.applyTransform([0, 0], inv);
  4686. var br = Util.applyTransform([0, height], inv);
  4687. var ul = Util.applyTransform([width, 0], inv);
  4688. var ur = Util.applyTransform([width, height], inv);
  4689. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4690. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4691. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4692. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4693. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4694. } else {
  4695. // HACK to draw the gradient onto an infinite rectangle.
  4696. // PDF gradients are drawn across the entire image while
  4697. // Canvas only allows gradients to be drawn in a rectangle
  4698. // The following bug should allow us to remove this.
  4699. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4700. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4701. }
  4702. this.restore();
  4703. },
  4704. // Images
  4705. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4706. error('Should not call beginInlineImage');
  4707. },
  4708. beginImageData: function CanvasGraphics_beginImageData() {
  4709. error('Should not call beginImageData');
  4710. },
  4711. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4712. bbox) {
  4713. this.save();
  4714. this.baseTransformStack.push(this.baseTransform);
  4715. if (isArray(matrix) && 6 === matrix.length) {
  4716. this.transform.apply(this, matrix);
  4717. }
  4718. this.baseTransform = this.ctx.mozCurrentTransform;
  4719. if (isArray(bbox) && 4 === bbox.length) {
  4720. var width = bbox[2] - bbox[0];
  4721. var height = bbox[3] - bbox[1];
  4722. this.rectangle(bbox[0], bbox[1], width, height);
  4723. this.clip();
  4724. this.endPath();
  4725. }
  4726. },
  4727. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4728. this.restore();
  4729. this.baseTransform = this.baseTransformStack.pop();
  4730. },
  4731. beginGroup: function CanvasGraphics_beginGroup(group) {
  4732. this.save();
  4733. var currentCtx = this.ctx;
  4734. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4735. // group results aren't usually that different and they even have tools
  4736. // that ignore this setting. Notes from Rik on implmenting:
  4737. // - When you encounter an transparency group, create a new canvas with
  4738. // the dimensions of the bbox
  4739. // - copy the content from the previous canvas to the new canvas
  4740. // - draw as usual
  4741. // - remove the backdrop alpha:
  4742. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4743. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4744. // backdrop
  4745. // - remove background color:
  4746. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4747. if (!group.isolated) {
  4748. info('TODO: Support non-isolated groups.');
  4749. }
  4750. // TODO knockout - supposedly possible with the clever use of compositing
  4751. // modes.
  4752. if (group.knockout) {
  4753. warn('Knockout groups not supported.');
  4754. }
  4755. var currentTransform = currentCtx.mozCurrentTransform;
  4756. if (group.matrix) {
  4757. currentCtx.transform.apply(currentCtx, group.matrix);
  4758. }
  4759. assert(group.bbox, 'Bounding box is required.');
  4760. // Based on the current transform figure out how big the bounding box
  4761. // will actually be.
  4762. var bounds = Util.getAxialAlignedBoundingBox(
  4763. group.bbox,
  4764. currentCtx.mozCurrentTransform);
  4765. // Clip the bounding box to the current canvas.
  4766. var canvasBounds = [0,
  4767. 0,
  4768. currentCtx.canvas.width,
  4769. currentCtx.canvas.height];
  4770. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4771. // Use ceil in case we're between sizes so we don't create canvas that is
  4772. // too small and make the canvas at least 1x1 pixels.
  4773. var offsetX = Math.floor(bounds[0]);
  4774. var offsetY = Math.floor(bounds[1]);
  4775. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4776. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4777. var scaleX = 1, scaleY = 1;
  4778. if (drawnWidth > MAX_GROUP_SIZE) {
  4779. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4780. drawnWidth = MAX_GROUP_SIZE;
  4781. }
  4782. if (drawnHeight > MAX_GROUP_SIZE) {
  4783. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4784. drawnHeight = MAX_GROUP_SIZE;
  4785. }
  4786. var cacheId = 'groupAt' + this.groupLevel;
  4787. if (group.smask) {
  4788. // Using two cache entries is case if masks are used one after another.
  4789. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4790. }
  4791. var scratchCanvas = CachedCanvases.getCanvas(
  4792. cacheId, drawnWidth, drawnHeight, true);
  4793. var groupCtx = scratchCanvas.context;
  4794. // Since we created a new canvas that is just the size of the bounding box
  4795. // we have to translate the group ctx.
  4796. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4797. groupCtx.translate(-offsetX, -offsetY);
  4798. groupCtx.transform.apply(groupCtx, currentTransform);
  4799. if (group.smask) {
  4800. // Saving state and cached mask to be used in setGState.
  4801. this.smaskStack.push({
  4802. canvas: scratchCanvas.canvas,
  4803. context: groupCtx,
  4804. offsetX: offsetX,
  4805. offsetY: offsetY,
  4806. scaleX: scaleX,
  4807. scaleY: scaleY,
  4808. subtype: group.smask.subtype,
  4809. backdrop: group.smask.backdrop
  4810. });
  4811. } else {
  4812. // Setup the current ctx so when the group is popped we draw it at the
  4813. // right location.
  4814. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4815. currentCtx.translate(offsetX, offsetY);
  4816. currentCtx.scale(scaleX, scaleY);
  4817. }
  4818. // The transparency group inherits all off the current graphics state
  4819. // except the blend mode, soft mask, and alpha constants.
  4820. copyCtxState(currentCtx, groupCtx);
  4821. this.ctx = groupCtx;
  4822. this.setGState([
  4823. ['BM', 'Normal'],
  4824. ['ca', 1],
  4825. ['CA', 1]
  4826. ]);
  4827. this.groupStack.push(currentCtx);
  4828. this.groupLevel++;
  4829. },
  4830. endGroup: function CanvasGraphics_endGroup(group) {
  4831. this.groupLevel--;
  4832. var groupCtx = this.ctx;
  4833. this.ctx = this.groupStack.pop();
  4834. // Turn off image smoothing to avoid sub pixel interpolation which can
  4835. // look kind of blurry for some pdfs.
  4836. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4837. this.ctx.imageSmoothingEnabled = false;
  4838. } else {
  4839. this.ctx.mozImageSmoothingEnabled = false;
  4840. }
  4841. if (group.smask) {
  4842. this.tempSMask = this.smaskStack.pop();
  4843. } else {
  4844. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4845. }
  4846. this.restore();
  4847. },
  4848. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4849. this.save();
  4850. this.current = new CanvasExtraState();
  4851. },
  4852. endAnnotations: function CanvasGraphics_endAnnotations() {
  4853. this.restore();
  4854. },
  4855. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4856. matrix) {
  4857. this.save();
  4858. if (isArray(rect) && 4 === rect.length) {
  4859. var width = rect[2] - rect[0];
  4860. var height = rect[3] - rect[1];
  4861. this.rectangle(rect[0], rect[1], width, height);
  4862. this.clip();
  4863. this.endPath();
  4864. }
  4865. this.transform.apply(this, transform);
  4866. this.transform.apply(this, matrix);
  4867. },
  4868. endAnnotation: function CanvasGraphics_endAnnotation() {
  4869. this.restore();
  4870. },
  4871. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4872. var domImage = this.objs.get(objId);
  4873. if (!domImage) {
  4874. warn('Dependent image isn\'t ready yet');
  4875. return;
  4876. }
  4877. this.save();
  4878. var ctx = this.ctx;
  4879. // scale the image to the unit square
  4880. ctx.scale(1 / w, -1 / h);
  4881. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4882. 0, -h, w, h);
  4883. if (this.imageLayer) {
  4884. var currentTransform = ctx.mozCurrentTransformInverse;
  4885. var position = this.getCanvasPosition(0, 0);
  4886. this.imageLayer.appendImage({
  4887. objId: objId,
  4888. left: position[0],
  4889. top: position[1],
  4890. width: w / currentTransform[0],
  4891. height: h / currentTransform[3]
  4892. });
  4893. }
  4894. this.restore();
  4895. },
  4896. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4897. var ctx = this.ctx;
  4898. var width = img.width, height = img.height;
  4899. var glyph = this.processingType3;
  4900. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  4901. var MAX_SIZE_TO_COMPILE = 1000;
  4902. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4903. glyph.compiled =
  4904. compileType3Glyph({data: img.data, width: width, height: height});
  4905. } else {
  4906. glyph.compiled = null;
  4907. }
  4908. }
  4909. if (glyph && glyph.compiled) {
  4910. glyph.compiled(ctx);
  4911. return;
  4912. }
  4913. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4914. var maskCtx = maskCanvas.context;
  4915. maskCtx.save();
  4916. putBinaryImageMask(maskCtx, img);
  4917. maskCtx.globalCompositeOperation = 'source-in';
  4918. var fillColor = this.current.fillColor;
  4919. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4920. fillColor.type === 'Pattern') ?
  4921. fillColor.getPattern(maskCtx, this) : fillColor;
  4922. maskCtx.fillRect(0, 0, width, height);
  4923. maskCtx.restore();
  4924. this.paintInlineImageXObject(maskCanvas.canvas);
  4925. },
  4926. paintImageMaskXObjectRepeat:
  4927. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4928. scaleY, positions) {
  4929. var width = imgData.width;
  4930. var height = imgData.height;
  4931. var ctx = this.ctx;
  4932. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4933. var maskCtx = maskCanvas.context;
  4934. maskCtx.save();
  4935. putBinaryImageMask(maskCtx, imgData);
  4936. maskCtx.globalCompositeOperation = 'source-in';
  4937. var fillColor = this.current.fillColor;
  4938. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4939. fillColor.type === 'Pattern') ?
  4940. fillColor.getPattern(maskCtx, this) : fillColor;
  4941. maskCtx.fillRect(0, 0, width, height);
  4942. maskCtx.restore();
  4943. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4944. ctx.save();
  4945. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4946. ctx.scale(1, -1);
  4947. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4948. 0, -1, 1, 1);
  4949. ctx.restore();
  4950. }
  4951. },
  4952. paintImageMaskXObjectGroup:
  4953. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4954. var ctx = this.ctx;
  4955. for (var i = 0, ii = images.length; i < ii; i++) {
  4956. var image = images[i];
  4957. var width = image.width, height = image.height;
  4958. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4959. var maskCtx = maskCanvas.context;
  4960. maskCtx.save();
  4961. putBinaryImageMask(maskCtx, image);
  4962. maskCtx.globalCompositeOperation = 'source-in';
  4963. var fillColor = this.current.fillColor;
  4964. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  4965. fillColor.type === 'Pattern') ?
  4966. fillColor.getPattern(maskCtx, this) : fillColor;
  4967. maskCtx.fillRect(0, 0, width, height);
  4968. maskCtx.restore();
  4969. ctx.save();
  4970. ctx.transform.apply(ctx, image.transform);
  4971. ctx.scale(1, -1);
  4972. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4973. 0, -1, 1, 1);
  4974. ctx.restore();
  4975. }
  4976. },
  4977. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4978. var imgData = this.objs.get(objId);
  4979. if (!imgData) {
  4980. warn('Dependent image isn\'t ready yet');
  4981. return;
  4982. }
  4983. this.paintInlineImageXObject(imgData);
  4984. },
  4985. paintImageXObjectRepeat:
  4986. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4987. positions) {
  4988. var imgData = this.objs.get(objId);
  4989. if (!imgData) {
  4990. warn('Dependent image isn\'t ready yet');
  4991. return;
  4992. }
  4993. var width = imgData.width;
  4994. var height = imgData.height;
  4995. var map = [];
  4996. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4997. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4998. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4999. }
  5000. this.paintInlineImageXObjectGroup(imgData, map);
  5001. },
  5002. paintInlineImageXObject:
  5003. function CanvasGraphics_paintInlineImageXObject(imgData) {
  5004. var width = imgData.width;
  5005. var height = imgData.height;
  5006. var ctx = this.ctx;
  5007. this.save();
  5008. // scale the image to the unit square
  5009. ctx.scale(1 / width, -1 / height);
  5010. var currentTransform = ctx.mozCurrentTransformInverse;
  5011. var a = currentTransform[0], b = currentTransform[1];
  5012. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  5013. var c = currentTransform[2], d = currentTransform[3];
  5014. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  5015. var imgToPaint, tmpCanvas;
  5016. // instanceof HTMLElement does not work in jsdom node.js module
  5017. if (imgData instanceof HTMLElement || !imgData.data) {
  5018. imgToPaint = imgData;
  5019. } else {
  5020. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  5021. var tmpCtx = tmpCanvas.context;
  5022. putBinaryImageData(tmpCtx, imgData);
  5023. imgToPaint = tmpCanvas.canvas;
  5024. }
  5025. var paintWidth = width, paintHeight = height;
  5026. var tmpCanvasId = 'prescale1';
  5027. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  5028. // pixels during drawImage operation, painting on the temporary canvas(es)
  5029. // that are twice smaller in size
  5030. while ((widthScale > 2 && paintWidth > 1) ||
  5031. (heightScale > 2 && paintHeight > 1)) {
  5032. var newWidth = paintWidth, newHeight = paintHeight;
  5033. if (widthScale > 2 && paintWidth > 1) {
  5034. newWidth = Math.ceil(paintWidth / 2);
  5035. widthScale /= paintWidth / newWidth;
  5036. }
  5037. if (heightScale > 2 && paintHeight > 1) {
  5038. newHeight = Math.ceil(paintHeight / 2);
  5039. heightScale /= paintHeight / newHeight;
  5040. }
  5041. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5042. tmpCtx = tmpCanvas.context;
  5043. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5044. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5045. 0, 0, newWidth, newHeight);
  5046. imgToPaint = tmpCanvas.canvas;
  5047. paintWidth = newWidth;
  5048. paintHeight = newHeight;
  5049. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  5050. }
  5051. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  5052. 0, -height, width, height);
  5053. if (this.imageLayer) {
  5054. var position = this.getCanvasPosition(0, -height);
  5055. this.imageLayer.appendImage({
  5056. imgData: imgData,
  5057. left: position[0],
  5058. top: position[1],
  5059. width: width / currentTransform[0],
  5060. height: height / currentTransform[3]
  5061. });
  5062. }
  5063. this.restore();
  5064. },
  5065. paintInlineImageXObjectGroup:
  5066. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  5067. var ctx = this.ctx;
  5068. var w = imgData.width;
  5069. var h = imgData.height;
  5070. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  5071. var tmpCtx = tmpCanvas.context;
  5072. putBinaryImageData(tmpCtx, imgData);
  5073. for (var i = 0, ii = map.length; i < ii; i++) {
  5074. var entry = map[i];
  5075. ctx.save();
  5076. ctx.transform.apply(ctx, entry.transform);
  5077. ctx.scale(1, -1);
  5078. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  5079. 0, -1, 1, 1);
  5080. if (this.imageLayer) {
  5081. var position = this.getCanvasPosition(entry.x, entry.y);
  5082. this.imageLayer.appendImage({
  5083. imgData: imgData,
  5084. left: position[0],
  5085. top: position[1],
  5086. width: w,
  5087. height: h
  5088. });
  5089. }
  5090. ctx.restore();
  5091. }
  5092. },
  5093. paintSolidColorImageMask:
  5094. function CanvasGraphics_paintSolidColorImageMask() {
  5095. this.ctx.fillRect(0, 0, 1, 1);
  5096. },
  5097. // Marked content
  5098. markPoint: function CanvasGraphics_markPoint(tag) {
  5099. // TODO Marked content.
  5100. },
  5101. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  5102. // TODO Marked content.
  5103. },
  5104. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  5105. // TODO Marked content.
  5106. },
  5107. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  5108. tag, properties) {
  5109. // TODO Marked content.
  5110. },
  5111. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  5112. // TODO Marked content.
  5113. },
  5114. // Compatibility
  5115. beginCompat: function CanvasGraphics_beginCompat() {
  5116. // TODO ignore undefined operators (should we do that anyway?)
  5117. },
  5118. endCompat: function CanvasGraphics_endCompat() {
  5119. // TODO stop ignoring undefined operators
  5120. },
  5121. // Helper functions
  5122. consumePath: function CanvasGraphics_consumePath() {
  5123. var ctx = this.ctx;
  5124. if (this.pendingClip) {
  5125. if (this.pendingClip === EO_CLIP) {
  5126. if (ctx.mozFillRule !== undefined) {
  5127. ctx.mozFillRule = 'evenodd';
  5128. ctx.clip();
  5129. ctx.mozFillRule = 'nonzero';
  5130. } else {
  5131. try {
  5132. ctx.clip('evenodd');
  5133. } catch (ex) {
  5134. // shouldn't really happen, but browsers might think differently
  5135. ctx.clip();
  5136. }
  5137. }
  5138. } else {
  5139. ctx.clip();
  5140. }
  5141. this.pendingClip = null;
  5142. }
  5143. ctx.beginPath();
  5144. },
  5145. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  5146. var inverse = this.ctx.mozCurrentTransformInverse;
  5147. // max of the current horizontal and vertical scale
  5148. return Math.sqrt(Math.max(
  5149. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  5150. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  5151. },
  5152. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  5153. var transform = this.ctx.mozCurrentTransform;
  5154. return [
  5155. transform[0] * x + transform[2] * y + transform[4],
  5156. transform[1] * x + transform[3] * y + transform[5]
  5157. ];
  5158. }
  5159. };
  5160. for (var op in OPS) {
  5161. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  5162. }
  5163. return CanvasGraphics;
  5164. })();
  5165. var WebGLUtils = (function WebGLUtilsClosure() {
  5166. function loadShader(gl, code, shaderType) {
  5167. var shader = gl.createShader(shaderType);
  5168. gl.shaderSource(shader, code);
  5169. gl.compileShader(shader);
  5170. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5171. if (!compiled) {
  5172. var errorMsg = gl.getShaderInfoLog(shader);
  5173. throw new Error('Error during shader compilation: ' + errorMsg);
  5174. }
  5175. return shader;
  5176. }
  5177. function createVertexShader(gl, code) {
  5178. return loadShader(gl, code, gl.VERTEX_SHADER);
  5179. }
  5180. function createFragmentShader(gl, code) {
  5181. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5182. }
  5183. function createProgram(gl, shaders) {
  5184. var program = gl.createProgram();
  5185. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5186. gl.attachShader(program, shaders[i]);
  5187. }
  5188. gl.linkProgram(program);
  5189. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5190. if (!linked) {
  5191. var errorMsg = gl.getProgramInfoLog(program);
  5192. throw new Error('Error during program linking: ' + errorMsg);
  5193. }
  5194. return program;
  5195. }
  5196. function createTexture(gl, image, textureId) {
  5197. gl.activeTexture(textureId);
  5198. var texture = gl.createTexture();
  5199. gl.bindTexture(gl.TEXTURE_2D, texture);
  5200. // Set the parameters so we can render any size image.
  5201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5205. // Upload the image into the texture.
  5206. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5207. return texture;
  5208. }
  5209. var currentGL, currentCanvas;
  5210. function generageGL() {
  5211. if (currentGL) {
  5212. return;
  5213. }
  5214. currentCanvas = document.createElement('canvas');
  5215. currentGL = currentCanvas.getContext('webgl',
  5216. { premultipliedalpha: false });
  5217. }
  5218. var smaskVertexShaderCode = '\
  5219. attribute vec2 a_position; \
  5220. attribute vec2 a_texCoord; \
  5221. \
  5222. uniform vec2 u_resolution; \
  5223. \
  5224. varying vec2 v_texCoord; \
  5225. \
  5226. void main() { \
  5227. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5228. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5229. \
  5230. v_texCoord = a_texCoord; \
  5231. } ';
  5232. var smaskFragmentShaderCode = '\
  5233. precision mediump float; \
  5234. \
  5235. uniform vec4 u_backdrop; \
  5236. uniform int u_subtype; \
  5237. uniform sampler2D u_image; \
  5238. uniform sampler2D u_mask; \
  5239. \
  5240. varying vec2 v_texCoord; \
  5241. \
  5242. void main() { \
  5243. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5244. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5245. if (u_backdrop.a > 0.0) { \
  5246. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5247. u_backdrop.rgb * (1.0 - maskColor.a); \
  5248. } \
  5249. float lum; \
  5250. if (u_subtype == 0) { \
  5251. lum = maskColor.a; \
  5252. } else { \
  5253. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5254. maskColor.b * 0.11; \
  5255. } \
  5256. imageColor.a *= lum; \
  5257. imageColor.rgb *= imageColor.a; \
  5258. gl_FragColor = imageColor; \
  5259. } ';
  5260. var smaskCache = null;
  5261. function initSmaskGL() {
  5262. var canvas, gl;
  5263. generageGL();
  5264. canvas = currentCanvas;
  5265. currentCanvas = null;
  5266. gl = currentGL;
  5267. currentGL = null;
  5268. // setup a GLSL program
  5269. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5270. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5271. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5272. gl.useProgram(program);
  5273. var cache = {};
  5274. cache.gl = gl;
  5275. cache.canvas = canvas;
  5276. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5277. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5278. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5279. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5280. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5281. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5282. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5283. // provide texture coordinates for the rectangle.
  5284. var texCoordBuffer = gl.createBuffer();
  5285. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5286. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5287. 0.0, 0.0,
  5288. 1.0, 0.0,
  5289. 0.0, 1.0,
  5290. 0.0, 1.0,
  5291. 1.0, 0.0,
  5292. 1.0, 1.0]), gl.STATIC_DRAW);
  5293. gl.enableVertexAttribArray(texCoordLocation);
  5294. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5295. gl.uniform1i(texLayerLocation, 0);
  5296. gl.uniform1i(texMaskLocation, 1);
  5297. smaskCache = cache;
  5298. }
  5299. function composeSMask(layer, mask, properties) {
  5300. var width = layer.width, height = layer.height;
  5301. if (!smaskCache) {
  5302. initSmaskGL();
  5303. }
  5304. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5305. canvas.width = width;
  5306. canvas.height = height;
  5307. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5308. gl.uniform2f(cache.resolutionLocation, width, height);
  5309. if (properties.backdrop) {
  5310. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5311. properties.backdrop[1], properties.backdrop[2], 1);
  5312. } else {
  5313. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5314. }
  5315. gl.uniform1i(cache.subtypeLocation,
  5316. properties.subtype === 'Luminosity' ? 1 : 0);
  5317. // Create a textures
  5318. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5319. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5320. // Create a buffer and put a single clipspace rectangle in
  5321. // it (2 triangles)
  5322. var buffer = gl.createBuffer();
  5323. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5324. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5325. 0, 0,
  5326. width, 0,
  5327. 0, height,
  5328. 0, height,
  5329. width, 0,
  5330. width, height]), gl.STATIC_DRAW);
  5331. gl.enableVertexAttribArray(cache.positionLocation);
  5332. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5333. // draw
  5334. gl.clearColor(0, 0, 0, 0);
  5335. gl.enable(gl.BLEND);
  5336. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5337. gl.clear(gl.COLOR_BUFFER_BIT);
  5338. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5339. gl.flush();
  5340. gl.deleteTexture(texture);
  5341. gl.deleteTexture(maskTexture);
  5342. gl.deleteBuffer(buffer);
  5343. return canvas;
  5344. }
  5345. var figuresVertexShaderCode = '\
  5346. attribute vec2 a_position; \
  5347. attribute vec3 a_color; \
  5348. \
  5349. uniform vec2 u_resolution; \
  5350. uniform vec2 u_scale; \
  5351. uniform vec2 u_offset; \
  5352. \
  5353. varying vec4 v_color; \
  5354. \
  5355. void main() { \
  5356. vec2 position = (a_position + u_offset) * u_scale; \
  5357. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5358. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5359. \
  5360. v_color = vec4(a_color / 255.0, 1.0); \
  5361. } ';
  5362. var figuresFragmentShaderCode = '\
  5363. precision mediump float; \
  5364. \
  5365. varying vec4 v_color; \
  5366. \
  5367. void main() { \
  5368. gl_FragColor = v_color; \
  5369. } ';
  5370. var figuresCache = null;
  5371. function initFiguresGL() {
  5372. var canvas, gl;
  5373. generageGL();
  5374. canvas = currentCanvas;
  5375. currentCanvas = null;
  5376. gl = currentGL;
  5377. currentGL = null;
  5378. // setup a GLSL program
  5379. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5380. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5381. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5382. gl.useProgram(program);
  5383. var cache = {};
  5384. cache.gl = gl;
  5385. cache.canvas = canvas;
  5386. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5387. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5388. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5389. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5390. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5391. figuresCache = cache;
  5392. }
  5393. function drawFigures(width, height, backgroundColor, figures, context) {
  5394. if (!figuresCache) {
  5395. initFiguresGL();
  5396. }
  5397. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5398. canvas.width = width;
  5399. canvas.height = height;
  5400. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5401. gl.uniform2f(cache.resolutionLocation, width, height);
  5402. // count triangle points
  5403. var count = 0;
  5404. var i, ii, rows;
  5405. for (i = 0, ii = figures.length; i < ii; i++) {
  5406. switch (figures[i].type) {
  5407. case 'lattice':
  5408. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5409. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5410. break;
  5411. case 'triangles':
  5412. count += figures[i].coords.length;
  5413. break;
  5414. }
  5415. }
  5416. // transfer data
  5417. var coords = new Float32Array(count * 2);
  5418. var colors = new Uint8Array(count * 3);
  5419. var coordsMap = context.coords, colorsMap = context.colors;
  5420. var pIndex = 0, cIndex = 0;
  5421. for (i = 0, ii = figures.length; i < ii; i++) {
  5422. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5423. switch (figure.type) {
  5424. case 'lattice':
  5425. var cols = figure.verticesPerRow;
  5426. rows = (ps.length / cols) | 0;
  5427. for (var row = 1; row < rows; row++) {
  5428. var offset = row * cols + 1;
  5429. for (var col = 1; col < cols; col++, offset++) {
  5430. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5431. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5432. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5433. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5434. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5435. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5436. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5437. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5438. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5439. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5440. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5441. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5442. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5443. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5444. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5445. coords[pIndex + 6] = coords[pIndex + 2];
  5446. coords[pIndex + 7] = coords[pIndex + 3];
  5447. coords[pIndex + 8] = coords[pIndex + 4];
  5448. coords[pIndex + 9] = coords[pIndex + 5];
  5449. coords[pIndex + 10] = coordsMap[ps[offset]];
  5450. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5451. colors[cIndex + 9] = colors[cIndex + 3];
  5452. colors[cIndex + 10] = colors[cIndex + 4];
  5453. colors[cIndex + 11] = colors[cIndex + 5];
  5454. colors[cIndex + 12] = colors[cIndex + 6];
  5455. colors[cIndex + 13] = colors[cIndex + 7];
  5456. colors[cIndex + 14] = colors[cIndex + 8];
  5457. colors[cIndex + 15] = colorsMap[cs[offset]];
  5458. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5459. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5460. pIndex += 12;
  5461. cIndex += 18;
  5462. }
  5463. }
  5464. break;
  5465. case 'triangles':
  5466. for (var j = 0, jj = ps.length; j < jj; j++) {
  5467. coords[pIndex] = coordsMap[ps[j]];
  5468. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5469. colors[cIndex] = colorsMap[cs[i]];
  5470. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5471. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5472. pIndex += 2;
  5473. cIndex += 3;
  5474. }
  5475. break;
  5476. }
  5477. }
  5478. // draw
  5479. if (backgroundColor) {
  5480. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5481. backgroundColor[2] / 255, 1.0);
  5482. } else {
  5483. gl.clearColor(0, 0, 0, 0);
  5484. }
  5485. gl.clear(gl.COLOR_BUFFER_BIT);
  5486. var coordsBuffer = gl.createBuffer();
  5487. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5488. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5489. gl.enableVertexAttribArray(cache.positionLocation);
  5490. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5491. var colorsBuffer = gl.createBuffer();
  5492. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5493. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5494. gl.enableVertexAttribArray(cache.colorLocation);
  5495. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5496. 0, 0);
  5497. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5498. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5499. gl.drawArrays(gl.TRIANGLES, 0, count);
  5500. gl.flush();
  5501. gl.deleteBuffer(coordsBuffer);
  5502. gl.deleteBuffer(colorsBuffer);
  5503. return canvas;
  5504. }
  5505. function cleanup() {
  5506. smaskCache = null;
  5507. figuresCache = null;
  5508. }
  5509. return {
  5510. get isEnabled() {
  5511. if (PDFJS.disableWebGL) {
  5512. return false;
  5513. }
  5514. var enabled = false;
  5515. try {
  5516. generageGL();
  5517. enabled = !!currentGL;
  5518. } catch (e) { }
  5519. return shadow(this, 'isEnabled', enabled);
  5520. },
  5521. composeSMask: composeSMask,
  5522. drawFigures: drawFigures,
  5523. clear: cleanup
  5524. };
  5525. })();
  5526. var ShadingIRs = {};
  5527. ShadingIRs.RadialAxial = {
  5528. fromIR: function RadialAxial_fromIR(raw) {
  5529. var type = raw[1];
  5530. var colorStops = raw[2];
  5531. var p0 = raw[3];
  5532. var p1 = raw[4];
  5533. var r0 = raw[5];
  5534. var r1 = raw[6];
  5535. return {
  5536. type: 'Pattern',
  5537. getPattern: function RadialAxial_getPattern(ctx) {
  5538. var grad;
  5539. if (type === 'axial') {
  5540. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5541. } else if (type === 'radial') {
  5542. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5543. }
  5544. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5545. var c = colorStops[i];
  5546. grad.addColorStop(c[0], c[1]);
  5547. }
  5548. return grad;
  5549. }
  5550. };
  5551. }
  5552. };
  5553. var createMeshCanvas = (function createMeshCanvasClosure() {
  5554. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5555. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5556. var coords = context.coords, colors = context.colors;
  5557. var bytes = data.data, rowSize = data.width * 4;
  5558. var tmp;
  5559. if (coords[p1 + 1] > coords[p2 + 1]) {
  5560. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5561. }
  5562. if (coords[p2 + 1] > coords[p3 + 1]) {
  5563. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5564. }
  5565. if (coords[p1 + 1] > coords[p2 + 1]) {
  5566. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5567. }
  5568. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5569. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5570. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5571. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5572. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5573. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5574. if (y1 >= y3) {
  5575. return;
  5576. }
  5577. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5578. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5579. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5580. var minY = Math.round(y1), maxY = Math.round(y3);
  5581. var xa, car, cag, cab;
  5582. var xb, cbr, cbg, cbb;
  5583. var k;
  5584. for (var y = minY; y <= maxY; y++) {
  5585. if (y < y2) {
  5586. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5587. xa = x1 - (x1 - x2) * k;
  5588. car = c1r - (c1r - c2r) * k;
  5589. cag = c1g - (c1g - c2g) * k;
  5590. cab = c1b - (c1b - c2b) * k;
  5591. } else {
  5592. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5593. xa = x2 - (x2 - x3) * k;
  5594. car = c2r - (c2r - c3r) * k;
  5595. cag = c2g - (c2g - c3g) * k;
  5596. cab = c2b - (c2b - c3b) * k;
  5597. }
  5598. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5599. xb = x1 - (x1 - x3) * k;
  5600. cbr = c1r - (c1r - c3r) * k;
  5601. cbg = c1g - (c1g - c3g) * k;
  5602. cbb = c1b - (c1b - c3b) * k;
  5603. var x1_ = Math.round(Math.min(xa, xb));
  5604. var x2_ = Math.round(Math.max(xa, xb));
  5605. var j = rowSize * y + x1_ * 4;
  5606. for (var x = x1_; x <= x2_; x++) {
  5607. k = (xa - x) / (xa - xb);
  5608. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5609. bytes[j++] = (car - (car - cbr) * k) | 0;
  5610. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5611. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5612. bytes[j++] = 255;
  5613. }
  5614. }
  5615. }
  5616. function drawFigure(data, figure, context) {
  5617. var ps = figure.coords;
  5618. var cs = figure.colors;
  5619. var i, ii;
  5620. switch (figure.type) {
  5621. case 'lattice':
  5622. var verticesPerRow = figure.verticesPerRow;
  5623. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5624. var cols = verticesPerRow - 1;
  5625. for (i = 0; i < rows; i++) {
  5626. var q = i * verticesPerRow;
  5627. for (var j = 0; j < cols; j++, q++) {
  5628. drawTriangle(data, context,
  5629. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5630. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5631. drawTriangle(data, context,
  5632. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5633. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5634. }
  5635. }
  5636. break;
  5637. case 'triangles':
  5638. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5639. drawTriangle(data, context,
  5640. ps[i], ps[i + 1], ps[i + 2],
  5641. cs[i], cs[i + 1], cs[i + 2]);
  5642. }
  5643. break;
  5644. default:
  5645. error('illigal figure');
  5646. break;
  5647. }
  5648. }
  5649. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5650. backgroundColor) {
  5651. // we will increase scale on some weird factor to let antialiasing take
  5652. // care of "rough" edges
  5653. var EXPECTED_SCALE = 1.1;
  5654. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5655. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5656. var offsetX = Math.floor(bounds[0]);
  5657. var offsetY = Math.floor(bounds[1]);
  5658. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5659. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5660. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5661. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5662. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5663. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5664. var scaleX = boundsWidth / width;
  5665. var scaleY = boundsHeight / height;
  5666. var context = {
  5667. coords: coords,
  5668. colors: colors,
  5669. offsetX: -offsetX,
  5670. offsetY: -offsetY,
  5671. scaleX: 1 / scaleX,
  5672. scaleY: 1 / scaleY
  5673. };
  5674. var canvas, tmpCanvas, i, ii;
  5675. if (WebGLUtils.isEnabled) {
  5676. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5677. figures, context);
  5678. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5679. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5680. tmpCanvas.context.drawImage(canvas, 0, 0);
  5681. canvas = tmpCanvas.canvas;
  5682. } else {
  5683. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5684. var tmpCtx = tmpCanvas.context;
  5685. var data = tmpCtx.createImageData(width, height);
  5686. if (backgroundColor) {
  5687. var bytes = data.data;
  5688. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5689. bytes[i] = backgroundColor[0];
  5690. bytes[i + 1] = backgroundColor[1];
  5691. bytes[i + 2] = backgroundColor[2];
  5692. bytes[i + 3] = 255;
  5693. }
  5694. }
  5695. for (i = 0; i < figures.length; i++) {
  5696. drawFigure(data, figures[i], context);
  5697. }
  5698. tmpCtx.putImageData(data, 0, 0);
  5699. canvas = tmpCanvas.canvas;
  5700. }
  5701. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5702. scaleX: scaleX, scaleY: scaleY};
  5703. }
  5704. return createMeshCanvas;
  5705. })();
  5706. ShadingIRs.Mesh = {
  5707. fromIR: function Mesh_fromIR(raw) {
  5708. //var type = raw[1];
  5709. var coords = raw[2];
  5710. var colors = raw[3];
  5711. var figures = raw[4];
  5712. var bounds = raw[5];
  5713. var matrix = raw[6];
  5714. //var bbox = raw[7];
  5715. var background = raw[8];
  5716. return {
  5717. type: 'Pattern',
  5718. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5719. var combinedScale;
  5720. // Obtain scale from matrix and current transformation matrix.
  5721. if (shadingFill) {
  5722. combinedScale = Util.singularValueDecompose2dScale(
  5723. ctx.mozCurrentTransform);
  5724. } else {
  5725. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5726. var curMatrixScale = Util.singularValueDecompose2dScale(
  5727. owner.baseTransform);
  5728. combinedScale = [matrixScale[0] * curMatrixScale[0],
  5729. matrixScale[1] * curMatrixScale[1]];
  5730. }
  5731. // Rasterizing on the main thread since sending/queue large canvases
  5732. // might cause OOM.
  5733. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  5734. coords, colors, figures, shadingFill ? null : background);
  5735. if (!shadingFill) {
  5736. ctx.setTransform.apply(ctx, owner.baseTransform);
  5737. if (matrix) {
  5738. ctx.transform.apply(ctx, matrix);
  5739. }
  5740. }
  5741. ctx.translate(temporaryPatternCanvas.offsetX,
  5742. temporaryPatternCanvas.offsetY);
  5743. ctx.scale(temporaryPatternCanvas.scaleX,
  5744. temporaryPatternCanvas.scaleY);
  5745. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5746. }
  5747. };
  5748. }
  5749. };
  5750. ShadingIRs.Dummy = {
  5751. fromIR: function Dummy_fromIR() {
  5752. return {
  5753. type: 'Pattern',
  5754. getPattern: function Dummy_fromIR_getPattern() {
  5755. return 'hotpink';
  5756. }
  5757. };
  5758. }
  5759. };
  5760. function getShadingPatternFromIR(raw) {
  5761. var shadingIR = ShadingIRs[raw[0]];
  5762. if (!shadingIR) {
  5763. error('Unknown IR type: ' + raw[0]);
  5764. }
  5765. return shadingIR.fromIR(raw);
  5766. }
  5767. var TilingPattern = (function TilingPatternClosure() {
  5768. var PaintType = {
  5769. COLORED: 1,
  5770. UNCOLORED: 2
  5771. };
  5772. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5773. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5774. this.operatorList = IR[2];
  5775. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5776. this.bbox = IR[4];
  5777. this.xstep = IR[5];
  5778. this.ystep = IR[6];
  5779. this.paintType = IR[7];
  5780. this.tilingType = IR[8];
  5781. this.color = color;
  5782. this.objs = objs;
  5783. this.commonObjs = commonObjs;
  5784. this.baseTransform = baseTransform;
  5785. this.type = 'Pattern';
  5786. this.ctx = ctx;
  5787. }
  5788. TilingPattern.prototype = {
  5789. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5790. var operatorList = this.operatorList;
  5791. var bbox = this.bbox;
  5792. var xstep = this.xstep;
  5793. var ystep = this.ystep;
  5794. var paintType = this.paintType;
  5795. var tilingType = this.tilingType;
  5796. var color = this.color;
  5797. var objs = this.objs;
  5798. var commonObjs = this.commonObjs;
  5799. info('TilingType: ' + tilingType);
  5800. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5801. var topLeft = [x0, y0];
  5802. // we want the canvas to be as large as the step size
  5803. var botRight = [x0 + xstep, y0 + ystep];
  5804. var width = botRight[0] - topLeft[0];
  5805. var height = botRight[1] - topLeft[1];
  5806. // Obtain scale from matrix and current transformation matrix.
  5807. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5808. var curMatrixScale = Util.singularValueDecompose2dScale(
  5809. this.baseTransform);
  5810. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5811. matrixScale[1] * curMatrixScale[1]];
  5812. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5813. // Use width and height values that are as close as possible to the end
  5814. // result when the pattern is used. Too low value makes the pattern look
  5815. // blurry. Too large value makes it look too crispy.
  5816. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5817. MAX_PATTERN_SIZE);
  5818. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5819. MAX_PATTERN_SIZE);
  5820. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5821. var tmpCtx = tmpCanvas.context;
  5822. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5823. graphics.groupLevel = owner.groupLevel;
  5824. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5825. this.setScale(width, height, xstep, ystep);
  5826. this.transformToScale(graphics);
  5827. // transform coordinates to pattern space
  5828. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5829. graphics.transform.apply(graphics, tmpTranslate);
  5830. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5831. graphics.executeOperatorList(operatorList);
  5832. return tmpCanvas.canvas;
  5833. },
  5834. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5835. this.scale = [width / xstep, height / ystep];
  5836. },
  5837. transformToScale: function TilingPattern_transformToScale(graphics) {
  5838. var scale = this.scale;
  5839. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5840. graphics.transform.apply(graphics, tmpScale);
  5841. },
  5842. scaleToContext: function TilingPattern_scaleToContext() {
  5843. var scale = this.scale;
  5844. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5845. },
  5846. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5847. if (bbox && isArray(bbox) && 4 == bbox.length) {
  5848. var bboxWidth = x1 - x0;
  5849. var bboxHeight = y1 - y0;
  5850. graphics.rectangle(x0, y0, bboxWidth, bboxHeight);
  5851. graphics.clip();
  5852. graphics.endPath();
  5853. }
  5854. },
  5855. setFillAndStrokeStyleToContext:
  5856. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5857. switch (paintType) {
  5858. case PaintType.COLORED:
  5859. var ctx = this.ctx;
  5860. context.fillStyle = ctx.fillStyle;
  5861. context.strokeStyle = ctx.strokeStyle;
  5862. break;
  5863. case PaintType.UNCOLORED:
  5864. var cssColor = Util.makeCssRgb(color);
  5865. context.fillStyle = cssColor;
  5866. context.strokeStyle = cssColor;
  5867. break;
  5868. default:
  5869. error('Unsupported paint type: ' + paintType);
  5870. }
  5871. },
  5872. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5873. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5874. ctx = this.ctx;
  5875. ctx.setTransform.apply(ctx, this.baseTransform);
  5876. ctx.transform.apply(ctx, this.matrix);
  5877. this.scaleToContext();
  5878. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5879. }
  5880. };
  5881. return TilingPattern;
  5882. })();
  5883. PDFJS.disableFontFace = false;
  5884. var FontLoader = {
  5885. insertRule: function fontLoaderInsertRule(rule) {
  5886. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5887. if (!styleElement) {
  5888. styleElement = document.createElement('style');
  5889. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5890. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5891. styleElement);
  5892. }
  5893. var styleSheet = styleElement.sheet;
  5894. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5895. },
  5896. clear: function fontLoaderClear() {
  5897. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5898. if (styleElement) {
  5899. styleElement.parentNode.removeChild(styleElement);
  5900. }
  5901. },
  5902. get loadTestFont() {
  5903. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5904. // height.
  5905. return shadow(this, 'loadTestFont', atob(
  5906. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5907. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5908. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5909. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5910. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5911. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5912. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5913. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5914. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5915. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5916. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5917. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5918. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5919. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5920. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5921. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5922. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5923. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5924. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5925. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5926. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5927. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5928. ));
  5929. },
  5930. loadTestFontId: 0,
  5931. loadingContext: {
  5932. requests: [],
  5933. nextRequestId: 0
  5934. },
  5935. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5936. if (isWorker) {
  5937. return false;
  5938. }
  5939. // User agent string sniffing is bad, but there is no reliable way to tell
  5940. // if font is fully loaded and ready to be used with canvas.
  5941. var userAgent = window.navigator.userAgent;
  5942. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5943. if (m && m[1] >= 14) {
  5944. return true;
  5945. }
  5946. // TODO other browsers
  5947. return false;
  5948. })(),
  5949. bind: function fontLoaderBind(fonts, callback) {
  5950. assert(!isWorker, 'bind() shall be called from main thread');
  5951. var rules = [], fontsToLoad = [];
  5952. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5953. var font = fonts[i];
  5954. // Add the font to the DOM only once or skip if the font
  5955. // is already loaded.
  5956. if (font.attached || font.loading === false) {
  5957. continue;
  5958. }
  5959. font.attached = true;
  5960. var rule = font.bindDOM();
  5961. if (rule) {
  5962. rules.push(rule);
  5963. fontsToLoad.push(font);
  5964. }
  5965. }
  5966. var request = FontLoader.queueLoadingCallback(callback);
  5967. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5968. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5969. } else {
  5970. request.complete();
  5971. }
  5972. },
  5973. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5974. function LoadLoader_completeRequest() {
  5975. assert(!request.end, 'completeRequest() cannot be called twice');
  5976. request.end = Date.now();
  5977. // sending all completed requests in order how they were queued
  5978. while (context.requests.length > 0 && context.requests[0].end) {
  5979. var otherRequest = context.requests.shift();
  5980. setTimeout(otherRequest.callback, 0);
  5981. }
  5982. }
  5983. var context = FontLoader.loadingContext;
  5984. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5985. var request = {
  5986. id: requestId,
  5987. complete: LoadLoader_completeRequest,
  5988. callback: callback,
  5989. started: Date.now()
  5990. };
  5991. context.requests.push(request);
  5992. return request;
  5993. },
  5994. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5995. fonts,
  5996. request) {
  5997. /** Hack begin */
  5998. // There's currently no event when a font has finished downloading so the
  5999. // following code is a dirty hack to 'guess' when a font is
  6000. // ready. It's assumed fonts are loaded in order, so add a known test
  6001. // font after the desired fonts and then test for the loading of that
  6002. // test font.
  6003. function int32(data, offset) {
  6004. return (data.charCodeAt(offset) << 24) |
  6005. (data.charCodeAt(offset + 1) << 16) |
  6006. (data.charCodeAt(offset + 2) << 8) |
  6007. (data.charCodeAt(offset + 3) & 0xff);
  6008. }
  6009. function spliceString(s, offset, remove, insert) {
  6010. var chunk1 = s.substr(0, offset);
  6011. var chunk2 = s.substr(offset + remove);
  6012. return chunk1 + insert + chunk2;
  6013. }
  6014. var i, ii;
  6015. var canvas = document.createElement('canvas');
  6016. canvas.width = 1;
  6017. canvas.height = 1;
  6018. var ctx = canvas.getContext('2d');
  6019. var called = 0;
  6020. function isFontReady(name, callback) {
  6021. called++;
  6022. // With setTimeout clamping this gives the font ~100ms to load.
  6023. if(called > 30) {
  6024. warn('Load test font never loaded.');
  6025. callback();
  6026. return;
  6027. }
  6028. ctx.font = '30px ' + name;
  6029. ctx.fillText('.', 0, 20);
  6030. var imageData = ctx.getImageData(0, 0, 1, 1);
  6031. if (imageData.data[3] > 0) {
  6032. callback();
  6033. return;
  6034. }
  6035. setTimeout(isFontReady.bind(null, name, callback));
  6036. }
  6037. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  6038. // Chromium seems to cache fonts based on a hash of the actual font data,
  6039. // so the font must be modified for each load test else it will appear to
  6040. // be loaded already.
  6041. // TODO: This could maybe be made faster by avoiding the btoa of the full
  6042. // font by splitting it in chunks before hand and padding the font id.
  6043. var data = this.loadTestFont;
  6044. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  6045. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  6046. loadTestFontId);
  6047. // CFF checksum is important for IE, adjusting it
  6048. var CFF_CHECKSUM_OFFSET = 16;
  6049. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  6050. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  6051. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  6052. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  6053. }
  6054. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  6055. checksum = (checksum - XXXX_VALUE +
  6056. int32(loadTestFontId + 'XXX', i)) | 0;
  6057. }
  6058. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  6059. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  6060. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  6061. url + '}';
  6062. FontLoader.insertRule(rule);
  6063. var names = [];
  6064. for (i = 0, ii = fonts.length; i < ii; i++) {
  6065. names.push(fonts[i].loadedName);
  6066. }
  6067. names.push(loadTestFontId);
  6068. var div = document.createElement('div');
  6069. div.setAttribute('style',
  6070. 'visibility: hidden;' +
  6071. 'width: 10px; height: 10px;' +
  6072. 'position: absolute; top: 0px; left: 0px;');
  6073. for (i = 0, ii = names.length; i < ii; ++i) {
  6074. var span = document.createElement('span');
  6075. span.textContent = 'Hi';
  6076. span.style.fontFamily = names[i];
  6077. div.appendChild(span);
  6078. }
  6079. document.body.appendChild(div);
  6080. isFontReady(loadTestFontId, function() {
  6081. document.body.removeChild(div);
  6082. request.complete();
  6083. });
  6084. /** Hack end */
  6085. }
  6086. };
  6087. var FontFace = (function FontFaceClosure() {
  6088. function FontFace(name, file, properties) {
  6089. this.compiledGlyphs = {};
  6090. if (arguments.length === 1) {
  6091. // importing translated data
  6092. var data = arguments[0];
  6093. for (var i in data) {
  6094. this[i] = data[i];
  6095. }
  6096. return;
  6097. }
  6098. }
  6099. FontFace.prototype = {
  6100. bindDOM: function FontFace_bindDOM() {
  6101. if (!this.data) {
  6102. return null;
  6103. }
  6104. if (PDFJS.disableFontFace) {
  6105. this.disableFontFace = true;
  6106. return null;
  6107. }
  6108. var data = bytesToString(new Uint8Array(this.data));
  6109. var fontName = this.loadedName;
  6110. // Add the font-face rule to the document
  6111. var url = ('url(data:' + this.mimetype + ';base64,' +
  6112. window.btoa(data) + ');');
  6113. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  6114. FontLoader.insertRule(rule);
  6115. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  6116. globalScope['FontInspector'].enabled) {
  6117. globalScope['FontInspector'].fontAdded(this, url);
  6118. }
  6119. return rule;
  6120. },
  6121. getPathGenerator: function (objs, character) {
  6122. if (!(character in this.compiledGlyphs)) {
  6123. var js = objs.get(this.loadedName + '_path_' + character);
  6124. /*jshint -W054 */
  6125. this.compiledGlyphs[character] = new Function('c', 'size', js);
  6126. }
  6127. return this.compiledGlyphs[character];
  6128. }
  6129. };
  6130. return FontFace;
  6131. })();
  6132. }).call((typeof window === 'undefined') ? this : window);
  6133. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  6134. // workerSrc is not set -- using last script url to define default location
  6135. PDFJS.workerSrc = (function () {
  6136. 'use strict';
  6137. var scriptTagContainer = document.body ||
  6138. document.getElementsByTagName('head')[0];
  6139. var pdfjsSrc = scriptTagContainer.lastChild.src;
  6140. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  6141. })();
  6142. }