pdf.js 219 KB

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