pdf.js 275 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663
  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.239';
  23. PDFJS.build = 'fb74b02';
  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. Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) {
  493. var rgb = ColorSpace.singletons.cmyk.getRgb(cmyk, 0);
  494. return Util.makeCssRgb(rgb);
  495. };
  496. // Concatenates two transformation matrices together and returns the result.
  497. Util.transform = function Util_transform(m1, m2) {
  498. return [
  499. m1[0] * m2[0] + m1[2] * m2[1],
  500. m1[1] * m2[0] + m1[3] * m2[1],
  501. m1[0] * m2[2] + m1[2] * m2[3],
  502. m1[1] * m2[2] + m1[3] * m2[3],
  503. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  504. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  505. ];
  506. };
  507. // For 2d affine transforms
  508. Util.applyTransform = function Util_applyTransform(p, m) {
  509. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  510. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  511. return [xt, yt];
  512. };
  513. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  514. var d = m[0] * m[3] - m[1] * m[2];
  515. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  516. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  517. return [xt, yt];
  518. };
  519. // Applies the transform to the rectangle and finds the minimum axially
  520. // aligned bounding box.
  521. Util.getAxialAlignedBoundingBox =
  522. function Util_getAxialAlignedBoundingBox(r, m) {
  523. var p1 = Util.applyTransform(r, m);
  524. var p2 = Util.applyTransform(r.slice(2, 4), m);
  525. var p3 = Util.applyTransform([r[0], r[3]], m);
  526. var p4 = Util.applyTransform([r[2], r[1]], m);
  527. return [
  528. Math.min(p1[0], p2[0], p3[0], p4[0]),
  529. Math.min(p1[1], p2[1], p3[1], p4[1]),
  530. Math.max(p1[0], p2[0], p3[0], p4[0]),
  531. Math.max(p1[1], p2[1], p3[1], p4[1])
  532. ];
  533. };
  534. Util.inverseTransform = function Util_inverseTransform(m) {
  535. var d = m[0] * m[3] - m[1] * m[2];
  536. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  537. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  538. };
  539. // Apply a generic 3d matrix M on a 3-vector v:
  540. // | a b c | | X |
  541. // | d e f | x | Y |
  542. // | g h i | | Z |
  543. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  544. // with v as [X,Y,Z]
  545. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  546. return [
  547. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  548. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  549. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  550. ];
  551. };
  552. // This calculation uses Singular Value Decomposition.
  553. // The SVD can be represented with formula A = USV. We are interested in the
  554. // matrix S here because it represents the scale values.
  555. Util.singularValueDecompose2dScale =
  556. function Util_singularValueDecompose2dScale(m) {
  557. var transpose = [m[0], m[2], m[1], m[3]];
  558. // Multiply matrix m with its transpose.
  559. var a = m[0] * transpose[0] + m[1] * transpose[2];
  560. var b = m[0] * transpose[1] + m[1] * transpose[3];
  561. var c = m[2] * transpose[0] + m[3] * transpose[2];
  562. var d = m[2] * transpose[1] + m[3] * transpose[3];
  563. // Solve the second degree polynomial to get roots.
  564. var first = (a + d) / 2;
  565. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  566. var sx = first + second || 1;
  567. var sy = first - second || 1;
  568. // Scale values are the square roots of the eigenvalues.
  569. return [Math.sqrt(sx), Math.sqrt(sy)];
  570. };
  571. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  572. // For coordinate systems whose origin lies in the bottom-left, this
  573. // means normalization to (BL,TR) ordering. For systems with origin in the
  574. // top-left, this means (TL,BR) ordering.
  575. Util.normalizeRect = function Util_normalizeRect(rect) {
  576. var r = rect.slice(0); // clone rect
  577. if (rect[0] > rect[2]) {
  578. r[0] = rect[2];
  579. r[2] = rect[0];
  580. }
  581. if (rect[1] > rect[3]) {
  582. r[1] = rect[3];
  583. r[3] = rect[1];
  584. }
  585. return r;
  586. };
  587. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  588. // intersection of rect1 and rect2. If no intersection, returns 'false'
  589. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  590. Util.intersect = function Util_intersect(rect1, rect2) {
  591. function compare(a, b) {
  592. return a - b;
  593. }
  594. // Order points along the axes
  595. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  596. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  597. result = [];
  598. rect1 = Util.normalizeRect(rect1);
  599. rect2 = Util.normalizeRect(rect2);
  600. // X: first and second points belong to different rectangles?
  601. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  602. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  603. // Intersection must be between second and third points
  604. result[0] = orderedX[1];
  605. result[2] = orderedX[2];
  606. } else {
  607. return false;
  608. }
  609. // Y: first and second points belong to different rectangles?
  610. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  611. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  612. // Intersection must be between second and third points
  613. result[1] = orderedY[1];
  614. result[3] = orderedY[2];
  615. } else {
  616. return false;
  617. }
  618. return result;
  619. };
  620. Util.sign = function Util_sign(num) {
  621. return num < 0 ? -1 : 1;
  622. };
  623. // TODO(mack): Rename appendToArray
  624. Util.concatenateToArray = function concatenateToArray(arr1, arr2) {
  625. Array.prototype.push.apply(arr1, arr2);
  626. };
  627. Util.prependToArray = function concatenateToArray(arr1, arr2) {
  628. Array.prototype.unshift.apply(arr1, arr2);
  629. };
  630. Util.extendObj = function extendObj(obj1, obj2) {
  631. for (var key in obj2) {
  632. obj1[key] = obj2[key];
  633. }
  634. };
  635. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  636. name) {
  637. while (dict && !dict.has(name)) {
  638. dict = dict.get('Parent');
  639. }
  640. if (!dict) {
  641. return null;
  642. }
  643. return dict.get(name);
  644. };
  645. Util.inherit = function Util_inherit(sub, base, prototype) {
  646. sub.prototype = Object.create(base.prototype);
  647. sub.prototype.constructor = sub;
  648. for (var prop in prototype) {
  649. sub.prototype[prop] = prototype[prop];
  650. }
  651. };
  652. Util.loadScript = function Util_loadScript(src, callback) {
  653. var script = document.createElement('script');
  654. var loaded = false;
  655. script.setAttribute('src', src);
  656. if (callback) {
  657. script.onload = function() {
  658. if (!loaded) {
  659. callback();
  660. }
  661. loaded = true;
  662. };
  663. }
  664. document.getElementsByTagName('head')[0].appendChild(script);
  665. };
  666. return Util;
  667. })();
  668. /**
  669. * PDF page viewport created based on scale, rotation and offset.
  670. * @class
  671. * @alias PDFJS.PageViewport
  672. */
  673. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  674. /**
  675. * @constructor
  676. * @private
  677. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  678. * @param scale {number} scale of the viewport.
  679. * @param rotation {number} rotations of the viewport in degrees.
  680. * @param offsetX {number} offset X
  681. * @param offsetY {number} offset Y
  682. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  683. */
  684. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  685. this.viewBox = viewBox;
  686. this.scale = scale;
  687. this.rotation = rotation;
  688. this.offsetX = offsetX;
  689. this.offsetY = offsetY;
  690. // creating transform to convert pdf coordinate system to the normal
  691. // canvas like coordinates taking in account scale and rotation
  692. var centerX = (viewBox[2] + viewBox[0]) / 2;
  693. var centerY = (viewBox[3] + viewBox[1]) / 2;
  694. var rotateA, rotateB, rotateC, rotateD;
  695. rotation = rotation % 360;
  696. rotation = rotation < 0 ? rotation + 360 : rotation;
  697. switch (rotation) {
  698. case 180:
  699. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  700. break;
  701. case 90:
  702. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  703. break;
  704. case 270:
  705. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  706. break;
  707. //case 0:
  708. default:
  709. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  710. break;
  711. }
  712. if (dontFlip) {
  713. rotateC = -rotateC; rotateD = -rotateD;
  714. }
  715. var offsetCanvasX, offsetCanvasY;
  716. var width, height;
  717. if (rotateA === 0) {
  718. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  719. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  720. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  721. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  722. } else {
  723. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  724. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  725. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  726. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  727. }
  728. // creating transform for the following operations:
  729. // translate(-centerX, -centerY), rotate and flip vertically,
  730. // scale, and translate(offsetCanvasX, offsetCanvasY)
  731. this.transform = [
  732. rotateA * scale,
  733. rotateB * scale,
  734. rotateC * scale,
  735. rotateD * scale,
  736. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  737. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  738. ];
  739. this.width = width;
  740. this.height = height;
  741. this.fontScale = scale;
  742. }
  743. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  744. /**
  745. * Clones viewport with additional properties.
  746. * @param args {Object} (optional) If specified, may contain the 'scale' or
  747. * 'rotation' properties to override the corresponding properties in
  748. * the cloned viewport.
  749. * @returns {PDFJS.PageViewport} Cloned viewport.
  750. */
  751. clone: function PageViewPort_clone(args) {
  752. args = args || {};
  753. var scale = 'scale' in args ? args.scale : this.scale;
  754. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  755. return new PageViewport(this.viewBox.slice(), scale, rotation,
  756. this.offsetX, this.offsetY, args.dontFlip);
  757. },
  758. /**
  759. * Converts PDF point to the viewport coordinates. For examples, useful for
  760. * converting PDF location into canvas pixel coordinates.
  761. * @param x {number} X coordinate.
  762. * @param y {number} Y coordinate.
  763. * @returns {Object} Object that contains 'x' and 'y' properties of the
  764. * point in the viewport coordinate space.
  765. * @see {@link convertToPdfPoint}
  766. * @see {@link convertToViewportRectangle}
  767. */
  768. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  769. return Util.applyTransform([x, y], this.transform);
  770. },
  771. /**
  772. * Converts PDF rectangle to the viewport coordinates.
  773. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  774. * @returns {Array} Contains corresponding coordinates of the rectangle
  775. * in the viewport coordinate space.
  776. * @see {@link convertToViewportPoint}
  777. */
  778. convertToViewportRectangle:
  779. function PageViewport_convertToViewportRectangle(rect) {
  780. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  781. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  782. return [tl[0], tl[1], br[0], br[1]];
  783. },
  784. /**
  785. * Converts viewport coordinates to the PDF location. For examples, useful
  786. * for converting canvas pixel location into PDF one.
  787. * @param x {number} X coordinate.
  788. * @param y {number} Y coordinate.
  789. * @returns {Object} Object that contains 'x' and 'y' properties of the
  790. * point in the PDF coordinate space.
  791. * @see {@link convertToViewportPoint}
  792. */
  793. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  794. return Util.applyInverseTransform([x, y], this.transform);
  795. }
  796. };
  797. return PageViewport;
  798. })();
  799. var PDFStringTranslateTable = [
  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,
  801. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  802. 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,
  803. 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,
  804. 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,
  805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  806. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  807. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  808. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  809. ];
  810. function stringToPDFString(str) {
  811. var i, n = str.length, strBuf = [];
  812. if (str[0] === '\xFE' && str[1] === '\xFF') {
  813. // UTF16BE BOM
  814. for (i = 2; i < n; i += 2) {
  815. strBuf.push(String.fromCharCode(
  816. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  817. }
  818. } else {
  819. for (i = 0; i < n; ++i) {
  820. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  821. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  822. }
  823. }
  824. return strBuf.join('');
  825. }
  826. function stringToUTF8String(str) {
  827. return decodeURIComponent(escape(str));
  828. }
  829. function isEmptyObj(obj) {
  830. for (var key in obj) {
  831. return false;
  832. }
  833. return true;
  834. }
  835. function isBool(v) {
  836. return typeof v == 'boolean';
  837. }
  838. function isInt(v) {
  839. return typeof v == 'number' && ((v | 0) == v);
  840. }
  841. function isNum(v) {
  842. return typeof v == 'number';
  843. }
  844. function isString(v) {
  845. return typeof v == 'string';
  846. }
  847. function isNull(v) {
  848. return v === null;
  849. }
  850. function isName(v) {
  851. return v instanceof Name;
  852. }
  853. function isCmd(v, cmd) {
  854. return v instanceof Cmd && (!cmd || v.cmd == cmd);
  855. }
  856. function isDict(v, type) {
  857. if (!(v instanceof Dict)) {
  858. return false;
  859. }
  860. if (!type) {
  861. return true;
  862. }
  863. var dictType = v.get('Type');
  864. return isName(dictType) && dictType.name == type;
  865. }
  866. function isArray(v) {
  867. return v instanceof Array;
  868. }
  869. function isStream(v) {
  870. return typeof v == 'object' && v !== null && v !== undefined &&
  871. ('getBytes' in v);
  872. }
  873. function isArrayBuffer(v) {
  874. return typeof v == 'object' && v !== null && v !== undefined &&
  875. ('byteLength' in v);
  876. }
  877. function isRef(v) {
  878. return v instanceof Ref;
  879. }
  880. function isPDFFunction(v) {
  881. var fnDict;
  882. if (typeof v != 'object') {
  883. return false;
  884. } else if (isDict(v)) {
  885. fnDict = v;
  886. } else if (isStream(v)) {
  887. fnDict = v.dict;
  888. } else {
  889. return false;
  890. }
  891. return fnDict.has('FunctionType');
  892. }
  893. /**
  894. * Promise Capability object.
  895. *
  896. * @typedef {Object} PromiseCapability
  897. * @property {Promise} promise - A promise object.
  898. * @property {function} resolve - Fullfills the promise.
  899. * @property {function} reject - Rejects the promise.
  900. */
  901. /**
  902. * Creates a promise capability object.
  903. * @alias PDFJS.createPromiseCapability
  904. *
  905. * @return {PromiseCapability} A capability object contains:
  906. * - a Promise, resolve and reject methods.
  907. */
  908. function createPromiseCapability() {
  909. var capability = {};
  910. capability.promise = new Promise(function (resolve, reject) {
  911. capability.resolve = resolve;
  912. capability.reject = reject;
  913. });
  914. return capability;
  915. }
  916. PDFJS.createPromiseCapability = createPromiseCapability;
  917. /**
  918. * Polyfill for Promises:
  919. * The following promise implementation tries to generally implement the
  920. * Promise/A+ spec. Some notable differences from other promise libaries are:
  921. * - There currently isn't a seperate deferred and promise object.
  922. * - Unhandled rejections eventually show an error if they aren't handled.
  923. *
  924. * Based off of the work in:
  925. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  926. */
  927. (function PromiseClosure() {
  928. if (globalScope.Promise) {
  929. // Promises existing in the DOM/Worker, checking presence of all/resolve
  930. if (typeof globalScope.Promise.all !== 'function') {
  931. globalScope.Promise.all = function (iterable) {
  932. var count = 0, results = [], resolve, reject;
  933. var promise = new globalScope.Promise(function (resolve_, reject_) {
  934. resolve = resolve_;
  935. reject = reject_;
  936. });
  937. iterable.forEach(function (p, i) {
  938. count++;
  939. p.then(function (result) {
  940. results[i] = result;
  941. count--;
  942. if (count === 0) {
  943. resolve(results);
  944. }
  945. }, reject);
  946. });
  947. if (count === 0) {
  948. resolve(results);
  949. }
  950. return promise;
  951. };
  952. }
  953. if (typeof globalScope.Promise.resolve !== 'function') {
  954. globalScope.Promise.resolve = function (value) {
  955. return new globalScope.Promise(function (resolve) { resolve(value); });
  956. };
  957. }
  958. if (typeof globalScope.Promise.reject !== 'function') {
  959. globalScope.Promise.reject = function (reason) {
  960. return new globalScope.Promise(function (resolve, reject) {
  961. reject(reason);
  962. });
  963. };
  964. }
  965. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  966. globalScope.Promise.prototype.catch = function (onReject) {
  967. return globalScope.Promise.prototype.then(undefined, onReject);
  968. };
  969. }
  970. return;
  971. }
  972. var STATUS_PENDING = 0;
  973. var STATUS_RESOLVED = 1;
  974. var STATUS_REJECTED = 2;
  975. // In an attempt to avoid silent exceptions, unhandled rejections are
  976. // tracked and if they aren't handled in a certain amount of time an
  977. // error is logged.
  978. var REJECTION_TIMEOUT = 500;
  979. var HandlerManager = {
  980. handlers: [],
  981. running: false,
  982. unhandledRejections: [],
  983. pendingRejectionCheck: false,
  984. scheduleHandlers: function scheduleHandlers(promise) {
  985. if (promise._status == STATUS_PENDING) {
  986. return;
  987. }
  988. this.handlers = this.handlers.concat(promise._handlers);
  989. promise._handlers = [];
  990. if (this.running) {
  991. return;
  992. }
  993. this.running = true;
  994. setTimeout(this.runHandlers.bind(this), 0);
  995. },
  996. runHandlers: function runHandlers() {
  997. var RUN_TIMEOUT = 1; // ms
  998. var timeoutAt = Date.now() + RUN_TIMEOUT;
  999. while (this.handlers.length > 0) {
  1000. var handler = this.handlers.shift();
  1001. var nextStatus = handler.thisPromise._status;
  1002. var nextValue = handler.thisPromise._value;
  1003. try {
  1004. if (nextStatus === STATUS_RESOLVED) {
  1005. if (typeof(handler.onResolve) == 'function') {
  1006. nextValue = handler.onResolve(nextValue);
  1007. }
  1008. } else if (typeof(handler.onReject) === 'function') {
  1009. nextValue = handler.onReject(nextValue);
  1010. nextStatus = STATUS_RESOLVED;
  1011. if (handler.thisPromise._unhandledRejection) {
  1012. this.removeUnhandeledRejection(handler.thisPromise);
  1013. }
  1014. }
  1015. } catch (ex) {
  1016. nextStatus = STATUS_REJECTED;
  1017. nextValue = ex;
  1018. }
  1019. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1020. if (Date.now() >= timeoutAt) {
  1021. break;
  1022. }
  1023. }
  1024. if (this.handlers.length > 0) {
  1025. setTimeout(this.runHandlers.bind(this), 0);
  1026. return;
  1027. }
  1028. this.running = false;
  1029. },
  1030. addUnhandledRejection: function addUnhandledRejection(promise) {
  1031. this.unhandledRejections.push({
  1032. promise: promise,
  1033. time: Date.now()
  1034. });
  1035. this.scheduleRejectionCheck();
  1036. },
  1037. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1038. promise._unhandledRejection = false;
  1039. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1040. if (this.unhandledRejections[i].promise === promise) {
  1041. this.unhandledRejections.splice(i);
  1042. i--;
  1043. }
  1044. }
  1045. },
  1046. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1047. if (this.pendingRejectionCheck) {
  1048. return;
  1049. }
  1050. this.pendingRejectionCheck = true;
  1051. setTimeout(function rejectionCheck() {
  1052. this.pendingRejectionCheck = false;
  1053. var now = Date.now();
  1054. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1055. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1056. var unhandled = this.unhandledRejections[i].promise._value;
  1057. var msg = 'Unhandled rejection: ' + unhandled;
  1058. if (unhandled.stack) {
  1059. msg += '\n' + unhandled.stack;
  1060. }
  1061. warn(msg);
  1062. this.unhandledRejections.splice(i);
  1063. i--;
  1064. }
  1065. }
  1066. if (this.unhandledRejections.length) {
  1067. this.scheduleRejectionCheck();
  1068. }
  1069. }.bind(this), REJECTION_TIMEOUT);
  1070. }
  1071. };
  1072. function Promise(resolver) {
  1073. this._status = STATUS_PENDING;
  1074. this._handlers = [];
  1075. try {
  1076. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1077. } catch (e) {
  1078. this._reject(e);
  1079. }
  1080. }
  1081. /**
  1082. * Builds a promise that is resolved when all the passed in promises are
  1083. * resolved.
  1084. * @param {array} array of data and/or promises to wait for.
  1085. * @return {Promise} New dependant promise.
  1086. */
  1087. Promise.all = function Promise_all(promises) {
  1088. var resolveAll, rejectAll;
  1089. var deferred = new Promise(function (resolve, reject) {
  1090. resolveAll = resolve;
  1091. rejectAll = reject;
  1092. });
  1093. var unresolved = promises.length;
  1094. var results = [];
  1095. if (unresolved === 0) {
  1096. resolveAll(results);
  1097. return deferred;
  1098. }
  1099. function reject(reason) {
  1100. if (deferred._status === STATUS_REJECTED) {
  1101. return;
  1102. }
  1103. results = [];
  1104. rejectAll(reason);
  1105. }
  1106. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1107. var promise = promises[i];
  1108. var resolve = (function(i) {
  1109. return function(value) {
  1110. if (deferred._status === STATUS_REJECTED) {
  1111. return;
  1112. }
  1113. results[i] = value;
  1114. unresolved--;
  1115. if (unresolved === 0) {
  1116. resolveAll(results);
  1117. }
  1118. };
  1119. })(i);
  1120. if (Promise.isPromise(promise)) {
  1121. promise.then(resolve, reject);
  1122. } else {
  1123. resolve(promise);
  1124. }
  1125. }
  1126. return deferred;
  1127. };
  1128. /**
  1129. * Checks if the value is likely a promise (has a 'then' function).
  1130. * @return {boolean} true if value is thenable
  1131. */
  1132. Promise.isPromise = function Promise_isPromise(value) {
  1133. return value && typeof value.then === 'function';
  1134. };
  1135. /**
  1136. * Creates resolved promise
  1137. * @param value resolve value
  1138. * @returns {Promise}
  1139. */
  1140. Promise.resolve = function Promise_resolve(value) {
  1141. return new Promise(function (resolve) { resolve(value); });
  1142. };
  1143. /**
  1144. * Creates rejected promise
  1145. * @param reason rejection value
  1146. * @returns {Promise}
  1147. */
  1148. Promise.reject = function Promise_reject(reason) {
  1149. return new Promise(function (resolve, reject) { reject(reason); });
  1150. };
  1151. Promise.prototype = {
  1152. _status: null,
  1153. _value: null,
  1154. _handlers: null,
  1155. _unhandledRejection: null,
  1156. _updateStatus: function Promise__updateStatus(status, value) {
  1157. if (this._status === STATUS_RESOLVED ||
  1158. this._status === STATUS_REJECTED) {
  1159. return;
  1160. }
  1161. if (status == STATUS_RESOLVED &&
  1162. Promise.isPromise(value)) {
  1163. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1164. this._updateStatus.bind(this, STATUS_REJECTED));
  1165. return;
  1166. }
  1167. this._status = status;
  1168. this._value = value;
  1169. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1170. this._unhandledRejection = true;
  1171. HandlerManager.addUnhandledRejection(this);
  1172. }
  1173. HandlerManager.scheduleHandlers(this);
  1174. },
  1175. _resolve: function Promise_resolve(value) {
  1176. this._updateStatus(STATUS_RESOLVED, value);
  1177. },
  1178. _reject: function Promise_reject(reason) {
  1179. this._updateStatus(STATUS_REJECTED, reason);
  1180. },
  1181. then: function Promise_then(onResolve, onReject) {
  1182. var nextPromise = new Promise(function (resolve, reject) {
  1183. this.resolve = reject;
  1184. this.reject = reject;
  1185. });
  1186. this._handlers.push({
  1187. thisPromise: this,
  1188. onResolve: onResolve,
  1189. onReject: onReject,
  1190. nextPromise: nextPromise
  1191. });
  1192. HandlerManager.scheduleHandlers(this);
  1193. return nextPromise;
  1194. },
  1195. catch: function Promise_catch(onReject) {
  1196. return this.then(undefined, onReject);
  1197. }
  1198. };
  1199. globalScope.Promise = Promise;
  1200. })();
  1201. var StatTimer = (function StatTimerClosure() {
  1202. function rpad(str, pad, length) {
  1203. while (str.length < length) {
  1204. str += pad;
  1205. }
  1206. return str;
  1207. }
  1208. function StatTimer() {
  1209. this.started = {};
  1210. this.times = [];
  1211. this.enabled = true;
  1212. }
  1213. StatTimer.prototype = {
  1214. time: function StatTimer_time(name) {
  1215. if (!this.enabled) {
  1216. return;
  1217. }
  1218. if (name in this.started) {
  1219. warn('Timer is already running for ' + name);
  1220. }
  1221. this.started[name] = Date.now();
  1222. },
  1223. timeEnd: function StatTimer_timeEnd(name) {
  1224. if (!this.enabled) {
  1225. return;
  1226. }
  1227. if (!(name in this.started)) {
  1228. warn('Timer has not been started for ' + name);
  1229. }
  1230. this.times.push({
  1231. 'name': name,
  1232. 'start': this.started[name],
  1233. 'end': Date.now()
  1234. });
  1235. // Remove timer from started so it can be called again.
  1236. delete this.started[name];
  1237. },
  1238. toString: function StatTimer_toString() {
  1239. var i, ii;
  1240. var times = this.times;
  1241. var out = '';
  1242. // Find the longest name for padding purposes.
  1243. var longest = 0;
  1244. for (i = 0, ii = times.length; i < ii; ++i) {
  1245. var name = times[i]['name'];
  1246. if (name.length > longest) {
  1247. longest = name.length;
  1248. }
  1249. }
  1250. for (i = 0, ii = times.length; i < ii; ++i) {
  1251. var span = times[i];
  1252. var duration = span.end - span.start;
  1253. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1254. }
  1255. return out;
  1256. }
  1257. };
  1258. return StatTimer;
  1259. })();
  1260. PDFJS.createBlob = function createBlob(data, contentType) {
  1261. if (typeof Blob !== 'undefined') {
  1262. return new Blob([data], { type: contentType });
  1263. }
  1264. // Blob builder is deprecated in FF14 and removed in FF18.
  1265. var bb = new MozBlobBuilder();
  1266. bb.append(data);
  1267. return bb.getBlob(contentType);
  1268. };
  1269. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1270. // Blob/createObjectURL is not available, falling back to data schema.
  1271. var digits =
  1272. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1273. return function createObjectURL(data, contentType) {
  1274. if (!PDFJS.disableCreateObjectURL &&
  1275. typeof URL !== 'undefined' && URL.createObjectURL) {
  1276. var blob = PDFJS.createBlob(data, contentType);
  1277. return URL.createObjectURL(blob);
  1278. }
  1279. var buffer = 'data:' + contentType + ';base64,';
  1280. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1281. var b1 = data[i] & 0xFF;
  1282. var b2 = data[i + 1] & 0xFF;
  1283. var b3 = data[i + 2] & 0xFF;
  1284. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1285. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1286. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1287. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1288. }
  1289. return buffer;
  1290. };
  1291. })();
  1292. function MessageHandler(name, comObj) {
  1293. this.name = name;
  1294. this.comObj = comObj;
  1295. this.callbackIndex = 1;
  1296. this.postMessageTransfers = true;
  1297. var callbacksCapabilities = this.callbacksCapabilities = {};
  1298. var ah = this.actionHandler = {};
  1299. ah['console_log'] = [function ahConsoleLog(data) {
  1300. console.log.apply(console, data);
  1301. }];
  1302. ah['console_error'] = [function ahConsoleError(data) {
  1303. console.error.apply(console, data);
  1304. }];
  1305. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1306. UnsupportedManager.notify(data);
  1307. }];
  1308. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1309. var data = event.data;
  1310. if (data.isReply) {
  1311. var callbackId = data.callbackId;
  1312. if (data.callbackId in callbacksCapabilities) {
  1313. var callback = callbacksCapabilities[callbackId];
  1314. delete callbacksCapabilities[callbackId];
  1315. if ('error' in data) {
  1316. callback.reject(data.error);
  1317. } else {
  1318. callback.resolve(data.data);
  1319. }
  1320. } else {
  1321. error('Cannot resolve callback ' + callbackId);
  1322. }
  1323. } else if (data.action in ah) {
  1324. var action = ah[data.action];
  1325. if (data.callbackId) {
  1326. Promise.resolve().then(function () {
  1327. return action[0].call(action[1], data.data);
  1328. }).then(function (result) {
  1329. comObj.postMessage({
  1330. isReply: true,
  1331. callbackId: data.callbackId,
  1332. data: result
  1333. });
  1334. }, function (reason) {
  1335. comObj.postMessage({
  1336. isReply: true,
  1337. callbackId: data.callbackId,
  1338. error: reason
  1339. });
  1340. });
  1341. } else {
  1342. action[0].call(action[1], data.data);
  1343. }
  1344. } else {
  1345. error('Unknown action from worker: ' + data.action);
  1346. }
  1347. };
  1348. }
  1349. MessageHandler.prototype = {
  1350. on: function messageHandlerOn(actionName, handler, scope) {
  1351. var ah = this.actionHandler;
  1352. if (ah[actionName]) {
  1353. error('There is already an actionName called "' + actionName + '"');
  1354. }
  1355. ah[actionName] = [handler, scope];
  1356. },
  1357. /**
  1358. * Sends a message to the comObj to invoke the action with the supplied data.
  1359. * @param {String} actionName Action to call.
  1360. * @param {JSON} data JSON data to send.
  1361. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1362. */
  1363. send: function messageHandlerSend(actionName, data, transfers) {
  1364. var message = {
  1365. action: actionName,
  1366. data: data
  1367. };
  1368. this.postMessage(message, transfers);
  1369. },
  1370. /**
  1371. * Sends a message to the comObj to invoke the action with the supplied data.
  1372. * Expects that other side will callback with the response.
  1373. * @param {String} actionName Action to call.
  1374. * @param {JSON} data JSON data to send.
  1375. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1376. * @returns {Promise} Promise to be resolved with response data.
  1377. */
  1378. sendWithPromise:
  1379. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1380. var callbackId = this.callbackIndex++;
  1381. var message = {
  1382. action: actionName,
  1383. data: data,
  1384. callbackId: callbackId
  1385. };
  1386. var capability = createPromiseCapability();
  1387. this.callbacksCapabilities[callbackId] = capability;
  1388. try {
  1389. this.postMessage(message, transfers);
  1390. } catch (e) {
  1391. capability.reject(e);
  1392. }
  1393. return capability.promise;
  1394. },
  1395. /**
  1396. * Sends raw message to the comObj.
  1397. * @private
  1398. * @param message {Object} Raw message.
  1399. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1400. */
  1401. postMessage: function (message, transfers) {
  1402. if (transfers && this.postMessageTransfers) {
  1403. this.comObj.postMessage(message, transfers);
  1404. } else {
  1405. this.comObj.postMessage(message);
  1406. }
  1407. }
  1408. };
  1409. function loadJpegStream(id, imageUrl, objs) {
  1410. var img = new Image();
  1411. img.onload = (function loadJpegStream_onloadClosure() {
  1412. objs.resolve(id, img);
  1413. });
  1414. img.src = imageUrl;
  1415. }
  1416. var ColorSpace = (function ColorSpaceClosure() {
  1417. // Constructor should define this.numComps, this.defaultColor, this.name
  1418. function ColorSpace() {
  1419. error('should not call ColorSpace constructor');
  1420. }
  1421. ColorSpace.prototype = {
  1422. /**
  1423. * Converts the color value to the RGB color. The color components are
  1424. * located in the src array starting from the srcOffset. Returns the array
  1425. * of the rgb components, each value ranging from [0,255].
  1426. */
  1427. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  1428. var rgb = new Uint8Array(3);
  1429. this.getRgbItem(src, srcOffset, rgb, 0);
  1430. return rgb;
  1431. },
  1432. /**
  1433. * Converts the color value to the RGB color, similar to the getRgb method.
  1434. * The result placed into the dest array starting from the destOffset.
  1435. */
  1436. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  1437. dest, destOffset) {
  1438. error('Should not call ColorSpace.getRgbItem');
  1439. },
  1440. /**
  1441. * Converts the specified number of the color values to the RGB colors.
  1442. * The colors are located in the src array starting from the srcOffset.
  1443. * The result is placed into the dest array starting from the destOffset.
  1444. * The src array items shall be in [0,2^bits) range, the dest array items
  1445. * will be in [0,255] range. alpha01 indicates how many alpha components
  1446. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  1447. * array).
  1448. */
  1449. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  1450. dest, destOffset, bits,
  1451. alpha01) {
  1452. error('Should not call ColorSpace.getRgbBuffer');
  1453. },
  1454. /**
  1455. * Determines the number of bytes required to store the result of the
  1456. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  1457. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  1458. */
  1459. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  1460. alpha01) {
  1461. error('Should not call ColorSpace.getOutputLength');
  1462. },
  1463. /**
  1464. * Returns true if source data will be equal the result/output data.
  1465. */
  1466. isPassthrough: function ColorSpace_isPassthrough(bits) {
  1467. return false;
  1468. },
  1469. /**
  1470. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  1471. * how many alpha components there are in the dest array; it will be either
  1472. * 0 (RGB array) or 1 (RGBA array).
  1473. */
  1474. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  1475. originalHeight, width, height,
  1476. actualHeight, bpc, comps, alpha01) {
  1477. var count = originalWidth * originalHeight;
  1478. var rgbBuf = null;
  1479. var numComponentColors = 1 << bpc;
  1480. var needsResizing = originalHeight != height || originalWidth != width;
  1481. var i, ii;
  1482. if (this.isPassthrough(bpc)) {
  1483. rgbBuf = comps;
  1484. } else if (this.numComps === 1 && count > numComponentColors &&
  1485. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  1486. // Optimization: create a color map when there is just one component and
  1487. // we are converting more colors than the size of the color map. We
  1488. // don't build the map if the colorspace is gray or rgb since those
  1489. // methods are faster than building a map. This mainly offers big speed
  1490. // ups for indexed and alternate colorspaces.
  1491. //
  1492. // TODO it may be worth while to cache the color map. While running
  1493. // testing I never hit a cache so I will leave that out for now (perhaps
  1494. // we are reparsing colorspaces too much?).
  1495. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  1496. new Uint16Array(numComponentColors);
  1497. var key;
  1498. for (i = 0; i < numComponentColors; i++) {
  1499. allColors[i] = i;
  1500. }
  1501. var colorMap = new Uint8Array(numComponentColors * 3);
  1502. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  1503. /* alpha01 = */ 0);
  1504. var destPos, rgbPos;
  1505. if (!needsResizing) {
  1506. // Fill in the RGB values directly into |dest|.
  1507. destPos = 0;
  1508. for (i = 0; i < count; ++i) {
  1509. key = comps[i] * 3;
  1510. dest[destPos++] = colorMap[key];
  1511. dest[destPos++] = colorMap[key + 1];
  1512. dest[destPos++] = colorMap[key + 2];
  1513. destPos += alpha01;
  1514. }
  1515. } else {
  1516. rgbBuf = new Uint8Array(count * 3);
  1517. rgbPos = 0;
  1518. for (i = 0; i < count; ++i) {
  1519. key = comps[i] * 3;
  1520. rgbBuf[rgbPos++] = colorMap[key];
  1521. rgbBuf[rgbPos++] = colorMap[key + 1];
  1522. rgbBuf[rgbPos++] = colorMap[key + 2];
  1523. }
  1524. }
  1525. } else {
  1526. if (!needsResizing) {
  1527. // Fill in the RGB values directly into |dest|.
  1528. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  1529. alpha01);
  1530. } else {
  1531. rgbBuf = new Uint8Array(count * 3);
  1532. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  1533. /* alpha01 = */ 0);
  1534. }
  1535. }
  1536. if (rgbBuf) {
  1537. if (needsResizing) {
  1538. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  1539. height, dest, alpha01);
  1540. } else {
  1541. rgbPos = 0;
  1542. destPos = 0;
  1543. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  1544. dest[destPos++] = rgbBuf[rgbPos++];
  1545. dest[destPos++] = rgbBuf[rgbPos++];
  1546. dest[destPos++] = rgbBuf[rgbPos++];
  1547. destPos += alpha01;
  1548. }
  1549. }
  1550. }
  1551. },
  1552. /**
  1553. * True if the colorspace has components in the default range of [0, 1].
  1554. * This should be true for all colorspaces except for lab color spaces
  1555. * which are [0,100], [-128, 127], [-128, 127].
  1556. */
  1557. usesZeroToOneRange: true
  1558. };
  1559. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  1560. var IR = ColorSpace.parseToIR(cs, xref, res);
  1561. if (IR instanceof AlternateCS) {
  1562. return IR;
  1563. }
  1564. return ColorSpace.fromIR(IR);
  1565. };
  1566. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  1567. var name = isArray(IR) ? IR[0] : IR;
  1568. var whitePoint, blackPoint;
  1569. switch (name) {
  1570. case 'DeviceGrayCS':
  1571. return this.singletons.gray;
  1572. case 'DeviceRgbCS':
  1573. return this.singletons.rgb;
  1574. case 'DeviceCmykCS':
  1575. return this.singletons.cmyk;
  1576. case 'CalGrayCS':
  1577. whitePoint = IR[1].WhitePoint;
  1578. blackPoint = IR[1].BlackPoint;
  1579. var gamma = IR[1].Gamma;
  1580. return new CalGrayCS(whitePoint, blackPoint, gamma);
  1581. case 'PatternCS':
  1582. var basePatternCS = IR[1];
  1583. if (basePatternCS) {
  1584. basePatternCS = ColorSpace.fromIR(basePatternCS);
  1585. }
  1586. return new PatternCS(basePatternCS);
  1587. case 'IndexedCS':
  1588. var baseIndexedCS = IR[1];
  1589. var hiVal = IR[2];
  1590. var lookup = IR[3];
  1591. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  1592. case 'AlternateCS':
  1593. var numComps = IR[1];
  1594. var alt = IR[2];
  1595. var tintFnIR = IR[3];
  1596. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  1597. PDFFunction.fromIR(tintFnIR));
  1598. case 'LabCS':
  1599. whitePoint = IR[1].WhitePoint;
  1600. blackPoint = IR[1].BlackPoint;
  1601. var range = IR[1].Range;
  1602. return new LabCS(whitePoint, blackPoint, range);
  1603. default:
  1604. error('Unkown name ' + name);
  1605. }
  1606. return null;
  1607. };
  1608. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  1609. if (isName(cs)) {
  1610. var colorSpaces = res.get('ColorSpace');
  1611. if (isDict(colorSpaces)) {
  1612. var refcs = colorSpaces.get(cs.name);
  1613. if (refcs) {
  1614. cs = refcs;
  1615. }
  1616. }
  1617. }
  1618. cs = xref.fetchIfRef(cs);
  1619. var mode;
  1620. if (isName(cs)) {
  1621. mode = cs.name;
  1622. this.mode = mode;
  1623. switch (mode) {
  1624. case 'DeviceGray':
  1625. case 'G':
  1626. return 'DeviceGrayCS';
  1627. case 'DeviceRGB':
  1628. case 'RGB':
  1629. return 'DeviceRgbCS';
  1630. case 'DeviceCMYK':
  1631. case 'CMYK':
  1632. return 'DeviceCmykCS';
  1633. case 'Pattern':
  1634. return ['PatternCS', null];
  1635. default:
  1636. error('unrecognized colorspace ' + mode);
  1637. }
  1638. } else if (isArray(cs)) {
  1639. mode = cs[0].name;
  1640. this.mode = mode;
  1641. var numComps, params;
  1642. switch (mode) {
  1643. case 'DeviceGray':
  1644. case 'G':
  1645. return 'DeviceGrayCS';
  1646. case 'DeviceRGB':
  1647. case 'RGB':
  1648. return 'DeviceRgbCS';
  1649. case 'DeviceCMYK':
  1650. case 'CMYK':
  1651. return 'DeviceCmykCS';
  1652. case 'CalGray':
  1653. params = cs[1].getAll();
  1654. return ['CalGrayCS', params];
  1655. case 'CalRGB':
  1656. return 'DeviceRgbCS';
  1657. case 'ICCBased':
  1658. var stream = xref.fetchIfRef(cs[1]);
  1659. var dict = stream.dict;
  1660. numComps = dict.get('N');
  1661. if (numComps == 1) {
  1662. return 'DeviceGrayCS';
  1663. } else if (numComps == 3) {
  1664. return 'DeviceRgbCS';
  1665. } else if (numComps == 4) {
  1666. return 'DeviceCmykCS';
  1667. }
  1668. break;
  1669. case 'Pattern':
  1670. var basePatternCS = cs[1];
  1671. if (basePatternCS) {
  1672. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  1673. }
  1674. return ['PatternCS', basePatternCS];
  1675. case 'Indexed':
  1676. case 'I':
  1677. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  1678. var hiVal = cs[2] + 1;
  1679. var lookup = xref.fetchIfRef(cs[3]);
  1680. if (isStream(lookup)) {
  1681. lookup = lookup.getBytes();
  1682. }
  1683. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  1684. case 'Separation':
  1685. case 'DeviceN':
  1686. var name = cs[1];
  1687. numComps = 1;
  1688. if (isName(name)) {
  1689. numComps = 1;
  1690. } else if (isArray(name)) {
  1691. numComps = name.length;
  1692. }
  1693. var alt = ColorSpace.parseToIR(cs[2], xref, res);
  1694. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  1695. return ['AlternateCS', numComps, alt, tintFnIR];
  1696. case 'Lab':
  1697. params = cs[1].getAll();
  1698. return ['LabCS', params];
  1699. default:
  1700. error('unimplemented color space object "' + mode + '"');
  1701. }
  1702. } else {
  1703. error('unrecognized color space object: "' + cs + '"');
  1704. }
  1705. return null;
  1706. };
  1707. /**
  1708. * Checks if a decode map matches the default decode map for a color space.
  1709. * This handles the general decode maps where there are two values per
  1710. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  1711. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  1712. * slightly different.
  1713. * @param {Array} decode Decode map (usually from an image).
  1714. * @param {Number} n Number of components the color space has.
  1715. */
  1716. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  1717. if (!decode) {
  1718. return true;
  1719. }
  1720. if (n * 2 !== decode.length) {
  1721. warn('The decode map is not the correct length');
  1722. return true;
  1723. }
  1724. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  1725. if (decode[i] !== 0 || decode[i + 1] != 1) {
  1726. return false;
  1727. }
  1728. }
  1729. return true;
  1730. };
  1731. ColorSpace.singletons = {
  1732. get gray() {
  1733. return shadow(this, 'gray', new DeviceGrayCS());
  1734. },
  1735. get rgb() {
  1736. return shadow(this, 'rgb', new DeviceRgbCS());
  1737. },
  1738. get cmyk() {
  1739. return shadow(this, 'cmyk', new DeviceCmykCS());
  1740. }
  1741. };
  1742. return ColorSpace;
  1743. })();
  1744. /**
  1745. * Alternate color space handles both Separation and DeviceN color spaces. A
  1746. * Separation color space is actually just a DeviceN with one color component.
  1747. * Both color spaces use a tinting function to convert colors to a base color
  1748. * space.
  1749. */
  1750. var AlternateCS = (function AlternateCSClosure() {
  1751. function AlternateCS(numComps, base, tintFn) {
  1752. this.name = 'Alternate';
  1753. this.numComps = numComps;
  1754. this.defaultColor = new Float32Array(numComps);
  1755. for (var i = 0; i < numComps; ++i) {
  1756. this.defaultColor[i] = 1;
  1757. }
  1758. this.base = base;
  1759. this.tintFn = tintFn;
  1760. }
  1761. AlternateCS.prototype = {
  1762. getRgb: ColorSpace.prototype.getRgb,
  1763. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  1764. dest, destOffset) {
  1765. var baseNumComps = this.base.numComps;
  1766. var input = 'subarray' in src ?
  1767. src.subarray(srcOffset, srcOffset + this.numComps) :
  1768. Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps);
  1769. var tinted = this.tintFn(input);
  1770. this.base.getRgbItem(tinted, 0, dest, destOffset);
  1771. },
  1772. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  1773. dest, destOffset, bits,
  1774. alpha01) {
  1775. var tinted;
  1776. var tintFn = this.tintFn;
  1777. var base = this.base;
  1778. var scale = 1 / ((1 << bits) - 1);
  1779. var baseNumComps = base.numComps;
  1780. var usesZeroToOneRange = base.usesZeroToOneRange;
  1781. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  1782. alpha01 === 0;
  1783. var pos = isPassthrough ? destOffset : 0;
  1784. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  1785. var numComps = this.numComps;
  1786. var scaled = new Float32Array(numComps);
  1787. var i, j;
  1788. if (usesZeroToOneRange) {
  1789. for (i = 0; i < count; i++) {
  1790. for (j = 0; j < numComps; j++) {
  1791. scaled[j] = src[srcOffset++] * scale;
  1792. }
  1793. tinted = tintFn(scaled);
  1794. for (j = 0; j < baseNumComps; j++) {
  1795. baseBuf[pos++] = tinted[j] * 255;
  1796. }
  1797. }
  1798. } else {
  1799. for (i = 0; i < count; i++) {
  1800. for (j = 0; j < numComps; j++) {
  1801. scaled[j] = src[srcOffset++] * scale;
  1802. }
  1803. tinted = tintFn(scaled);
  1804. base.getRgbItem(tinted, 0, baseBuf, pos);
  1805. pos += baseNumComps;
  1806. }
  1807. }
  1808. if (!isPassthrough) {
  1809. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  1810. }
  1811. },
  1812. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  1813. alpha01) {
  1814. return this.base.getOutputLength(inputLength *
  1815. this.base.numComps / this.numComps,
  1816. alpha01);
  1817. },
  1818. isPassthrough: ColorSpace.prototype.isPassthrough,
  1819. fillRgb: ColorSpace.prototype.fillRgb,
  1820. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  1821. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1822. },
  1823. usesZeroToOneRange: true
  1824. };
  1825. return AlternateCS;
  1826. })();
  1827. var PatternCS = (function PatternCSClosure() {
  1828. function PatternCS(baseCS) {
  1829. this.name = 'Pattern';
  1830. this.base = baseCS;
  1831. }
  1832. PatternCS.prototype = {};
  1833. return PatternCS;
  1834. })();
  1835. var IndexedCS = (function IndexedCSClosure() {
  1836. function IndexedCS(base, highVal, lookup) {
  1837. this.name = 'Indexed';
  1838. this.numComps = 1;
  1839. this.defaultColor = new Uint8Array([0]);
  1840. this.base = base;
  1841. this.highVal = highVal;
  1842. var baseNumComps = base.numComps;
  1843. var length = baseNumComps * highVal;
  1844. var lookupArray;
  1845. if (isStream(lookup)) {
  1846. lookupArray = new Uint8Array(length);
  1847. var bytes = lookup.getBytes(length);
  1848. lookupArray.set(bytes);
  1849. } else if (isString(lookup)) {
  1850. lookupArray = new Uint8Array(length);
  1851. for (var i = 0; i < length; ++i) {
  1852. lookupArray[i] = lookup.charCodeAt(i);
  1853. }
  1854. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  1855. lookupArray = lookup;
  1856. } else {
  1857. error('Unrecognized lookup table: ' + lookup);
  1858. }
  1859. this.lookup = lookupArray;
  1860. }
  1861. IndexedCS.prototype = {
  1862. getRgb: ColorSpace.prototype.getRgb,
  1863. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  1864. dest, destOffset) {
  1865. var numComps = this.base.numComps;
  1866. var start = src[srcOffset] * numComps;
  1867. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  1868. },
  1869. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  1870. dest, destOffset, bits,
  1871. alpha01) {
  1872. var base = this.base;
  1873. var numComps = base.numComps;
  1874. var outputDelta = base.getOutputLength(numComps, alpha01);
  1875. var lookup = this.lookup;
  1876. for (var i = 0; i < count; ++i) {
  1877. var lookupPos = src[srcOffset++] * numComps;
  1878. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  1879. destOffset += outputDelta;
  1880. }
  1881. },
  1882. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  1883. return this.base.getOutputLength(inputLength * this.base.numComps,
  1884. alpha01);
  1885. },
  1886. isPassthrough: ColorSpace.prototype.isPassthrough,
  1887. fillRgb: ColorSpace.prototype.fillRgb,
  1888. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  1889. // indexed color maps shouldn't be changed
  1890. return true;
  1891. },
  1892. usesZeroToOneRange: true
  1893. };
  1894. return IndexedCS;
  1895. })();
  1896. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  1897. function DeviceGrayCS() {
  1898. this.name = 'DeviceGray';
  1899. this.numComps = 1;
  1900. this.defaultColor = new Float32Array([0]);
  1901. }
  1902. DeviceGrayCS.prototype = {
  1903. getRgb: ColorSpace.prototype.getRgb,
  1904. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  1905. dest, destOffset) {
  1906. var c = (src[srcOffset] * 255) | 0;
  1907. c = c < 0 ? 0 : c > 255 ? 255 : c;
  1908. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  1909. },
  1910. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  1911. dest, destOffset, bits,
  1912. alpha01) {
  1913. var scale = 255 / ((1 << bits) - 1);
  1914. var j = srcOffset, q = destOffset;
  1915. for (var i = 0; i < count; ++i) {
  1916. var c = (scale * src[j++]) | 0;
  1917. dest[q++] = c;
  1918. dest[q++] = c;
  1919. dest[q++] = c;
  1920. q += alpha01;
  1921. }
  1922. },
  1923. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  1924. alpha01) {
  1925. return inputLength * (3 + alpha01);
  1926. },
  1927. isPassthrough: ColorSpace.prototype.isPassthrough,
  1928. fillRgb: ColorSpace.prototype.fillRgb,
  1929. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  1930. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1931. },
  1932. usesZeroToOneRange: true
  1933. };
  1934. return DeviceGrayCS;
  1935. })();
  1936. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  1937. function DeviceRgbCS() {
  1938. this.name = 'DeviceRGB';
  1939. this.numComps = 3;
  1940. this.defaultColor = new Float32Array([0, 0, 0]);
  1941. }
  1942. DeviceRgbCS.prototype = {
  1943. getRgb: ColorSpace.prototype.getRgb,
  1944. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  1945. dest, destOffset) {
  1946. var r = (src[srcOffset] * 255) | 0;
  1947. var g = (src[srcOffset + 1] * 255) | 0;
  1948. var b = (src[srcOffset + 2] * 255) | 0;
  1949. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  1950. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  1951. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  1952. },
  1953. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  1954. dest, destOffset, bits,
  1955. alpha01) {
  1956. if (bits === 8 && alpha01 === 0) {
  1957. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  1958. return;
  1959. }
  1960. var scale = 255 / ((1 << bits) - 1);
  1961. var j = srcOffset, q = destOffset;
  1962. for (var i = 0; i < count; ++i) {
  1963. dest[q++] = (scale * src[j++]) | 0;
  1964. dest[q++] = (scale * src[j++]) | 0;
  1965. dest[q++] = (scale * src[j++]) | 0;
  1966. q += alpha01;
  1967. }
  1968. },
  1969. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  1970. alpha01) {
  1971. return (inputLength * (3 + alpha01) / 3) | 0;
  1972. },
  1973. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  1974. return bits == 8;
  1975. },
  1976. fillRgb: ColorSpace.prototype.fillRgb,
  1977. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  1978. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1979. },
  1980. usesZeroToOneRange: true
  1981. };
  1982. return DeviceRgbCS;
  1983. })();
  1984. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  1985. // The coefficients below was found using numerical analysis: the method of
  1986. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  1987. // where color_value is the tabular value from the table of sampled RGB colors
  1988. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  1989. // CMYK color conversion using the estimation below:
  1990. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  1991. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  1992. var c = src[srcOffset + 0] * srcScale;
  1993. var m = src[srcOffset + 1] * srcScale;
  1994. var y = src[srcOffset + 2] * srcScale;
  1995. var k = src[srcOffset + 3] * srcScale;
  1996. var r =
  1997. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  1998. 18.82290502165302 * y + 212.25662451639585 * k +
  1999. -285.2331026137004) +
  2000. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  2001. -17.873870861415444 * k - 5.497006427196366) +
  2002. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  2003. 17.5119270841813) +
  2004. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  2005. var g =
  2006. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  2007. 6.871425592049007 * y + 31.159100130055922 * k +
  2008. -79.2970844816548) +
  2009. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  2010. 131.35250912493976 * k - 190.9453302588951) +
  2011. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  2012. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  2013. var b =
  2014. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  2015. 30.89978309703729 * y - 0.23883238689178934 * k +
  2016. -14.183576799673286) +
  2017. m * (10.49593273432072 * m + 63.02378494754052 * y +
  2018. 50.606957656360734 * k - 112.23884253719248) +
  2019. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  2020. -193.58209356861505) +
  2021. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  2022. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  2023. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  2024. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  2025. }
  2026. function DeviceCmykCS() {
  2027. this.name = 'DeviceCMYK';
  2028. this.numComps = 4;
  2029. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  2030. }
  2031. DeviceCmykCS.prototype = {
  2032. getRgb: ColorSpace.prototype.getRgb,
  2033. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  2034. dest, destOffset) {
  2035. convertToRgb(src, srcOffset, 1, dest, destOffset);
  2036. },
  2037. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  2038. dest, destOffset, bits,
  2039. alpha01) {
  2040. var scale = 1 / ((1 << bits) - 1);
  2041. for (var i = 0; i < count; i++) {
  2042. convertToRgb(src, srcOffset, scale, dest, destOffset);
  2043. srcOffset += 4;
  2044. destOffset += 3 + alpha01;
  2045. }
  2046. },
  2047. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  2048. alpha01) {
  2049. return (inputLength / 4 * (3 + alpha01)) | 0;
  2050. },
  2051. isPassthrough: ColorSpace.prototype.isPassthrough,
  2052. fillRgb: ColorSpace.prototype.fillRgb,
  2053. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  2054. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  2055. },
  2056. usesZeroToOneRange: true
  2057. };
  2058. return DeviceCmykCS;
  2059. })();
  2060. //
  2061. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  2062. //
  2063. var CalGrayCS = (function CalGrayCSClosure() {
  2064. function CalGrayCS(whitePoint, blackPoint, gamma) {
  2065. this.name = 'CalGray';
  2066. this.numComps = 1;
  2067. this.defaultColor = new Float32Array([0]);
  2068. if (!whitePoint) {
  2069. error('WhitePoint missing - required for color space CalGray');
  2070. }
  2071. blackPoint = blackPoint || [0, 0, 0];
  2072. gamma = gamma || 1;
  2073. // Translate arguments to spec variables.
  2074. this.XW = whitePoint[0];
  2075. this.YW = whitePoint[1];
  2076. this.ZW = whitePoint[2];
  2077. this.XB = blackPoint[0];
  2078. this.YB = blackPoint[1];
  2079. this.ZB = blackPoint[2];
  2080. this.G = gamma;
  2081. // Validate variables as per spec.
  2082. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  2083. error('Invalid WhitePoint components for ' + this.name +
  2084. ', no fallback available');
  2085. }
  2086. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  2087. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  2088. this.XB = this.YB = this.ZB = 0;
  2089. }
  2090. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  2091. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  2092. ', ZB: ' + this.ZB + ', only default values are supported.');
  2093. }
  2094. if (this.G < 1) {
  2095. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  2096. ', falling back to default');
  2097. this.G = 1;
  2098. }
  2099. }
  2100. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  2101. // A represents a gray component of a calibrated gray space.
  2102. // A <---> AG in the spec
  2103. var A = src[srcOffset] * scale;
  2104. var AG = Math.pow(A, cs.G);
  2105. // Computes L as per spec. ( = cs.YW * AG )
  2106. // Except if other than default BlackPoint values are used.
  2107. var L = cs.YW * AG;
  2108. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  2109. // Convert values to rgb range [0, 255].
  2110. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  2111. dest[destOffset] = val;
  2112. dest[destOffset + 1] = val;
  2113. dest[destOffset + 2] = val;
  2114. }
  2115. CalGrayCS.prototype = {
  2116. getRgb: ColorSpace.prototype.getRgb,
  2117. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  2118. dest, destOffset) {
  2119. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  2120. },
  2121. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  2122. dest, destOffset, bits,
  2123. alpha01) {
  2124. var scale = 1 / ((1 << bits) - 1);
  2125. for (var i = 0; i < count; ++i) {
  2126. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  2127. srcOffset += 1;
  2128. destOffset += 3 + alpha01;
  2129. }
  2130. },
  2131. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  2132. return inputLength * (3 + alpha01);
  2133. },
  2134. isPassthrough: ColorSpace.prototype.isPassthrough,
  2135. fillRgb: ColorSpace.prototype.fillRgb,
  2136. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  2137. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  2138. },
  2139. usesZeroToOneRange: true
  2140. };
  2141. return CalGrayCS;
  2142. })();
  2143. //
  2144. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  2145. //
  2146. var LabCS = (function LabCSClosure() {
  2147. function LabCS(whitePoint, blackPoint, range) {
  2148. this.name = 'Lab';
  2149. this.numComps = 3;
  2150. this.defaultColor = new Float32Array([0, 0, 0]);
  2151. if (!whitePoint) {
  2152. error('WhitePoint missing - required for color space Lab');
  2153. }
  2154. blackPoint = blackPoint || [0, 0, 0];
  2155. range = range || [-100, 100, -100, 100];
  2156. // Translate args to spec variables
  2157. this.XW = whitePoint[0];
  2158. this.YW = whitePoint[1];
  2159. this.ZW = whitePoint[2];
  2160. this.amin = range[0];
  2161. this.amax = range[1];
  2162. this.bmin = range[2];
  2163. this.bmax = range[3];
  2164. // These are here just for completeness - the spec doesn't offer any
  2165. // formulas that use BlackPoint in Lab
  2166. this.XB = blackPoint[0];
  2167. this.YB = blackPoint[1];
  2168. this.ZB = blackPoint[2];
  2169. // Validate vars as per spec
  2170. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  2171. error('Invalid WhitePoint components, no fallback available');
  2172. }
  2173. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  2174. info('Invalid BlackPoint, falling back to default');
  2175. this.XB = this.YB = this.ZB = 0;
  2176. }
  2177. if (this.amin > this.amax || this.bmin > this.bmax) {
  2178. info('Invalid Range, falling back to defaults');
  2179. this.amin = -100;
  2180. this.amax = 100;
  2181. this.bmin = -100;
  2182. this.bmax = 100;
  2183. }
  2184. }
  2185. // Function g(x) from spec
  2186. function fn_g(x) {
  2187. if (x >= 6 / 29) {
  2188. return x * x * x;
  2189. } else {
  2190. return (108 / 841) * (x - 4 / 29);
  2191. }
  2192. }
  2193. function decode(value, high1, low2, high2) {
  2194. return low2 + (value) * (high2 - low2) / (high1);
  2195. }
  2196. // If decoding is needed maxVal should be 2^bits per component - 1.
  2197. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  2198. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  2199. // not the usual [0, 1]. If a command like setFillColor is used the src
  2200. // values will already be within the correct range. However, if we are
  2201. // converting an image we have to map the values to the correct range given
  2202. // above.
  2203. // Ls,as,bs <---> L*,a*,b* in the spec
  2204. var Ls = src[srcOffset];
  2205. var as = src[srcOffset + 1];
  2206. var bs = src[srcOffset + 2];
  2207. if (maxVal !== false) {
  2208. Ls = decode(Ls, maxVal, 0, 100);
  2209. as = decode(as, maxVal, cs.amin, cs.amax);
  2210. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  2211. }
  2212. // Adjust limits of 'as' and 'bs'
  2213. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  2214. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  2215. // Computes intermediate variables X,Y,Z as per spec
  2216. var M = (Ls + 16) / 116;
  2217. var L = M + (as / 500);
  2218. var N = M - (bs / 200);
  2219. var X = cs.XW * fn_g(L);
  2220. var Y = cs.YW * fn_g(M);
  2221. var Z = cs.ZW * fn_g(N);
  2222. var r, g, b;
  2223. // Using different conversions for D50 and D65 white points,
  2224. // per http://www.color.org/srgb.pdf
  2225. if (cs.ZW < 1) {
  2226. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  2227. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  2228. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  2229. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  2230. } else {
  2231. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  2232. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  2233. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  2234. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  2235. }
  2236. // clamp color values to [0,1] range then convert to [0,255] range.
  2237. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  2238. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  2239. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  2240. }
  2241. LabCS.prototype = {
  2242. getRgb: ColorSpace.prototype.getRgb,
  2243. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  2244. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  2245. },
  2246. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  2247. dest, destOffset, bits,
  2248. alpha01) {
  2249. var maxVal = (1 << bits) - 1;
  2250. for (var i = 0; i < count; i++) {
  2251. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  2252. srcOffset += 3;
  2253. destOffset += 3 + alpha01;
  2254. }
  2255. },
  2256. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  2257. return (inputLength * (3 + alpha01) / 3) | 0;
  2258. },
  2259. isPassthrough: ColorSpace.prototype.isPassthrough,
  2260. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  2261. // XXX: Decoding is handled with the lab conversion because of the strange
  2262. // ranges that are used.
  2263. return true;
  2264. },
  2265. usesZeroToOneRange: false
  2266. };
  2267. return LabCS;
  2268. })();
  2269. var PDFFunction = (function PDFFunctionClosure() {
  2270. var CONSTRUCT_SAMPLED = 0;
  2271. var CONSTRUCT_INTERPOLATED = 2;
  2272. var CONSTRUCT_STICHED = 3;
  2273. var CONSTRUCT_POSTSCRIPT = 4;
  2274. return {
  2275. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  2276. str) {
  2277. var i, ii;
  2278. var length = 1;
  2279. for (i = 0, ii = size.length; i < ii; i++) {
  2280. length *= size[i];
  2281. }
  2282. length *= outputSize;
  2283. var array = [];
  2284. var codeSize = 0;
  2285. var codeBuf = 0;
  2286. // 32 is a valid bps so shifting won't work
  2287. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  2288. var strBytes = str.getBytes((length * bps + 7) / 8);
  2289. var strIdx = 0;
  2290. for (i = 0; i < length; i++) {
  2291. while (codeSize < bps) {
  2292. codeBuf <<= 8;
  2293. codeBuf |= strBytes[strIdx++];
  2294. codeSize += 8;
  2295. }
  2296. codeSize -= bps;
  2297. array.push((codeBuf >> codeSize) * sampleMul);
  2298. codeBuf &= (1 << codeSize) - 1;
  2299. }
  2300. return array;
  2301. },
  2302. getIR: function PDFFunction_getIR(xref, fn) {
  2303. var dict = fn.dict;
  2304. if (!dict) {
  2305. dict = fn;
  2306. }
  2307. var types = [this.constructSampled,
  2308. null,
  2309. this.constructInterpolated,
  2310. this.constructStiched,
  2311. this.constructPostScript];
  2312. var typeNum = dict.get('FunctionType');
  2313. var typeFn = types[typeNum];
  2314. if (!typeFn) {
  2315. error('Unknown type of function');
  2316. }
  2317. return typeFn.call(this, fn, dict, xref);
  2318. },
  2319. fromIR: function PDFFunction_fromIR(IR) {
  2320. var type = IR[0];
  2321. switch (type) {
  2322. case CONSTRUCT_SAMPLED:
  2323. return this.constructSampledFromIR(IR);
  2324. case CONSTRUCT_INTERPOLATED:
  2325. return this.constructInterpolatedFromIR(IR);
  2326. case CONSTRUCT_STICHED:
  2327. return this.constructStichedFromIR(IR);
  2328. //case CONSTRUCT_POSTSCRIPT:
  2329. default:
  2330. return this.constructPostScriptFromIR(IR);
  2331. }
  2332. },
  2333. parse: function PDFFunction_parse(xref, fn) {
  2334. var IR = this.getIR(xref, fn);
  2335. return this.fromIR(IR);
  2336. },
  2337. constructSampled: function PDFFunction_constructSampled(str, dict) {
  2338. function toMultiArray(arr) {
  2339. var inputLength = arr.length;
  2340. var out = [];
  2341. var index = 0;
  2342. for (var i = 0; i < inputLength; i += 2) {
  2343. out[index] = [arr[i], arr[i + 1]];
  2344. ++index;
  2345. }
  2346. return out;
  2347. }
  2348. var domain = dict.get('Domain');
  2349. var range = dict.get('Range');
  2350. if (!domain || !range) {
  2351. error('No domain or range');
  2352. }
  2353. var inputSize = domain.length / 2;
  2354. var outputSize = range.length / 2;
  2355. domain = toMultiArray(domain);
  2356. range = toMultiArray(range);
  2357. var size = dict.get('Size');
  2358. var bps = dict.get('BitsPerSample');
  2359. var order = dict.get('Order') || 1;
  2360. if (order !== 1) {
  2361. // No description how cubic spline interpolation works in PDF32000:2008
  2362. // As in poppler, ignoring order, linear interpolation may work as good
  2363. info('No support for cubic spline interpolation: ' + order);
  2364. }
  2365. var encode = dict.get('Encode');
  2366. if (!encode) {
  2367. encode = [];
  2368. for (var i = 0; i < inputSize; ++i) {
  2369. encode.push(0);
  2370. encode.push(size[i] - 1);
  2371. }
  2372. }
  2373. encode = toMultiArray(encode);
  2374. var decode = dict.get('Decode');
  2375. if (!decode) {
  2376. decode = range;
  2377. } else {
  2378. decode = toMultiArray(decode);
  2379. }
  2380. var samples = this.getSampleArray(size, outputSize, bps, str);
  2381. return [
  2382. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  2383. outputSize, Math.pow(2, bps) - 1, range
  2384. ];
  2385. },
  2386. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  2387. // See chapter 3, page 109 of the PDF reference
  2388. function interpolate(x, xmin, xmax, ymin, ymax) {
  2389. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  2390. }
  2391. return function constructSampledFromIRResult(args) {
  2392. // See chapter 3, page 110 of the PDF reference.
  2393. var m = IR[1];
  2394. var domain = IR[2];
  2395. var encode = IR[3];
  2396. var decode = IR[4];
  2397. var samples = IR[5];
  2398. var size = IR[6];
  2399. var n = IR[7];
  2400. //var mask = IR[8];
  2401. var range = IR[9];
  2402. if (m != args.length) {
  2403. error('Incorrect number of arguments: ' + m + ' != ' +
  2404. args.length);
  2405. }
  2406. var x = args;
  2407. // Building the cube vertices: its part and sample index
  2408. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  2409. var cubeVertices = 1 << m;
  2410. var cubeN = new Float64Array(cubeVertices);
  2411. var cubeVertex = new Uint32Array(cubeVertices);
  2412. var i, j;
  2413. for (j = 0; j < cubeVertices; j++) {
  2414. cubeN[j] = 1;
  2415. }
  2416. var k = n, pos = 1;
  2417. // Map x_i to y_j for 0 <= i < m using the sampled function.
  2418. for (i = 0; i < m; ++i) {
  2419. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  2420. var domain_2i = domain[i][0];
  2421. var domain_2i_1 = domain[i][1];
  2422. var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);
  2423. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  2424. // Encode_2i, Encode_2i+1)
  2425. var e = interpolate(xi, domain_2i, domain_2i_1,
  2426. encode[i][0], encode[i][1]);
  2427. // e_i' = min(max(e_i, 0), Size_i - 1)
  2428. var size_i = size[i];
  2429. e = Math.min(Math.max(e, 0), size_i - 1);
  2430. // Adjusting the cube: N and vertex sample index
  2431. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  2432. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  2433. var n1 = e - e0; // (e - e0) / (e1 - e0);
  2434. var offset0 = e0 * k;
  2435. var offset1 = offset0 + k; // e1 * k
  2436. for (j = 0; j < cubeVertices; j++) {
  2437. if (j & pos) {
  2438. cubeN[j] *= n1;
  2439. cubeVertex[j] += offset1;
  2440. } else {
  2441. cubeN[j] *= n0;
  2442. cubeVertex[j] += offset0;
  2443. }
  2444. }
  2445. k *= size_i;
  2446. pos <<= 1;
  2447. }
  2448. var y = new Float64Array(n);
  2449. for (j = 0; j < n; ++j) {
  2450. // Sum all cube vertices' samples portions
  2451. var rj = 0;
  2452. for (i = 0; i < cubeVertices; i++) {
  2453. rj += samples[cubeVertex[i] + j] * cubeN[i];
  2454. }
  2455. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  2456. // Decode_2j, Decode_2j+1)
  2457. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  2458. // y_j = min(max(r_j, range_2j), range_2j+1)
  2459. y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  2460. }
  2461. return y;
  2462. };
  2463. },
  2464. constructInterpolated: function PDFFunction_constructInterpolated(str,
  2465. dict) {
  2466. var c0 = dict.get('C0') || [0];
  2467. var c1 = dict.get('C1') || [1];
  2468. var n = dict.get('N');
  2469. if (!isArray(c0) || !isArray(c1)) {
  2470. error('Illegal dictionary for interpolated function');
  2471. }
  2472. var length = c0.length;
  2473. var diff = [];
  2474. for (var i = 0; i < length; ++i) {
  2475. diff.push(c1[i] - c0[i]);
  2476. }
  2477. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  2478. },
  2479. constructInterpolatedFromIR:
  2480. function PDFFunction_constructInterpolatedFromIR(IR) {
  2481. var c0 = IR[1];
  2482. var diff = IR[2];
  2483. var n = IR[3];
  2484. var length = diff.length;
  2485. return function constructInterpolatedFromIRResult(args) {
  2486. var x = n == 1 ? args[0] : Math.pow(args[0], n);
  2487. var out = [];
  2488. for (var j = 0; j < length; ++j) {
  2489. out.push(c0[j] + (x * diff[j]));
  2490. }
  2491. return out;
  2492. };
  2493. },
  2494. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  2495. var domain = dict.get('Domain');
  2496. if (!domain) {
  2497. error('No domain');
  2498. }
  2499. var inputSize = domain.length / 2;
  2500. if (inputSize != 1) {
  2501. error('Bad domain for stiched function');
  2502. }
  2503. var fnRefs = dict.get('Functions');
  2504. var fns = [];
  2505. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  2506. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  2507. }
  2508. var bounds = dict.get('Bounds');
  2509. var encode = dict.get('Encode');
  2510. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  2511. },
  2512. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  2513. var domain = IR[1];
  2514. var bounds = IR[2];
  2515. var encode = IR[3];
  2516. var fnsIR = IR[4];
  2517. var fns = [];
  2518. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  2519. fns.push(PDFFunction.fromIR(fnsIR[i]));
  2520. }
  2521. return function constructStichedFromIRResult(args) {
  2522. var clip = function constructStichedFromIRClip(v, min, max) {
  2523. if (v > max) {
  2524. v = max;
  2525. } else if (v < min) {
  2526. v = min;
  2527. }
  2528. return v;
  2529. };
  2530. // clip to domain
  2531. var v = clip(args[0], domain[0], domain[1]);
  2532. // calulate which bound the value is in
  2533. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  2534. if (v < bounds[i]) {
  2535. break;
  2536. }
  2537. }
  2538. // encode value into domain of function
  2539. var dmin = domain[0];
  2540. if (i > 0) {
  2541. dmin = bounds[i - 1];
  2542. }
  2543. var dmax = domain[1];
  2544. if (i < bounds.length) {
  2545. dmax = bounds[i];
  2546. }
  2547. var rmin = encode[2 * i];
  2548. var rmax = encode[2 * i + 1];
  2549. var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  2550. // call the appropriate function
  2551. return fns[i]([v2]);
  2552. };
  2553. },
  2554. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  2555. xref) {
  2556. var domain = dict.get('Domain');
  2557. var range = dict.get('Range');
  2558. if (!domain) {
  2559. error('No domain.');
  2560. }
  2561. if (!range) {
  2562. error('No range.');
  2563. }
  2564. var lexer = new PostScriptLexer(fn);
  2565. var parser = new PostScriptParser(lexer);
  2566. var code = parser.parse();
  2567. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  2568. },
  2569. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  2570. IR) {
  2571. var domain = IR[1];
  2572. var range = IR[2];
  2573. var code = IR[3];
  2574. var numOutputs = range.length >> 1;
  2575. var numInputs = domain.length >> 1;
  2576. var evaluator = new PostScriptEvaluator(code);
  2577. // Cache the values for a big speed up, the cache size is limited though
  2578. // since the number of possible values can be huge from a PS function.
  2579. var cache = {};
  2580. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  2581. // seen in our tests.
  2582. var MAX_CACHE_SIZE = 2048 * 4;
  2583. var cache_available = MAX_CACHE_SIZE;
  2584. return function constructPostScriptFromIRResult(args) {
  2585. var i, value;
  2586. var key = '';
  2587. var input = new Array(numInputs);
  2588. for (i = 0; i < numInputs; i++) {
  2589. value = args[i];
  2590. input[i] = value;
  2591. key += value + '_';
  2592. }
  2593. var cachedValue = cache[key];
  2594. if (cachedValue !== undefined) {
  2595. return cachedValue;
  2596. }
  2597. var output = new Array(numOutputs);
  2598. var stack = evaluator.execute(input);
  2599. var stackIndex = stack.length - numOutputs;
  2600. for (i = 0; i < numOutputs; i++) {
  2601. value = stack[stackIndex + i];
  2602. var bound = range[i * 2];
  2603. if (value < bound) {
  2604. value = bound;
  2605. } else {
  2606. bound = range[i * 2 +1];
  2607. if (value > bound) {
  2608. value = bound;
  2609. }
  2610. }
  2611. output[i] = value;
  2612. }
  2613. if (cache_available > 0) {
  2614. cache_available--;
  2615. cache[key] = output;
  2616. }
  2617. return output;
  2618. };
  2619. }
  2620. };
  2621. })();
  2622. var PostScriptStack = (function PostScriptStackClosure() {
  2623. var MAX_STACK_SIZE = 100;
  2624. function PostScriptStack(initialStack) {
  2625. this.stack = initialStack || [];
  2626. }
  2627. PostScriptStack.prototype = {
  2628. push: function PostScriptStack_push(value) {
  2629. if (this.stack.length >= MAX_STACK_SIZE) {
  2630. error('PostScript function stack overflow.');
  2631. }
  2632. this.stack.push(value);
  2633. },
  2634. pop: function PostScriptStack_pop() {
  2635. if (this.stack.length <= 0) {
  2636. error('PostScript function stack underflow.');
  2637. }
  2638. return this.stack.pop();
  2639. },
  2640. copy: function PostScriptStack_copy(n) {
  2641. if (this.stack.length + n >= MAX_STACK_SIZE) {
  2642. error('PostScript function stack overflow.');
  2643. }
  2644. var stack = this.stack;
  2645. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  2646. stack.push(stack[i]);
  2647. }
  2648. },
  2649. index: function PostScriptStack_index(n) {
  2650. this.push(this.stack[this.stack.length - n - 1]);
  2651. },
  2652. // rotate the last n stack elements p times
  2653. roll: function PostScriptStack_roll(n, p) {
  2654. var stack = this.stack;
  2655. var l = stack.length - n;
  2656. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  2657. for (i = l, j = r; i < j; i++, j--) {
  2658. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2659. }
  2660. for (i = l, j = c - 1; i < j; i++, j--) {
  2661. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2662. }
  2663. for (i = c, j = r; i < j; i++, j--) {
  2664. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2665. }
  2666. }
  2667. };
  2668. return PostScriptStack;
  2669. })();
  2670. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  2671. function PostScriptEvaluator(operators) {
  2672. this.operators = operators;
  2673. }
  2674. PostScriptEvaluator.prototype = {
  2675. execute: function PostScriptEvaluator_execute(initialStack) {
  2676. var stack = new PostScriptStack(initialStack);
  2677. var counter = 0;
  2678. var operators = this.operators;
  2679. var length = operators.length;
  2680. var operator, a, b;
  2681. while (counter < length) {
  2682. operator = operators[counter++];
  2683. if (typeof operator == 'number') {
  2684. // Operator is really an operand and should be pushed to the stack.
  2685. stack.push(operator);
  2686. continue;
  2687. }
  2688. switch (operator) {
  2689. // non standard ps operators
  2690. case 'jz': // jump if false
  2691. b = stack.pop();
  2692. a = stack.pop();
  2693. if (!a) {
  2694. counter = b;
  2695. }
  2696. break;
  2697. case 'j': // jump
  2698. a = stack.pop();
  2699. counter = a;
  2700. break;
  2701. // all ps operators in alphabetical order (excluding if/ifelse)
  2702. case 'abs':
  2703. a = stack.pop();
  2704. stack.push(Math.abs(a));
  2705. break;
  2706. case 'add':
  2707. b = stack.pop();
  2708. a = stack.pop();
  2709. stack.push(a + b);
  2710. break;
  2711. case 'and':
  2712. b = stack.pop();
  2713. a = stack.pop();
  2714. if (isBool(a) && isBool(b)) {
  2715. stack.push(a && b);
  2716. } else {
  2717. stack.push(a & b);
  2718. }
  2719. break;
  2720. case 'atan':
  2721. a = stack.pop();
  2722. stack.push(Math.atan(a));
  2723. break;
  2724. case 'bitshift':
  2725. b = stack.pop();
  2726. a = stack.pop();
  2727. if (a > 0) {
  2728. stack.push(a << b);
  2729. } else {
  2730. stack.push(a >> b);
  2731. }
  2732. break;
  2733. case 'ceiling':
  2734. a = stack.pop();
  2735. stack.push(Math.ceil(a));
  2736. break;
  2737. case 'copy':
  2738. a = stack.pop();
  2739. stack.copy(a);
  2740. break;
  2741. case 'cos':
  2742. a = stack.pop();
  2743. stack.push(Math.cos(a));
  2744. break;
  2745. case 'cvi':
  2746. a = stack.pop() | 0;
  2747. stack.push(a);
  2748. break;
  2749. case 'cvr':
  2750. // noop
  2751. break;
  2752. case 'div':
  2753. b = stack.pop();
  2754. a = stack.pop();
  2755. stack.push(a / b);
  2756. break;
  2757. case 'dup':
  2758. stack.copy(1);
  2759. break;
  2760. case 'eq':
  2761. b = stack.pop();
  2762. a = stack.pop();
  2763. stack.push(a == b);
  2764. break;
  2765. case 'exch':
  2766. stack.roll(2, 1);
  2767. break;
  2768. case 'exp':
  2769. b = stack.pop();
  2770. a = stack.pop();
  2771. stack.push(Math.pow(a, b));
  2772. break;
  2773. case 'false':
  2774. stack.push(false);
  2775. break;
  2776. case 'floor':
  2777. a = stack.pop();
  2778. stack.push(Math.floor(a));
  2779. break;
  2780. case 'ge':
  2781. b = stack.pop();
  2782. a = stack.pop();
  2783. stack.push(a >= b);
  2784. break;
  2785. case 'gt':
  2786. b = stack.pop();
  2787. a = stack.pop();
  2788. stack.push(a > b);
  2789. break;
  2790. case 'idiv':
  2791. b = stack.pop();
  2792. a = stack.pop();
  2793. stack.push((a / b) | 0);
  2794. break;
  2795. case 'index':
  2796. a = stack.pop();
  2797. stack.index(a);
  2798. break;
  2799. case 'le':
  2800. b = stack.pop();
  2801. a = stack.pop();
  2802. stack.push(a <= b);
  2803. break;
  2804. case 'ln':
  2805. a = stack.pop();
  2806. stack.push(Math.log(a));
  2807. break;
  2808. case 'log':
  2809. a = stack.pop();
  2810. stack.push(Math.log(a) / Math.LN10);
  2811. break;
  2812. case 'lt':
  2813. b = stack.pop();
  2814. a = stack.pop();
  2815. stack.push(a < b);
  2816. break;
  2817. case 'mod':
  2818. b = stack.pop();
  2819. a = stack.pop();
  2820. stack.push(a % b);
  2821. break;
  2822. case 'mul':
  2823. b = stack.pop();
  2824. a = stack.pop();
  2825. stack.push(a * b);
  2826. break;
  2827. case 'ne':
  2828. b = stack.pop();
  2829. a = stack.pop();
  2830. stack.push(a != b);
  2831. break;
  2832. case 'neg':
  2833. a = stack.pop();
  2834. stack.push(-a);
  2835. break;
  2836. case 'not':
  2837. a = stack.pop();
  2838. if (isBool(a)) {
  2839. stack.push(!a);
  2840. } else {
  2841. stack.push(~a);
  2842. }
  2843. break;
  2844. case 'or':
  2845. b = stack.pop();
  2846. a = stack.pop();
  2847. if (isBool(a) && isBool(b)) {
  2848. stack.push(a || b);
  2849. } else {
  2850. stack.push(a | b);
  2851. }
  2852. break;
  2853. case 'pop':
  2854. stack.pop();
  2855. break;
  2856. case 'roll':
  2857. b = stack.pop();
  2858. a = stack.pop();
  2859. stack.roll(a, b);
  2860. break;
  2861. case 'round':
  2862. a = stack.pop();
  2863. stack.push(Math.round(a));
  2864. break;
  2865. case 'sin':
  2866. a = stack.pop();
  2867. stack.push(Math.sin(a));
  2868. break;
  2869. case 'sqrt':
  2870. a = stack.pop();
  2871. stack.push(Math.sqrt(a));
  2872. break;
  2873. case 'sub':
  2874. b = stack.pop();
  2875. a = stack.pop();
  2876. stack.push(a - b);
  2877. break;
  2878. case 'true':
  2879. stack.push(true);
  2880. break;
  2881. case 'truncate':
  2882. a = stack.pop();
  2883. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  2884. stack.push(a);
  2885. break;
  2886. case 'xor':
  2887. b = stack.pop();
  2888. a = stack.pop();
  2889. if (isBool(a) && isBool(b)) {
  2890. stack.push(a != b);
  2891. } else {
  2892. stack.push(a ^ b);
  2893. }
  2894. break;
  2895. default:
  2896. error('Unknown operator ' + operator);
  2897. break;
  2898. }
  2899. }
  2900. return stack.stack;
  2901. }
  2902. };
  2903. return PostScriptEvaluator;
  2904. })();
  2905. var DEFAULT_ICON_SIZE = 22; // px
  2906. var HIGHLIGHT_OFFSET = 4; // px
  2907. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  2908. var Annotation = (function AnnotationClosure() {
  2909. // 12.5.5: Algorithm: Appearance streams
  2910. function getTransformMatrix(rect, bbox, matrix) {
  2911. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  2912. var minX = bounds[0];
  2913. var minY = bounds[1];
  2914. var maxX = bounds[2];
  2915. var maxY = bounds[3];
  2916. if (minX === maxX || minY === maxY) {
  2917. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  2918. // just apply the transform for rect
  2919. return [1, 0, 0, 1, rect[0], rect[1]];
  2920. }
  2921. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  2922. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  2923. return [
  2924. xRatio,
  2925. 0,
  2926. 0,
  2927. yRatio,
  2928. rect[0] - minX * xRatio,
  2929. rect[1] - minY * yRatio
  2930. ];
  2931. }
  2932. function getDefaultAppearance(dict) {
  2933. var appearanceState = dict.get('AP');
  2934. if (!isDict(appearanceState)) {
  2935. return;
  2936. }
  2937. var appearance;
  2938. var appearances = appearanceState.get('N');
  2939. if (isDict(appearances)) {
  2940. var as = dict.get('AS');
  2941. if (as && appearances.has(as.name)) {
  2942. appearance = appearances.get(as.name);
  2943. }
  2944. } else {
  2945. appearance = appearances;
  2946. }
  2947. return appearance;
  2948. }
  2949. function Annotation(params) {
  2950. if (params.data) {
  2951. this.data = params.data;
  2952. return;
  2953. }
  2954. var dict = params.dict;
  2955. var data = this.data = {};
  2956. data.subtype = dict.get('Subtype').name;
  2957. var rect = dict.get('Rect') || [0, 0, 0, 0];
  2958. data.rect = Util.normalizeRect(rect);
  2959. data.annotationFlags = dict.get('F');
  2960. var color = dict.get('C');
  2961. if (isArray(color) && color.length === 3) {
  2962. // TODO(mack): currently only supporting rgb; need support different
  2963. // colorspaces
  2964. data.color = color;
  2965. } else {
  2966. data.color = [0, 0, 0];
  2967. }
  2968. // Some types of annotations have border style dict which has more
  2969. // info than the border array
  2970. if (dict.has('BS')) {
  2971. var borderStyle = dict.get('BS');
  2972. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  2973. } else {
  2974. var borderArray = dict.get('Border') || [0, 0, 1];
  2975. data.borderWidth = borderArray[2] || 0;
  2976. // TODO: implement proper support for annotations with line dash patterns.
  2977. var dashArray = borderArray[3];
  2978. if (data.borderWidth > 0 && dashArray) {
  2979. if (!isArray(dashArray)) {
  2980. // Ignore the border if dashArray is not actually an array,
  2981. // this is consistent with the behaviour in Adobe Reader.
  2982. data.borderWidth = 0;
  2983. } else {
  2984. var dashArrayLength = dashArray.length;
  2985. if (dashArrayLength > 0) {
  2986. // According to the PDF specification: the elements in a dashArray
  2987. // shall be numbers that are nonnegative and not all equal to zero.
  2988. var isInvalid = false;
  2989. var numPositive = 0;
  2990. for (var i = 0; i < dashArrayLength; i++) {
  2991. var validNumber = (+dashArray[i] >= 0);
  2992. if (!validNumber) {
  2993. isInvalid = true;
  2994. break;
  2995. } else if (dashArray[i] > 0) {
  2996. numPositive++;
  2997. }
  2998. }
  2999. if (isInvalid || numPositive === 0) {
  3000. data.borderWidth = 0;
  3001. }
  3002. }
  3003. }
  3004. }
  3005. }
  3006. this.appearance = getDefaultAppearance(dict);
  3007. data.hasAppearance = !!this.appearance;
  3008. data.id = params.ref.num;
  3009. }
  3010. Annotation.prototype = {
  3011. getData: function Annotation_getData() {
  3012. return this.data;
  3013. },
  3014. hasHtml: function Annotation_hasHtml() {
  3015. return false;
  3016. },
  3017. getHtmlElement: function Annotation_getHtmlElement(commonObjs) {
  3018. throw new NotImplementedException(
  3019. 'getHtmlElement() should be implemented in subclass');
  3020. },
  3021. // TODO(mack): Remove this, it's not really that helpful.
  3022. getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect,
  3023. borderWidth) {
  3024. assert(!isWorker,
  3025. 'getEmptyContainer() should be called from main thread');
  3026. var bWidth = borderWidth || 0;
  3027. rect = rect || this.data.rect;
  3028. var element = document.createElement(tagName);
  3029. element.style.borderWidth = bWidth + 'px';
  3030. var width = rect[2] - rect[0] - 2 * bWidth;
  3031. var height = rect[3] - rect[1] - 2 * bWidth;
  3032. element.style.width = width + 'px';
  3033. element.style.height = height + 'px';
  3034. return element;
  3035. },
  3036. isInvisible: function Annotation_isInvisible() {
  3037. var data = this.data;
  3038. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  3039. return false;
  3040. } else {
  3041. return !!(data &&
  3042. data.annotationFlags && // Default: not invisible
  3043. data.annotationFlags & 0x1); // Invisible
  3044. }
  3045. },
  3046. isViewable: function Annotation_isViewable() {
  3047. var data = this.data;
  3048. return !!(!this.isInvisible() &&
  3049. data &&
  3050. (!data.annotationFlags ||
  3051. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  3052. data.rect); // rectangle is nessessary
  3053. },
  3054. isPrintable: function Annotation_isPrintable() {
  3055. var data = this.data;
  3056. return !!(!this.isInvisible() &&
  3057. data &&
  3058. data.annotationFlags && // Default: not printable
  3059. data.annotationFlags & 0x4 && // Print
  3060. data.rect); // rectangle is nessessary
  3061. },
  3062. loadResources: function Annotation_loadResources(keys) {
  3063. return new Promise(function (resolve, reject) {
  3064. this.appearance.dict.getAsync('Resources').then(function (resources) {
  3065. if (!resources) {
  3066. resolve();
  3067. return;
  3068. }
  3069. var objectLoader = new ObjectLoader(resources.map,
  3070. keys,
  3071. resources.xref);
  3072. objectLoader.load().then(function() {
  3073. resolve(resources);
  3074. }, reject);
  3075. }, reject);
  3076. }.bind(this));
  3077. },
  3078. getOperatorList: function Annotation_getOperatorList(evaluator) {
  3079. if (!this.appearance) {
  3080. return Promise.resolve(new OperatorList());
  3081. }
  3082. var data = this.data;
  3083. var appearanceDict = this.appearance.dict;
  3084. var resourcesPromise = this.loadResources([
  3085. 'ExtGState',
  3086. 'ColorSpace',
  3087. 'Pattern',
  3088. 'Shading',
  3089. 'XObject',
  3090. 'Font'
  3091. // ProcSet
  3092. // Properties
  3093. ]);
  3094. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  3095. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  3096. var transform = getTransformMatrix(data.rect, bbox, matrix);
  3097. var self = this;
  3098. return resourcesPromise.then(function(resources) {
  3099. var opList = new OperatorList();
  3100. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  3101. return evaluator.getOperatorList(self.appearance, resources, opList).
  3102. then(function () {
  3103. opList.addOp(OPS.endAnnotation, []);
  3104. self.appearance.reset();
  3105. return opList;
  3106. });
  3107. });
  3108. }
  3109. };
  3110. Annotation.getConstructor =
  3111. function Annotation_getConstructor(subtype, fieldType) {
  3112. if (!subtype) {
  3113. return;
  3114. }
  3115. // TODO(mack): Implement FreeText annotations
  3116. if (subtype === 'Link') {
  3117. return LinkAnnotation;
  3118. } else if (subtype === 'Text') {
  3119. return TextAnnotation;
  3120. } else if (subtype === 'Widget') {
  3121. if (!fieldType) {
  3122. return;
  3123. }
  3124. if (fieldType === 'Tx') {
  3125. return TextWidgetAnnotation;
  3126. } else {
  3127. return WidgetAnnotation;
  3128. }
  3129. } else {
  3130. return Annotation;
  3131. }
  3132. };
  3133. // TODO(mack): Support loading annotation from data
  3134. Annotation.fromData = function Annotation_fromData(data) {
  3135. var subtype = data.subtype;
  3136. var fieldType = data.fieldType;
  3137. var Constructor = Annotation.getConstructor(subtype, fieldType);
  3138. if (Constructor) {
  3139. return new Constructor({ data: data });
  3140. }
  3141. };
  3142. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  3143. var dict = xref.fetchIfRef(ref);
  3144. if (!isDict(dict)) {
  3145. return;
  3146. }
  3147. var subtype = dict.get('Subtype');
  3148. subtype = isName(subtype) ? subtype.name : '';
  3149. if (!subtype) {
  3150. return;
  3151. }
  3152. var fieldType = Util.getInheritableProperty(dict, 'FT');
  3153. fieldType = isName(fieldType) ? fieldType.name : '';
  3154. var Constructor = Annotation.getConstructor(subtype, fieldType);
  3155. if (!Constructor) {
  3156. return;
  3157. }
  3158. var params = {
  3159. dict: dict,
  3160. ref: ref,
  3161. };
  3162. var annotation = new Constructor(params);
  3163. if (annotation.isViewable() || annotation.isPrintable()) {
  3164. return annotation;
  3165. } else {
  3166. warn('unimplemented annotation type: ' + subtype);
  3167. }
  3168. };
  3169. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  3170. annotations, opList, pdfManager, partialEvaluator, intent) {
  3171. function reject(e) {
  3172. annotationsReadyCapability.reject(e);
  3173. }
  3174. var annotationsReadyCapability = createPromiseCapability();
  3175. var annotationPromises = [];
  3176. for (var i = 0, n = annotations.length; i < n; ++i) {
  3177. if (intent === 'display' && annotations[i].isViewable() ||
  3178. intent === 'print' && annotations[i].isPrintable()) {
  3179. annotationPromises.push(
  3180. annotations[i].getOperatorList(partialEvaluator));
  3181. }
  3182. }
  3183. Promise.all(annotationPromises).then(function(datas) {
  3184. opList.addOp(OPS.beginAnnotations, []);
  3185. for (var i = 0, n = datas.length; i < n; ++i) {
  3186. var annotOpList = datas[i];
  3187. opList.addOpList(annotOpList);
  3188. }
  3189. opList.addOp(OPS.endAnnotations, []);
  3190. annotationsReadyCapability.resolve();
  3191. }, reject);
  3192. return annotationsReadyCapability.promise;
  3193. };
  3194. return Annotation;
  3195. })();
  3196. PDFJS.Annotation = Annotation;
  3197. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  3198. function WidgetAnnotation(params) {
  3199. Annotation.call(this, params);
  3200. if (params.data) {
  3201. return;
  3202. }
  3203. var dict = params.dict;
  3204. var data = this.data;
  3205. data.fieldValue = stringToPDFString(
  3206. Util.getInheritableProperty(dict, 'V') || '');
  3207. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  3208. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  3209. var fieldType = Util.getInheritableProperty(dict, 'FT');
  3210. data.fieldType = isName(fieldType) ? fieldType.name : '';
  3211. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  3212. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  3213. // Building the full field name by collecting the field and
  3214. // its ancestors 'T' data and joining them using '.'.
  3215. var fieldName = [];
  3216. var namedItem = dict;
  3217. var ref = params.ref;
  3218. while (namedItem) {
  3219. var parent = namedItem.get('Parent');
  3220. var parentRef = namedItem.getRaw('Parent');
  3221. var name = namedItem.get('T');
  3222. if (name) {
  3223. fieldName.unshift(stringToPDFString(name));
  3224. } else {
  3225. // The field name is absent, that means more than one field
  3226. // with the same name may exist. Replacing the empty name
  3227. // with the '`' plus index in the parent's 'Kids' array.
  3228. // This is not in the PDF spec but necessary to id the
  3229. // the input controls.
  3230. var kids = parent.get('Kids');
  3231. var j, jj;
  3232. for (j = 0, jj = kids.length; j < jj; j++) {
  3233. var kidRef = kids[j];
  3234. if (kidRef.num == ref.num && kidRef.gen == ref.gen) {
  3235. break;
  3236. }
  3237. }
  3238. fieldName.unshift('`' + j);
  3239. }
  3240. namedItem = parent;
  3241. ref = parentRef;
  3242. }
  3243. data.fullName = fieldName.join('.');
  3244. }
  3245. var parent = Annotation.prototype;
  3246. Util.inherit(WidgetAnnotation, Annotation, {
  3247. isViewable: function WidgetAnnotation_isViewable() {
  3248. if (this.data.fieldType === 'Sig') {
  3249. warn('unimplemented annotation type: Widget signature');
  3250. return false;
  3251. }
  3252. return parent.isViewable.call(this);
  3253. }
  3254. });
  3255. return WidgetAnnotation;
  3256. })();
  3257. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  3258. function TextWidgetAnnotation(params) {
  3259. WidgetAnnotation.call(this, params);
  3260. if (params.data) {
  3261. return;
  3262. }
  3263. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  3264. }
  3265. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  3266. function setTextStyles(element, item, fontObj) {
  3267. var style = element.style;
  3268. style.fontSize = item.fontSize + 'px';
  3269. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  3270. if (!fontObj) {
  3271. return;
  3272. }
  3273. style.fontWeight = fontObj.black ?
  3274. (fontObj.bold ? 'bolder' : 'bold') :
  3275. (fontObj.bold ? 'bold' : 'normal');
  3276. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  3277. var fontName = fontObj.loadedName;
  3278. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  3279. // Use a reasonable default font if the font doesn't specify a fallback
  3280. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  3281. style.fontFamily = fontFamily + fallbackName;
  3282. }
  3283. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  3284. hasHtml: function TextWidgetAnnotation_hasHtml() {
  3285. return !this.data.hasAppearance && !!this.data.fieldValue;
  3286. },
  3287. getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {
  3288. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  3289. var item = this.data;
  3290. var element = this.getEmptyContainer('div');
  3291. element.style.display = 'table';
  3292. var content = document.createElement('div');
  3293. content.textContent = item.fieldValue;
  3294. var textAlignment = item.textAlignment;
  3295. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  3296. content.style.verticalAlign = 'middle';
  3297. content.style.display = 'table-cell';
  3298. var fontObj = item.fontRefName ?
  3299. commonObjs.getData(item.fontRefName) : null;
  3300. setTextStyles(content, item, fontObj);
  3301. element.appendChild(content);
  3302. return element;
  3303. },
  3304. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  3305. if (this.appearance) {
  3306. return Annotation.prototype.getOperatorList.call(this, evaluator);
  3307. }
  3308. var opList = new OperatorList();
  3309. var data = this.data;
  3310. // Even if there is an appearance stream, ignore it. This is the
  3311. // behaviour used by Adobe Reader.
  3312. if (!data.defaultAppearance) {
  3313. return Promise.resolve(opList);
  3314. }
  3315. var stream = new Stream(stringToBytes(data.defaultAppearance));
  3316. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  3317. then(function () {
  3318. return opList;
  3319. });
  3320. }
  3321. });
  3322. return TextWidgetAnnotation;
  3323. })();
  3324. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  3325. function InteractiveAnnotation(params) {
  3326. Annotation.call(this, params);
  3327. }
  3328. Util.inherit(InteractiveAnnotation, Annotation, {
  3329. hasHtml: function InteractiveAnnotation_hasHtml() {
  3330. return true;
  3331. },
  3332. highlight: function InteractiveAnnotation_highlight() {
  3333. if (this.highlightElement &&
  3334. this.highlightElement.hasAttribute('hidden')) {
  3335. this.highlightElement.removeAttribute('hidden');
  3336. }
  3337. },
  3338. unhighlight: function InteractiveAnnotation_unhighlight() {
  3339. if (this.highlightElement &&
  3340. !this.highlightElement.hasAttribute('hidden')) {
  3341. this.highlightElement.setAttribute('hidden', true);
  3342. }
  3343. },
  3344. initContainer: function InteractiveAnnotation_initContainer() {
  3345. var item = this.data;
  3346. var rect = item.rect;
  3347. var container = this.getEmptyContainer('section', rect, item.borderWidth);
  3348. container.style.backgroundColor = item.color;
  3349. var color = item.color;
  3350. var rgb = [];
  3351. for (var i = 0; i < 3; ++i) {
  3352. rgb[i] = Math.round(color[i] * 255);
  3353. }
  3354. item.colorCssRgb = Util.makeCssRgb(rgb);
  3355. var highlight = document.createElement('div');
  3356. highlight.className = 'annotationHighlight';
  3357. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  3358. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  3359. highlight.setAttribute('hidden', true);
  3360. this.highlightElement = highlight;
  3361. container.appendChild(this.highlightElement);
  3362. return container;
  3363. }
  3364. });
  3365. return InteractiveAnnotation;
  3366. })();
  3367. var TextAnnotation = (function TextAnnotationClosure() {
  3368. function TextAnnotation(params) {
  3369. InteractiveAnnotation.call(this, params);
  3370. if (params.data) {
  3371. return;
  3372. }
  3373. var dict = params.dict;
  3374. var data = this.data;
  3375. var content = dict.get('Contents');
  3376. var title = dict.get('T');
  3377. data.content = stringToPDFString(content || '');
  3378. data.title = stringToPDFString(title || '');
  3379. if (data.hasAppearance) {
  3380. data.name = 'NoIcon';
  3381. } else {
  3382. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  3383. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  3384. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  3385. }
  3386. if (dict.has('C')) {
  3387. data.hasBgColor = true;
  3388. }
  3389. }
  3390. var ANNOT_MIN_SIZE = 10;
  3391. Util.inherit(TextAnnotation, InteractiveAnnotation, {
  3392. getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {
  3393. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  3394. var item = this.data;
  3395. var rect = item.rect;
  3396. // sanity check because of OOo-generated PDFs
  3397. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  3398. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  3399. }
  3400. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  3401. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  3402. }
  3403. var container = this.initContainer();
  3404. container.className = 'annotText';
  3405. var image = document.createElement('img');
  3406. image.style.height = container.style.height;
  3407. image.style.width = container.style.width;
  3408. var iconName = item.name;
  3409. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  3410. iconName.toLowerCase() + '.svg';
  3411. image.alt = '[{{type}} Annotation]';
  3412. image.dataset.l10nId = 'text_annotation_type';
  3413. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  3414. var contentWrapper = document.createElement('div');
  3415. contentWrapper.className = 'annotTextContentWrapper';
  3416. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  3417. contentWrapper.style.top = '-10px';
  3418. var content = document.createElement('div');
  3419. content.className = 'annotTextContent';
  3420. content.setAttribute('hidden', true);
  3421. var i, ii;
  3422. if (item.hasBgColor) {
  3423. var color = item.color;
  3424. var rgb = [];
  3425. for (i = 0; i < 3; ++i) {
  3426. // Enlighten the color (70%)
  3427. var c = Math.round(color[i] * 255);
  3428. rgb[i] = Math.round((255 - c) * 0.7) + c;
  3429. }
  3430. content.style.backgroundColor = Util.makeCssRgb(rgb);
  3431. }
  3432. var title = document.createElement('h1');
  3433. var text = document.createElement('p');
  3434. title.textContent = item.title;
  3435. if (!item.content && !item.title) {
  3436. content.setAttribute('hidden', true);
  3437. } else {
  3438. var e = document.createElement('span');
  3439. var lines = item.content.split(/(?:\r\n?|\n)/);
  3440. for (i = 0, ii = lines.length; i < ii; ++i) {
  3441. var line = lines[i];
  3442. e.appendChild(document.createTextNode(line));
  3443. if (i < (ii - 1)) {
  3444. e.appendChild(document.createElement('br'));
  3445. }
  3446. }
  3447. text.appendChild(e);
  3448. var pinned = false;
  3449. var showAnnotation = function showAnnotation(pin) {
  3450. if (pin) {
  3451. pinned = true;
  3452. }
  3453. if (content.hasAttribute('hidden')) {
  3454. container.style.zIndex += 1;
  3455. content.removeAttribute('hidden');
  3456. }
  3457. };
  3458. var hideAnnotation = function hideAnnotation(unpin) {
  3459. if (unpin) {
  3460. pinned = false;
  3461. }
  3462. if (!content.hasAttribute('hidden') && !pinned) {
  3463. container.style.zIndex -= 1;
  3464. content.setAttribute('hidden', true);
  3465. }
  3466. };
  3467. var toggleAnnotation = function toggleAnnotation() {
  3468. if (pinned) {
  3469. hideAnnotation(true);
  3470. } else {
  3471. showAnnotation(true);
  3472. }
  3473. };
  3474. image.addEventListener('click', function image_clickHandler() {
  3475. toggleAnnotation();
  3476. }, false);
  3477. image.addEventListener('mouseover', function image_mouseOverHandler() {
  3478. showAnnotation();
  3479. }, false);
  3480. image.addEventListener('mouseout', function image_mouseOutHandler() {
  3481. hideAnnotation();
  3482. }, false);
  3483. content.addEventListener('click', function content_clickHandler() {
  3484. hideAnnotation(true);
  3485. }, false);
  3486. }
  3487. content.appendChild(title);
  3488. content.appendChild(text);
  3489. contentWrapper.appendChild(content);
  3490. container.appendChild(image);
  3491. container.appendChild(contentWrapper);
  3492. return container;
  3493. }
  3494. });
  3495. return TextAnnotation;
  3496. })();
  3497. var LinkAnnotation = (function LinkAnnotationClosure() {
  3498. function LinkAnnotation(params) {
  3499. InteractiveAnnotation.call(this, params);
  3500. if (params.data) {
  3501. return;
  3502. }
  3503. var dict = params.dict;
  3504. var data = this.data;
  3505. var action = dict.get('A');
  3506. if (action) {
  3507. var linkType = action.get('S').name;
  3508. if (linkType === 'URI') {
  3509. var url = action.get('URI');
  3510. if (isName(url)) {
  3511. // Some bad PDFs do not put parentheses around relative URLs.
  3512. url = '/' + url.name;
  3513. } else if (url) {
  3514. url = addDefaultProtocolToUrl(url);
  3515. }
  3516. // TODO: pdf spec mentions urls can be relative to a Base
  3517. // entry in the dictionary.
  3518. if (!isValidUrl(url, false)) {
  3519. url = '';
  3520. }
  3521. data.url = url;
  3522. } else if (linkType === 'GoTo') {
  3523. data.dest = action.get('D');
  3524. } else if (linkType === 'GoToR') {
  3525. var urlDict = action.get('F');
  3526. if (isDict(urlDict)) {
  3527. // We assume that the 'url' is a Filspec dictionary
  3528. // and fetch the url without checking any further
  3529. url = urlDict.get('F') || '';
  3530. }
  3531. // TODO: pdf reference says that GoToR
  3532. // can also have 'NewWindow' attribute
  3533. if (!isValidUrl(url, false)) {
  3534. url = '';
  3535. }
  3536. data.url = url;
  3537. data.dest = action.get('D');
  3538. } else if (linkType === 'Named') {
  3539. data.action = action.get('N').name;
  3540. } else {
  3541. warn('unrecognized link type: ' + linkType);
  3542. }
  3543. } else if (dict.has('Dest')) {
  3544. // simple destination link
  3545. var dest = dict.get('Dest');
  3546. data.dest = isName(dest) ? dest.name : dest;
  3547. }
  3548. }
  3549. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  3550. function addDefaultProtocolToUrl(url) {
  3551. if (url && url.indexOf('www.') === 0) {
  3552. return ('http://' + url);
  3553. }
  3554. return url;
  3555. }
  3556. Util.inherit(LinkAnnotation, InteractiveAnnotation, {
  3557. hasOperatorList: function LinkAnnotation_hasOperatorList() {
  3558. return false;
  3559. },
  3560. getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {
  3561. var container = this.initContainer();
  3562. container.className = 'annotLink';
  3563. var item = this.data;
  3564. container.style.borderColor = item.colorCssRgb;
  3565. container.style.borderStyle = 'solid';
  3566. var link = document.createElement('a');
  3567. link.href = link.title = this.data.url || '';
  3568. container.appendChild(link);
  3569. return container;
  3570. }
  3571. });
  3572. return LinkAnnotation;
  3573. })();
  3574. /**
  3575. * The maximum allowed image size in total pixels e.g. width * height. Images
  3576. * above this value will not be drawn. Use -1 for no limit.
  3577. * @var {number}
  3578. */
  3579. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  3580. -1 : PDFJS.maxImageSize);
  3581. /**
  3582. * The url of where the predefined Adobe CMaps are located. Include trailing
  3583. * slash.
  3584. * @var {string}
  3585. */
  3586. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  3587. /**
  3588. * Specifies if CMaps are binary packed.
  3589. * @var {boolean}
  3590. */
  3591. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  3592. /*
  3593. * By default fonts are converted to OpenType fonts and loaded via font face
  3594. * rules. If disabled, the font will be rendered using a built in font renderer
  3595. * that constructs the glyphs with primitive path commands.
  3596. * @var {boolean}
  3597. */
  3598. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  3599. false : PDFJS.disableFontFace);
  3600. /**
  3601. * Path for image resources, mainly for annotation icons. Include trailing
  3602. * slash.
  3603. * @var {string}
  3604. */
  3605. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  3606. '' : PDFJS.imageResourcesPath);
  3607. /**
  3608. * Disable the web worker and run all code on the main thread. This will happen
  3609. * automatically if the browser doesn't support workers or sending typed arrays
  3610. * to workers.
  3611. * @var {boolean}
  3612. */
  3613. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  3614. false : PDFJS.disableWorker);
  3615. /**
  3616. * Path and filename of the worker file. Required when the worker is enabled in
  3617. * development mode. If unspecified in the production build, the worker will be
  3618. * loaded based on the location of the pdf.js file.
  3619. * @var {string}
  3620. */
  3621. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  3622. /**
  3623. * Disable range request loading of PDF files. When enabled and if the server
  3624. * supports partial content requests then the PDF will be fetched in chunks.
  3625. * Enabled (false) by default.
  3626. * @var {boolean}
  3627. */
  3628. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  3629. false : PDFJS.disableRange);
  3630. /**
  3631. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  3632. * will automatically keep fetching more data even if it isn't needed to display
  3633. * the current page. This default behavior can be disabled.
  3634. * @var {boolean}
  3635. */
  3636. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  3637. false : PDFJS.disableAutoFetch);
  3638. /**
  3639. * Enables special hooks for debugging PDF.js.
  3640. * @var {boolean}
  3641. */
  3642. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  3643. /**
  3644. * Enables transfer usage in postMessage for ArrayBuffers.
  3645. * @var {boolean}
  3646. */
  3647. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  3648. true : PDFJS.postMessageTransfers);
  3649. /**
  3650. * Disables URL.createObjectURL usage.
  3651. * @var {boolean}
  3652. */
  3653. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  3654. false : PDFJS.disableCreateObjectURL);
  3655. /**
  3656. * Disables WebGL usage.
  3657. * @var {boolean}
  3658. */
  3659. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  3660. true : PDFJS.disableWebGL);
  3661. /**
  3662. * Controls the logging level.
  3663. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  3664. * - errors
  3665. * - warnings [default]
  3666. * - infos
  3667. * @var {number}
  3668. */
  3669. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  3670. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  3671. /**
  3672. * Document initialization / loading parameters object.
  3673. *
  3674. * @typedef {Object} DocumentInitParameters
  3675. * @property {string} url - The URL of the PDF.
  3676. * @property {TypedArray} data - A typed array with PDF data.
  3677. * @property {Object} httpHeaders - Basic authentication headers.
  3678. * @property {boolean} withCredentials - Indicates whether or not cross-site
  3679. * Access-Control requests should be made using credentials such as cookies
  3680. * or authorization headers. The default is false.
  3681. * @property {string} password - For decrypting password-protected PDFs.
  3682. * @property {TypedArray} initialData - A typed array with the first portion or
  3683. * all of the pdf data. Used by the extension since some data is already
  3684. * loaded before the switch to range requests.
  3685. */
  3686. /**
  3687. * This is the main entry point for loading a PDF and interacting with it.
  3688. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  3689. * is used, which means it must follow the same origin rules that any XHR does
  3690. * e.g. No cross domain requests without CORS.
  3691. *
  3692. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  3693. * where a PDF is located, a typed array (Uint8Array) already populated with
  3694. * data or parameter object.
  3695. *
  3696. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  3697. * to manually serve range requests for data in the PDF. See viewer.js for
  3698. * an example of pdfDataRangeTransport's interface.
  3699. *
  3700. * @param {function} passwordCallback is optional. It is used to request a
  3701. * password if wrong or no password was provided. The callback receives two
  3702. * parameters: function that needs to be called with new password and reason
  3703. * (see {PasswordResponses}).
  3704. *
  3705. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  3706. * object.
  3707. */
  3708. PDFJS.getDocument = function getDocument(source,
  3709. pdfDataRangeTransport,
  3710. passwordCallback,
  3711. progressCallback) {
  3712. var workerInitializedCapability, workerReadyCapability, transport;
  3713. if (typeof source === 'string') {
  3714. source = { url: source };
  3715. } else if (isArrayBuffer(source)) {
  3716. source = { data: source };
  3717. } else if (typeof source !== 'object') {
  3718. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  3719. 'string or a parameter object');
  3720. }
  3721. if (!source.url && !source.data) {
  3722. error('Invalid parameter array, need either .data or .url');
  3723. }
  3724. // copy/use all keys as is except 'url' -- full path is required
  3725. var params = {};
  3726. for (var key in source) {
  3727. if (key === 'url' && typeof window !== 'undefined') {
  3728. params[key] = combineUrl(window.location.href, source[key]);
  3729. continue;
  3730. }
  3731. params[key] = source[key];
  3732. }
  3733. workerInitializedCapability = createPromiseCapability();
  3734. workerReadyCapability = createPromiseCapability();
  3735. transport = new WorkerTransport(workerInitializedCapability,
  3736. workerReadyCapability, pdfDataRangeTransport,
  3737. progressCallback);
  3738. workerInitializedCapability.promise.then(function transportInitialized() {
  3739. transport.passwordCallback = passwordCallback;
  3740. transport.fetchDocument(params);
  3741. });
  3742. return workerReadyCapability.promise;
  3743. };
  3744. /**
  3745. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  3746. * properties that can be read synchronously.
  3747. * @class
  3748. */
  3749. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  3750. function PDFDocumentProxy(pdfInfo, transport) {
  3751. this.pdfInfo = pdfInfo;
  3752. this.transport = transport;
  3753. }
  3754. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  3755. /**
  3756. * @return {number} Total number of pages the PDF contains.
  3757. */
  3758. get numPages() {
  3759. return this.pdfInfo.numPages;
  3760. },
  3761. /**
  3762. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  3763. * unique.
  3764. */
  3765. get fingerprint() {
  3766. return this.pdfInfo.fingerprint;
  3767. },
  3768. /**
  3769. * @param {number} pageNumber The page number to get. The first page is 1.
  3770. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  3771. * object.
  3772. */
  3773. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  3774. return this.transport.getPage(pageNumber);
  3775. },
  3776. /**
  3777. * @param {{num: number, gen: number}} ref The page reference. Must have
  3778. * the 'num' and 'gen' properties.
  3779. * @return {Promise} A promise that is resolved with the page index that is
  3780. * associated with the reference.
  3781. */
  3782. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  3783. return this.transport.getPageIndex(ref);
  3784. },
  3785. /**
  3786. * @return {Promise} A promise that is resolved with a lookup table for
  3787. * mapping named destinations to reference numbers.
  3788. */
  3789. getDestinations: function PDFDocumentProxy_getDestinations() {
  3790. return this.transport.getDestinations();
  3791. },
  3792. /**
  3793. * @return {Promise} A promise that is resolved with a lookup table for
  3794. * mapping named attachments to their content.
  3795. */
  3796. getAttachments: function PDFDocumentProxy_getAttachments() {
  3797. return this.transport.getAttachments();
  3798. },
  3799. /**
  3800. * @return {Promise} A promise that is resolved with an array of all the
  3801. * JavaScript strings in the name tree.
  3802. */
  3803. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  3804. return this.transport.getJavaScript();
  3805. },
  3806. /**
  3807. * @return {Promise} A promise that is resolved with an {Array} that is a
  3808. * tree outline (if it has one) of the PDF. The tree is in the format of:
  3809. * [
  3810. * {
  3811. * title: string,
  3812. * bold: boolean,
  3813. * italic: boolean,
  3814. * color: rgb array,
  3815. * dest: dest obj,
  3816. * items: array of more items like this
  3817. * },
  3818. * ...
  3819. * ].
  3820. */
  3821. getOutline: function PDFDocumentProxy_getOutline() {
  3822. return this.transport.getOutline();
  3823. },
  3824. /**
  3825. * @return {Promise} A promise that is resolved with an {Object} that has
  3826. * info and metadata properties. Info is an {Object} filled with anything
  3827. * available in the information dictionary and similarly metadata is a
  3828. * {Metadata} object with information from the metadata section of the PDF.
  3829. */
  3830. getMetadata: function PDFDocumentProxy_getMetadata() {
  3831. return this.transport.getMetadata();
  3832. },
  3833. /**
  3834. * @return {Promise} A promise that is resolved with a TypedArray that has
  3835. * the raw data from the PDF.
  3836. */
  3837. getData: function PDFDocumentProxy_getData() {
  3838. return this.transport.getData();
  3839. },
  3840. /**
  3841. * @return {Promise} A promise that is resolved when the document's data
  3842. * is loaded. It is resolved with an {Object} that contains the length
  3843. * property that indicates size of the PDF data in bytes.
  3844. */
  3845. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  3846. return this.transport.downloadInfoCapability.promise;
  3847. },
  3848. /**
  3849. * Cleans up resources allocated by the document, e.g. created @font-face.
  3850. */
  3851. cleanup: function PDFDocumentProxy_cleanup() {
  3852. this.transport.startCleanup();
  3853. },
  3854. /**
  3855. * Destroys current document instance and terminates worker.
  3856. */
  3857. destroy: function PDFDocumentProxy_destroy() {
  3858. this.transport.destroy();
  3859. }
  3860. };
  3861. return PDFDocumentProxy;
  3862. })();
  3863. /**
  3864. * Page text content.
  3865. *
  3866. * @typedef {Object} TextContent
  3867. * @property {array} items - array of {@link TextItem}
  3868. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  3869. * name.
  3870. */
  3871. /**
  3872. * Page text content part.
  3873. *
  3874. * @typedef {Object} TextItem
  3875. * @property {string} str - text content.
  3876. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  3877. * @property {array} transform - transformation matrix.
  3878. * @property {number} width - width in device space.
  3879. * @property {number} height - height in device space.
  3880. * @property {string} fontName - font name used by pdf.js for converted font.
  3881. */
  3882. /**
  3883. * Text style.
  3884. *
  3885. * @typedef {Object} TextStyle
  3886. * @property {number} ascent - font ascent.
  3887. * @property {number} descent - font descent.
  3888. * @property {boolean} vertical - text is in vertical mode.
  3889. * @property {string} fontFamily - possible font family
  3890. */
  3891. /**
  3892. * Page render parameters.
  3893. *
  3894. * @typedef {Object} RenderParameters
  3895. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  3896. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  3897. * calling of PDFPage.getViewport method.
  3898. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  3899. * (default value is 'display').
  3900. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  3901. * endLayout and appendImage functions.
  3902. * @property {function} continueCallback - (optional) A function that will be
  3903. * called each time the rendering is paused. To continue
  3904. * rendering call the function that is the first argument
  3905. * to the callback.
  3906. */
  3907. /**
  3908. * Proxy to a PDFPage in the worker thread.
  3909. * @class
  3910. */
  3911. var PDFPageProxy = (function PDFPageProxyClosure() {
  3912. function PDFPageProxy(pageIndex, pageInfo, transport) {
  3913. this.pageIndex = pageIndex;
  3914. this.pageInfo = pageInfo;
  3915. this.transport = transport;
  3916. this.stats = new StatTimer();
  3917. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  3918. this.commonObjs = transport.commonObjs;
  3919. this.objs = new PDFObjects();
  3920. this.cleanupAfterRender = false;
  3921. this.pendingDestroy = false;
  3922. this.intentStates = {};
  3923. }
  3924. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  3925. /**
  3926. * @return {number} Page number of the page. First page is 1.
  3927. */
  3928. get pageNumber() {
  3929. return this.pageIndex + 1;
  3930. },
  3931. /**
  3932. * @return {number} The number of degrees the page is rotated clockwise.
  3933. */
  3934. get rotate() {
  3935. return this.pageInfo.rotate;
  3936. },
  3937. /**
  3938. * @return {Object} The reference that points to this page. It has 'num' and
  3939. * 'gen' properties.
  3940. */
  3941. get ref() {
  3942. return this.pageInfo.ref;
  3943. },
  3944. /**
  3945. * @return {Array} An array of the visible portion of the PDF page in the
  3946. * user space units - [x1, y1, x2, y2].
  3947. */
  3948. get view() {
  3949. return this.pageInfo.view;
  3950. },
  3951. /**
  3952. * @param {number} scale The desired scale of the viewport.
  3953. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  3954. * defaults to the page rotation.
  3955. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  3956. * along with transforms required for rendering.
  3957. */
  3958. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  3959. if (arguments.length < 2) {
  3960. rotate = this.rotate;
  3961. }
  3962. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  3963. },
  3964. /**
  3965. * @return {Promise} A promise that is resolved with an {Array} of the
  3966. * annotation objects.
  3967. */
  3968. getAnnotations: function PDFPageProxy_getAnnotations() {
  3969. if (this.annotationsPromise) {
  3970. return this.annotationsPromise;
  3971. }
  3972. var promise = this.transport.getAnnotations(this.pageIndex);
  3973. this.annotationsPromise = promise;
  3974. return promise;
  3975. },
  3976. /**
  3977. * Begins the process of rendering a page to the desired context.
  3978. * @param {RenderParameters} params Page render parameters.
  3979. * @return {RenderTask} An object that contains the promise, which
  3980. * is resolved when the page finishes rendering.
  3981. */
  3982. render: function PDFPageProxy_render(params) {
  3983. var stats = this.stats;
  3984. stats.time('Overall');
  3985. // If there was a pending destroy cancel it so no cleanup happens during
  3986. // this call to render.
  3987. this.pendingDestroy = false;
  3988. var renderingIntent = ('intent' in params ?
  3989. (params.intent == 'print' ? 'print' : 'display') : 'display');
  3990. if (!this.intentStates[renderingIntent]) {
  3991. this.intentStates[renderingIntent] = {};
  3992. }
  3993. var intentState = this.intentStates[renderingIntent];
  3994. // If there's no displayReadyCapability yet, then the operatorList
  3995. // was never requested before. Make the request and create the promise.
  3996. if (!intentState.displayReadyCapability) {
  3997. intentState.receivingOperatorList = true;
  3998. intentState.displayReadyCapability = createPromiseCapability();
  3999. intentState.operatorList = {
  4000. fnArray: [],
  4001. argsArray: [],
  4002. lastChunk: false
  4003. };
  4004. this.stats.time('Page Request');
  4005. this.transport.messageHandler.send('RenderPageRequest', {
  4006. pageIndex: this.pageNumber - 1,
  4007. intent: renderingIntent
  4008. });
  4009. }
  4010. var internalRenderTask = new InternalRenderTask(complete, params,
  4011. this.objs,
  4012. this.commonObjs,
  4013. intentState.operatorList,
  4014. this.pageNumber);
  4015. if (!intentState.renderTasks) {
  4016. intentState.renderTasks = [];
  4017. }
  4018. intentState.renderTasks.push(internalRenderTask);
  4019. var renderTask = new RenderTask(internalRenderTask);
  4020. var self = this;
  4021. intentState.displayReadyCapability.promise.then(
  4022. function pageDisplayReadyPromise(transparency) {
  4023. if (self.pendingDestroy) {
  4024. complete();
  4025. return;
  4026. }
  4027. stats.time('Rendering');
  4028. internalRenderTask.initalizeGraphics(transparency);
  4029. internalRenderTask.operatorListChanged();
  4030. },
  4031. function pageDisplayReadPromiseError(reason) {
  4032. complete(reason);
  4033. }
  4034. );
  4035. function complete(error) {
  4036. var i = intentState.renderTasks.indexOf(internalRenderTask);
  4037. if (i >= 0) {
  4038. intentState.renderTasks.splice(i, 1);
  4039. }
  4040. if (self.cleanupAfterRender) {
  4041. self.pendingDestroy = true;
  4042. }
  4043. self._tryDestroy();
  4044. if (error) {
  4045. internalRenderTask.capability.reject(error);
  4046. } else {
  4047. internalRenderTask.capability.resolve();
  4048. }
  4049. stats.timeEnd('Rendering');
  4050. stats.timeEnd('Overall');
  4051. }
  4052. return renderTask;
  4053. },
  4054. /**
  4055. * @return {Promise} That is resolved a {@link TextContent}
  4056. * object that represent the page text content.
  4057. */
  4058. getTextContent: function PDFPageProxy_getTextContent() {
  4059. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  4060. pageIndex: this.pageNumber - 1
  4061. });
  4062. },
  4063. /**
  4064. * Destroys resources allocated by the page.
  4065. */
  4066. destroy: function PDFPageProxy_destroy() {
  4067. this.pendingDestroy = true;
  4068. this._tryDestroy();
  4069. },
  4070. /**
  4071. * For internal use only. Attempts to clean up if rendering is in a state
  4072. * where that's possible.
  4073. * @ignore
  4074. */
  4075. _tryDestroy: function PDFPageProxy__destroy() {
  4076. if (!this.pendingDestroy ||
  4077. Object.keys(this.intentStates).some(function(intent) {
  4078. var intentState = this.intentStates[intent];
  4079. return (intentState.renderTasks.length !== 0 ||
  4080. intentState.receivingOperatorList);
  4081. }, this)) {
  4082. return;
  4083. }
  4084. Object.keys(this.intentStates).forEach(function(intent) {
  4085. delete this.intentStates[intent];
  4086. }, this);
  4087. this.objs.clear();
  4088. this.annotationsPromise = null;
  4089. this.pendingDestroy = false;
  4090. },
  4091. /**
  4092. * For internal use only.
  4093. * @ignore
  4094. */
  4095. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  4096. intent) {
  4097. var intentState = this.intentStates[intent];
  4098. intentState.displayReadyCapability.resolve(transparency);
  4099. },
  4100. /**
  4101. * For internal use only.
  4102. * @ignore
  4103. */
  4104. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  4105. intent) {
  4106. var intentState = this.intentStates[intent];
  4107. var i, ii;
  4108. // Add the new chunk to the current operator list.
  4109. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  4110. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  4111. intentState.operatorList.argsArray.push(
  4112. operatorListChunk.argsArray[i]);
  4113. }
  4114. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  4115. // Notify all the rendering tasks there are more operators to be consumed.
  4116. for (i = 0; i < intentState.renderTasks.length; i++) {
  4117. intentState.renderTasks[i].operatorListChanged();
  4118. }
  4119. if (operatorListChunk.lastChunk) {
  4120. intentState.receivingOperatorList = false;
  4121. this._tryDestroy();
  4122. }
  4123. }
  4124. };
  4125. return PDFPageProxy;
  4126. })();
  4127. /**
  4128. * For internal use only.
  4129. * @ignore
  4130. */
  4131. var WorkerTransport = (function WorkerTransportClosure() {
  4132. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  4133. pdfDataRangeTransport, progressCallback) {
  4134. this.pdfDataRangeTransport = pdfDataRangeTransport;
  4135. this.workerReadyCapability = workerReadyCapability;
  4136. this.progressCallback = progressCallback;
  4137. this.commonObjs = new PDFObjects();
  4138. this.pageCache = [];
  4139. this.pagePromises = [];
  4140. this.downloadInfoCapability = createPromiseCapability();
  4141. this.passwordCallback = null;
  4142. // If worker support isn't disabled explicit and the browser has worker
  4143. // support, create a new web worker and test if it/the browser fullfills
  4144. // all requirements to run parts of pdf.js in a web worker.
  4145. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  4146. // as it arrives on the worker. Chrome added this with version 15.
  4147. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  4148. var workerSrc = PDFJS.workerSrc;
  4149. if (!workerSrc) {
  4150. error('No PDFJS.workerSrc specified');
  4151. }
  4152. try {
  4153. // Some versions of FF can't create a worker on localhost, see:
  4154. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  4155. var worker = new Worker(workerSrc);
  4156. var messageHandler = new MessageHandler('main', worker);
  4157. this.messageHandler = messageHandler;
  4158. messageHandler.on('test', function transportTest(data) {
  4159. var supportTypedArray = data && data.supportTypedArray;
  4160. if (supportTypedArray) {
  4161. this.worker = worker;
  4162. if (!data.supportTransfers) {
  4163. PDFJS.postMessageTransfers = false;
  4164. }
  4165. this.setupMessageHandler(messageHandler);
  4166. workerInitializedCapability.resolve();
  4167. } else {
  4168. globalScope.PDFJS.disableWorker = true;
  4169. this.loadFakeWorkerFiles().then(function() {
  4170. this.setupFakeWorker();
  4171. workerInitializedCapability.resolve();
  4172. }.bind(this));
  4173. }
  4174. }.bind(this));
  4175. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  4176. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  4177. // typed array. Also, checking if we can use transfers.
  4178. try {
  4179. messageHandler.send('test', testObj, [testObj.buffer]);
  4180. } catch (ex) {
  4181. info('Cannot use postMessage transfers');
  4182. testObj[0] = 0;
  4183. messageHandler.send('test', testObj);
  4184. }
  4185. return;
  4186. } catch (e) {
  4187. info('The worker has been disabled.');
  4188. }
  4189. }
  4190. // Either workers are disabled, not supported or have thrown an exception.
  4191. // Thus, we fallback to a faked worker.
  4192. globalScope.PDFJS.disableWorker = true;
  4193. this.loadFakeWorkerFiles().then(function() {
  4194. this.setupFakeWorker();
  4195. workerInitializedCapability.resolve();
  4196. }.bind(this));
  4197. }
  4198. WorkerTransport.prototype = {
  4199. destroy: function WorkerTransport_destroy() {
  4200. this.pageCache = [];
  4201. this.pagePromises = [];
  4202. var self = this;
  4203. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  4204. FontLoader.clear();
  4205. if (self.worker) {
  4206. self.worker.terminate();
  4207. }
  4208. });
  4209. },
  4210. loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {
  4211. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  4212. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  4213. // In the developer build load worker_loader which in turn loads all the
  4214. // other files and resolves the promise. In production only the
  4215. // pdf.worker.js file is needed.
  4216. Util.loadScript(PDFJS.workerSrc, function() {
  4217. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  4218. });
  4219. }
  4220. return PDFJS.fakeWorkerFilesLoadedCapability.promise;
  4221. },
  4222. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  4223. warn('Setting up fake worker.');
  4224. // If we don't use a worker, just post/sendMessage to the main thread.
  4225. var fakeWorker = {
  4226. postMessage: function WorkerTransport_postMessage(obj) {
  4227. fakeWorker.onmessage({data: obj});
  4228. },
  4229. terminate: function WorkerTransport_terminate() {}
  4230. };
  4231. var messageHandler = new MessageHandler('main', fakeWorker);
  4232. this.setupMessageHandler(messageHandler);
  4233. // If the main thread is our worker, setup the handling for the messages
  4234. // the main thread sends to it self.
  4235. PDFJS.WorkerMessageHandler.setup(messageHandler);
  4236. },
  4237. setupMessageHandler:
  4238. function WorkerTransport_setupMessageHandler(messageHandler) {
  4239. this.messageHandler = messageHandler;
  4240. function updatePassword(password) {
  4241. messageHandler.send('UpdatePassword', password);
  4242. }
  4243. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  4244. if (pdfDataRangeTransport) {
  4245. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  4246. messageHandler.send('OnDataRange', {
  4247. begin: begin,
  4248. chunk: chunk
  4249. });
  4250. });
  4251. pdfDataRangeTransport.addProgressListener(function(loaded) {
  4252. messageHandler.send('OnDataProgress', {
  4253. loaded: loaded
  4254. });
  4255. });
  4256. messageHandler.on('RequestDataRange',
  4257. function transportDataRange(data) {
  4258. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  4259. }, this);
  4260. }
  4261. messageHandler.on('GetDoc', function transportDoc(data) {
  4262. var pdfInfo = data.pdfInfo;
  4263. this.numPages = data.pdfInfo.numPages;
  4264. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  4265. this.pdfDocument = pdfDocument;
  4266. this.workerReadyCapability.resolve(pdfDocument);
  4267. }, this);
  4268. messageHandler.on('NeedPassword', function transportPassword(data) {
  4269. if (this.passwordCallback) {
  4270. return this.passwordCallback(updatePassword,
  4271. PasswordResponses.NEED_PASSWORD);
  4272. }
  4273. this.workerReadyCapability.reject(data.exception.message,
  4274. data.exception);
  4275. }, this);
  4276. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  4277. if (this.passwordCallback) {
  4278. return this.passwordCallback(updatePassword,
  4279. PasswordResponses.INCORRECT_PASSWORD);
  4280. }
  4281. this.workerReadyCapability.reject(data.exception.message,
  4282. data.exception);
  4283. }, this);
  4284. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  4285. this.workerReadyCapability.reject(data.exception.name, data.exception);
  4286. }, this);
  4287. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  4288. this.workerReadyCapability.reject(data.exception.message,
  4289. data.exception);
  4290. }, this);
  4291. messageHandler.on('UnknownError', function transportUnknownError(data) {
  4292. this.workerReadyCapability.reject(data.exception.message,
  4293. data.exception);
  4294. }, this);
  4295. messageHandler.on('DataLoaded', function transportPage(data) {
  4296. this.downloadInfoCapability.resolve(data);
  4297. }, this);
  4298. messageHandler.on('StartRenderPage', function transportRender(data) {
  4299. var page = this.pageCache[data.pageIndex];
  4300. page.stats.timeEnd('Page Request');
  4301. page._startRenderPage(data.transparency, data.intent);
  4302. }, this);
  4303. messageHandler.on('RenderPageChunk', function transportRender(data) {
  4304. var page = this.pageCache[data.pageIndex];
  4305. page._renderPageChunk(data.operatorList, data.intent);
  4306. }, this);
  4307. messageHandler.on('commonobj', function transportObj(data) {
  4308. var id = data[0];
  4309. var type = data[1];
  4310. if (this.commonObjs.hasData(id)) {
  4311. return;
  4312. }
  4313. switch (type) {
  4314. case 'Font':
  4315. var exportedData = data[2];
  4316. var font;
  4317. if ('error' in exportedData) {
  4318. var error = exportedData.error;
  4319. warn('Error during font loading: ' + error);
  4320. this.commonObjs.resolve(id, error);
  4321. break;
  4322. } else {
  4323. font = new FontFace(exportedData);
  4324. }
  4325. FontLoader.bind(
  4326. [font],
  4327. function fontReady(fontObjs) {
  4328. this.commonObjs.resolve(id, font);
  4329. }.bind(this)
  4330. );
  4331. break;
  4332. case 'FontPath':
  4333. this.commonObjs.resolve(id, data[2]);
  4334. break;
  4335. default:
  4336. error('Got unknown common object type ' + type);
  4337. }
  4338. }, this);
  4339. messageHandler.on('obj', function transportObj(data) {
  4340. var id = data[0];
  4341. var pageIndex = data[1];
  4342. var type = data[2];
  4343. var pageProxy = this.pageCache[pageIndex];
  4344. var imageData;
  4345. if (pageProxy.objs.hasData(id)) {
  4346. return;
  4347. }
  4348. switch (type) {
  4349. case 'JpegStream':
  4350. imageData = data[3];
  4351. loadJpegStream(id, imageData, pageProxy.objs);
  4352. break;
  4353. case 'Image':
  4354. imageData = data[3];
  4355. pageProxy.objs.resolve(id, imageData);
  4356. // heuristics that will allow not to store large data
  4357. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  4358. if (imageData && 'data' in imageData &&
  4359. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  4360. pageProxy.cleanupAfterRender = true;
  4361. }
  4362. break;
  4363. default:
  4364. error('Got unknown object type ' + type);
  4365. }
  4366. }, this);
  4367. messageHandler.on('DocProgress', function transportDocProgress(data) {
  4368. if (this.progressCallback) {
  4369. this.progressCallback({
  4370. loaded: data.loaded,
  4371. total: data.total
  4372. });
  4373. }
  4374. }, this);
  4375. messageHandler.on('DocError', function transportDocError(data) {
  4376. this.workerReadyCapability.reject(data);
  4377. }, this);
  4378. messageHandler.on('PageError', function transportError(data) {
  4379. var page = this.pageCache[data.pageNum - 1];
  4380. var intentState = page.intentStates[data.intent];
  4381. if (intentState.displayReadyCapability.promise) {
  4382. intentState.displayReadyCapability.reject(data.error);
  4383. } else {
  4384. error(data.error);
  4385. }
  4386. }, this);
  4387. messageHandler.on('JpegDecode', function(data) {
  4388. var imageUrl = data[0];
  4389. var components = data[1];
  4390. if (components != 3 && components != 1) {
  4391. return Promise.reject(
  4392. new Error('Only 3 components or 1 component can be returned'));
  4393. }
  4394. return new Promise(function (resolve, reject) {
  4395. var img = new Image();
  4396. img.onload = function () {
  4397. var width = img.width;
  4398. var height = img.height;
  4399. var size = width * height;
  4400. var rgbaLength = size * 4;
  4401. var buf = new Uint8Array(size * components);
  4402. var tmpCanvas = createScratchCanvas(width, height);
  4403. var tmpCtx = tmpCanvas.getContext('2d');
  4404. tmpCtx.drawImage(img, 0, 0);
  4405. var data = tmpCtx.getImageData(0, 0, width, height).data;
  4406. var i, j;
  4407. if (components == 3) {
  4408. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  4409. buf[j] = data[i];
  4410. buf[j + 1] = data[i + 1];
  4411. buf[j + 2] = data[i + 2];
  4412. }
  4413. } else if (components == 1) {
  4414. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  4415. buf[j] = data[i];
  4416. }
  4417. }
  4418. resolve({ data: buf, width: width, height: height});
  4419. };
  4420. img.onerror = function () {
  4421. reject(new Error('JpegDecode failed to load image'));
  4422. };
  4423. img.src = imageUrl;
  4424. });
  4425. });
  4426. },
  4427. fetchDocument: function WorkerTransport_fetchDocument(source) {
  4428. source.disableAutoFetch = PDFJS.disableAutoFetch;
  4429. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  4430. this.messageHandler.send('GetDocRequest', {
  4431. source: source,
  4432. disableRange: PDFJS.disableRange,
  4433. maxImageSize: PDFJS.maxImageSize,
  4434. cMapUrl: PDFJS.cMapUrl,
  4435. cMapPacked: PDFJS.cMapPacked,
  4436. disableFontFace: PDFJS.disableFontFace,
  4437. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  4438. verbosity: PDFJS.verbosity
  4439. });
  4440. },
  4441. getData: function WorkerTransport_getData() {
  4442. return this.messageHandler.sendWithPromise('GetData', null);
  4443. },
  4444. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  4445. if (pageNumber <= 0 || pageNumber > this.numPages ||
  4446. (pageNumber|0) !== pageNumber) {
  4447. return Promise.reject(new Error('Invalid page request'));
  4448. }
  4449. var pageIndex = pageNumber - 1;
  4450. if (pageIndex in this.pagePromises) {
  4451. return this.pagePromises[pageIndex];
  4452. }
  4453. var promise = this.messageHandler.sendWithPromise('GetPage', {
  4454. pageIndex: pageIndex
  4455. }).then(function (pageInfo) {
  4456. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  4457. this.pageCache[pageIndex] = page;
  4458. return page;
  4459. }.bind(this));
  4460. this.pagePromises[pageIndex] = promise;
  4461. return promise;
  4462. },
  4463. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  4464. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  4465. },
  4466. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  4467. return this.messageHandler.sendWithPromise('GetAnnotations',
  4468. { pageIndex: pageIndex });
  4469. },
  4470. getDestinations: function WorkerTransport_getDestinations() {
  4471. return this.messageHandler.sendWithPromise('GetDestinations', null);
  4472. },
  4473. getAttachments: function WorkerTransport_getAttachments() {
  4474. return this.messageHandler.sendWithPromise('GetAttachments', null);
  4475. },
  4476. getJavaScript: function WorkerTransport_getJavaScript() {
  4477. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  4478. },
  4479. getOutline: function WorkerTransport_getOutline() {
  4480. return this.messageHandler.sendWithPromise('GetOutline', null);
  4481. },
  4482. getMetadata: function WorkerTransport_getMetadata() {
  4483. return this.messageHandler.sendWithPromise('GetMetadata', null).
  4484. then(function transportMetadata(results) {
  4485. return {
  4486. info: results[0],
  4487. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  4488. };
  4489. });
  4490. },
  4491. startCleanup: function WorkerTransport_startCleanup() {
  4492. this.messageHandler.sendWithPromise('Cleanup', null).
  4493. then(function endCleanup() {
  4494. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  4495. var page = this.pageCache[i];
  4496. if (page) {
  4497. page.destroy();
  4498. }
  4499. }
  4500. this.commonObjs.clear();
  4501. FontLoader.clear();
  4502. }.bind(this));
  4503. }
  4504. };
  4505. return WorkerTransport;
  4506. })();
  4507. /**
  4508. * A PDF document and page is built of many objects. E.g. there are objects
  4509. * for fonts, images, rendering code and such. These objects might get processed
  4510. * inside of a worker. The `PDFObjects` implements some basic functions to
  4511. * manage these objects.
  4512. * @ignore
  4513. */
  4514. var PDFObjects = (function PDFObjectsClosure() {
  4515. function PDFObjects() {
  4516. this.objs = {};
  4517. }
  4518. PDFObjects.prototype = {
  4519. /**
  4520. * Internal function.
  4521. * Ensures there is an object defined for `objId`.
  4522. */
  4523. ensureObj: function PDFObjects_ensureObj(objId) {
  4524. if (this.objs[objId]) {
  4525. return this.objs[objId];
  4526. }
  4527. var obj = {
  4528. capability: createPromiseCapability(),
  4529. data: null,
  4530. resolved: false
  4531. };
  4532. this.objs[objId] = obj;
  4533. return obj;
  4534. },
  4535. /**
  4536. * If called *without* callback, this returns the data of `objId` but the
  4537. * object needs to be resolved. If it isn't, this function throws.
  4538. *
  4539. * If called *with* a callback, the callback is called with the data of the
  4540. * object once the object is resolved. That means, if you call this
  4541. * function and the object is already resolved, the callback gets called
  4542. * right away.
  4543. */
  4544. get: function PDFObjects_get(objId, callback) {
  4545. // If there is a callback, then the get can be async and the object is
  4546. // not required to be resolved right now
  4547. if (callback) {
  4548. this.ensureObj(objId).capability.promise.then(callback);
  4549. return null;
  4550. }
  4551. // If there isn't a callback, the user expects to get the resolved data
  4552. // directly.
  4553. var obj = this.objs[objId];
  4554. // If there isn't an object yet or the object isn't resolved, then the
  4555. // data isn't ready yet!
  4556. if (!obj || !obj.resolved) {
  4557. error('Requesting object that isn\'t resolved yet ' + objId);
  4558. }
  4559. return obj.data;
  4560. },
  4561. /**
  4562. * Resolves the object `objId` with optional `data`.
  4563. */
  4564. resolve: function PDFObjects_resolve(objId, data) {
  4565. var obj = this.ensureObj(objId);
  4566. obj.resolved = true;
  4567. obj.data = data;
  4568. obj.capability.resolve(data);
  4569. },
  4570. isResolved: function PDFObjects_isResolved(objId) {
  4571. var objs = this.objs;
  4572. if (!objs[objId]) {
  4573. return false;
  4574. } else {
  4575. return objs[objId].resolved;
  4576. }
  4577. },
  4578. hasData: function PDFObjects_hasData(objId) {
  4579. return this.isResolved(objId);
  4580. },
  4581. /**
  4582. * Returns the data of `objId` if object exists, null otherwise.
  4583. */
  4584. getData: function PDFObjects_getData(objId) {
  4585. var objs = this.objs;
  4586. if (!objs[objId] || !objs[objId].resolved) {
  4587. return null;
  4588. } else {
  4589. return objs[objId].data;
  4590. }
  4591. },
  4592. clear: function PDFObjects_clear() {
  4593. this.objs = {};
  4594. }
  4595. };
  4596. return PDFObjects;
  4597. })();
  4598. /**
  4599. * Allows controlling of the rendering tasks.
  4600. * @class
  4601. */
  4602. var RenderTask = (function RenderTaskClosure() {
  4603. function RenderTask(internalRenderTask) {
  4604. this.internalRenderTask = internalRenderTask;
  4605. /**
  4606. * Promise for rendering task completion.
  4607. * @type {Promise}
  4608. */
  4609. this.promise = this.internalRenderTask.capability.promise;
  4610. }
  4611. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  4612. /**
  4613. * Cancels the rendering task. If the task is currently rendering it will
  4614. * not be cancelled until graphics pauses with a timeout. The promise that
  4615. * this object extends will resolved when cancelled.
  4616. */
  4617. cancel: function RenderTask_cancel() {
  4618. this.internalRenderTask.cancel();
  4619. },
  4620. /**
  4621. * Registers callback to indicate the rendering task completion.
  4622. *
  4623. * @param {function} onFulfilled The callback for the rendering completion.
  4624. * @param {function} onRejected The callback for the rendering failure.
  4625. * @return {Promise} A promise that is resolved after the onFulfilled or
  4626. * onRejected callback.
  4627. */
  4628. then: function RenderTask_then(onFulfilled, onRejected) {
  4629. return this.promise.then(onFulfilled, onRejected);
  4630. }
  4631. };
  4632. return RenderTask;
  4633. })();
  4634. /**
  4635. * For internal use only.
  4636. * @ignore
  4637. */
  4638. var InternalRenderTask = (function InternalRenderTaskClosure() {
  4639. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  4640. pageNumber) {
  4641. this.callback = callback;
  4642. this.params = params;
  4643. this.objs = objs;
  4644. this.commonObjs = commonObjs;
  4645. this.operatorListIdx = null;
  4646. this.operatorList = operatorList;
  4647. this.pageNumber = pageNumber;
  4648. this.running = false;
  4649. this.graphicsReadyCallback = null;
  4650. this.graphicsReady = false;
  4651. this.cancelled = false;
  4652. this.capability = createPromiseCapability();
  4653. // caching this-bound methods
  4654. this._continueBound = this._continue.bind(this);
  4655. this._scheduleNextBound = this._scheduleNext.bind(this);
  4656. this._nextBound = this._next.bind(this);
  4657. }
  4658. InternalRenderTask.prototype = {
  4659. initalizeGraphics:
  4660. function InternalRenderTask_initalizeGraphics(transparency) {
  4661. if (this.cancelled) {
  4662. return;
  4663. }
  4664. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  4665. globalScope.StepperManager.enabled) {
  4666. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  4667. this.stepper.init(this.operatorList);
  4668. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  4669. }
  4670. var params = this.params;
  4671. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  4672. this.objs, params.imageLayer);
  4673. this.gfx.beginDrawing(params.viewport, transparency);
  4674. this.operatorListIdx = 0;
  4675. this.graphicsReady = true;
  4676. if (this.graphicsReadyCallback) {
  4677. this.graphicsReadyCallback();
  4678. }
  4679. },
  4680. cancel: function InternalRenderTask_cancel() {
  4681. this.running = false;
  4682. this.cancelled = true;
  4683. this.callback('cancelled');
  4684. },
  4685. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  4686. if (!this.graphicsReady) {
  4687. if (!this.graphicsReadyCallback) {
  4688. this.graphicsReadyCallback = this._continueBound;
  4689. }
  4690. return;
  4691. }
  4692. if (this.stepper) {
  4693. this.stepper.updateOperatorList(this.operatorList);
  4694. }
  4695. if (this.running) {
  4696. return;
  4697. }
  4698. this._continue();
  4699. },
  4700. _continue: function InternalRenderTask__continue() {
  4701. this.running = true;
  4702. if (this.cancelled) {
  4703. return;
  4704. }
  4705. if (this.params.continueCallback) {
  4706. this.params.continueCallback(this._scheduleNextBound);
  4707. } else {
  4708. this._scheduleNext();
  4709. }
  4710. },
  4711. _scheduleNext: function InternalRenderTask__scheduleNext() {
  4712. window.requestAnimationFrame(this._nextBound);
  4713. },
  4714. _next: function InternalRenderTask__next() {
  4715. if (this.cancelled) {
  4716. return;
  4717. }
  4718. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  4719. this.operatorListIdx,
  4720. this._continueBound,
  4721. this.stepper);
  4722. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  4723. this.running = false;
  4724. if (this.operatorList.lastChunk) {
  4725. this.gfx.endDrawing();
  4726. this.callback();
  4727. }
  4728. }
  4729. }
  4730. };
  4731. return InternalRenderTask;
  4732. })();
  4733. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  4734. function fixMetadata(meta) {
  4735. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  4736. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  4737. function(code, d1, d2, d3) {
  4738. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  4739. });
  4740. var chars = '';
  4741. for (var i = 0; i < bytes.length; i += 2) {
  4742. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  4743. chars += code >= 32 && code < 127 && code != 60 && code != 62 &&
  4744. code != 38 && false ? String.fromCharCode(code) :
  4745. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  4746. }
  4747. return '>' + chars;
  4748. });
  4749. }
  4750. function Metadata(meta) {
  4751. if (typeof meta === 'string') {
  4752. // Ghostscript produces invalid metadata
  4753. meta = fixMetadata(meta);
  4754. var parser = new DOMParser();
  4755. meta = parser.parseFromString(meta, 'application/xml');
  4756. } else if (!(meta instanceof Document)) {
  4757. error('Metadata: Invalid metadata object');
  4758. }
  4759. this.metaDocument = meta;
  4760. this.metadata = {};
  4761. this.parse();
  4762. }
  4763. Metadata.prototype = {
  4764. parse: function Metadata_parse() {
  4765. var doc = this.metaDocument;
  4766. var rdf = doc.documentElement;
  4767. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  4768. rdf = rdf.firstChild;
  4769. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  4770. rdf = rdf.nextSibling;
  4771. }
  4772. }
  4773. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  4774. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  4775. return;
  4776. }
  4777. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  4778. for (i = 0, length = children.length; i < length; i++) {
  4779. desc = children[i];
  4780. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  4781. continue;
  4782. }
  4783. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  4784. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  4785. entry = desc.childNodes[ii];
  4786. name = entry.nodeName.toLowerCase();
  4787. this.metadata[name] = entry.textContent.trim();
  4788. }
  4789. }
  4790. }
  4791. },
  4792. get: function Metadata_get(name) {
  4793. return this.metadata[name] || null;
  4794. },
  4795. has: function Metadata_has(name) {
  4796. return typeof this.metadata[name] !== 'undefined';
  4797. }
  4798. };
  4799. return Metadata;
  4800. })();
  4801. // <canvas> contexts store most of the state we need natively.
  4802. // However, PDF needs a bit more state, which we store here.
  4803. // Minimal font size that would be used during canvas fillText operations.
  4804. var MIN_FONT_SIZE = 16;
  4805. var MAX_GROUP_SIZE = 4096;
  4806. var COMPILE_TYPE3_GLYPHS = true;
  4807. function createScratchCanvas(width, height) {
  4808. var canvas = document.createElement('canvas');
  4809. canvas.width = width;
  4810. canvas.height = height;
  4811. return canvas;
  4812. }
  4813. function addContextCurrentTransform(ctx) {
  4814. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  4815. if (!ctx.mozCurrentTransform) {
  4816. // Store the original context
  4817. ctx._scaleX = ctx._scaleX || 1.0;
  4818. ctx._scaleY = ctx._scaleY || 1.0;
  4819. ctx._originalSave = ctx.save;
  4820. ctx._originalRestore = ctx.restore;
  4821. ctx._originalRotate = ctx.rotate;
  4822. ctx._originalScale = ctx.scale;
  4823. ctx._originalTranslate = ctx.translate;
  4824. ctx._originalTransform = ctx.transform;
  4825. ctx._originalSetTransform = ctx.setTransform;
  4826. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  4827. ctx._transformStack = [];
  4828. Object.defineProperty(ctx, 'mozCurrentTransform', {
  4829. get: function getCurrentTransform() {
  4830. return this._transformMatrix;
  4831. }
  4832. });
  4833. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  4834. get: function getCurrentTransformInverse() {
  4835. // Calculation done using WolframAlpha:
  4836. // http://www.wolframalpha.com/input/?
  4837. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  4838. var m = this._transformMatrix;
  4839. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  4840. var ad_bc = a * d - b * c;
  4841. var bc_ad = b * c - a * d;
  4842. return [
  4843. d / ad_bc,
  4844. b / bc_ad,
  4845. c / bc_ad,
  4846. a / ad_bc,
  4847. (d * e - c * f) / bc_ad,
  4848. (b * e - a * f) / ad_bc
  4849. ];
  4850. }
  4851. });
  4852. ctx.save = function ctxSave() {
  4853. var old = this._transformMatrix;
  4854. this._transformStack.push(old);
  4855. this._transformMatrix = old.slice(0, 6);
  4856. this._originalSave();
  4857. };
  4858. ctx.restore = function ctxRestore() {
  4859. var prev = this._transformStack.pop();
  4860. if (prev) {
  4861. this._transformMatrix = prev;
  4862. this._originalRestore();
  4863. }
  4864. };
  4865. ctx.translate = function ctxTranslate(x, y) {
  4866. var m = this._transformMatrix;
  4867. m[4] = m[0] * x + m[2] * y + m[4];
  4868. m[5] = m[1] * x + m[3] * y + m[5];
  4869. this._originalTranslate(x, y);
  4870. };
  4871. ctx.scale = function ctxScale(x, y) {
  4872. var m = this._transformMatrix;
  4873. m[0] = m[0] * x;
  4874. m[1] = m[1] * x;
  4875. m[2] = m[2] * y;
  4876. m[3] = m[3] * y;
  4877. this._originalScale(x, y);
  4878. };
  4879. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4880. var m = this._transformMatrix;
  4881. this._transformMatrix = [
  4882. m[0] * a + m[2] * b,
  4883. m[1] * a + m[3] * b,
  4884. m[0] * c + m[2] * d,
  4885. m[1] * c + m[3] * d,
  4886. m[0] * e + m[2] * f + m[4],
  4887. m[1] * e + m[3] * f + m[5]
  4888. ];
  4889. ctx._originalTransform(a, b, c, d, e, f);
  4890. };
  4891. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4892. this._transformMatrix = [a, b, c, d, e, f];
  4893. ctx._originalSetTransform(a, b, c, d, e, f);
  4894. };
  4895. ctx.rotate = function ctxRotate(angle) {
  4896. var cosValue = Math.cos(angle);
  4897. var sinValue = Math.sin(angle);
  4898. var m = this._transformMatrix;
  4899. this._transformMatrix = [
  4900. m[0] * cosValue + m[2] * sinValue,
  4901. m[1] * cosValue + m[3] * sinValue,
  4902. m[0] * (-sinValue) + m[2] * cosValue,
  4903. m[1] * (-sinValue) + m[3] * cosValue,
  4904. m[4],
  4905. m[5]
  4906. ];
  4907. this._originalRotate(angle);
  4908. };
  4909. }
  4910. }
  4911. var CachedCanvases = (function CachedCanvasesClosure() {
  4912. var cache = {};
  4913. return {
  4914. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  4915. trackTransform) {
  4916. var canvasEntry;
  4917. if (id in cache) {
  4918. canvasEntry = cache[id];
  4919. canvasEntry.canvas.width = width;
  4920. canvasEntry.canvas.height = height;
  4921. // reset canvas transform for emulated mozCurrentTransform, if needed
  4922. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  4923. } else {
  4924. var canvas = createScratchCanvas(width, height);
  4925. var ctx = canvas.getContext('2d');
  4926. if (trackTransform) {
  4927. addContextCurrentTransform(ctx);
  4928. }
  4929. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  4930. }
  4931. return canvasEntry;
  4932. },
  4933. clear: function () {
  4934. cache = {};
  4935. }
  4936. };
  4937. })();
  4938. function compileType3Glyph(imgData) {
  4939. var POINT_TO_PROCESS_LIMIT = 1000;
  4940. var width = imgData.width, height = imgData.height;
  4941. var i, j, j0, width1 = width + 1;
  4942. var points = new Uint8Array(width1 * (height + 1));
  4943. var POINT_TYPES =
  4944. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  4945. // decodes bit-packed mask data
  4946. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  4947. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  4948. for (i = 0, ii = data0.length; i < ii; i++) {
  4949. var mask = 128, elem = data0[i];
  4950. while (mask > 0) {
  4951. data[pos++] = (elem & mask) ? 0 : 255;
  4952. mask >>= 1;
  4953. }
  4954. }
  4955. // finding iteresting points: every point is located between mask pixels,
  4956. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  4957. // will have flags assigned based on neighboring mask pixels:
  4958. // 4 | 8
  4959. // --P--
  4960. // 2 | 1
  4961. // We are interested only in points with the flags:
  4962. // - outside corners: 1, 2, 4, 8;
  4963. // - inside corners: 7, 11, 13, 14;
  4964. // - and, intersections: 5, 10.
  4965. var count = 0;
  4966. pos = 0;
  4967. if (data[pos] !== 0) {
  4968. points[0] = 1;
  4969. ++count;
  4970. }
  4971. for (j = 1; j < width; j++) {
  4972. if (data[pos] !== data[pos + 1]) {
  4973. points[j] = data[pos] ? 2 : 1;
  4974. ++count;
  4975. }
  4976. pos++;
  4977. }
  4978. if (data[pos] !== 0) {
  4979. points[j] = 2;
  4980. ++count;
  4981. }
  4982. for (i = 1; i < height; i++) {
  4983. pos = i * lineSize;
  4984. j0 = i * width1;
  4985. if (data[pos - lineSize] !== data[pos]) {
  4986. points[j0] = data[pos] ? 1 : 8;
  4987. ++count;
  4988. }
  4989. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  4990. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  4991. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  4992. for (j = 1; j < width; j++) {
  4993. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  4994. (data[pos - lineSize + 1] ? 8 : 0);
  4995. if (POINT_TYPES[sum]) {
  4996. points[j0 + j] = POINT_TYPES[sum];
  4997. ++count;
  4998. }
  4999. pos++;
  5000. }
  5001. if (data[pos - lineSize] !== data[pos]) {
  5002. points[j0 + j] = data[pos] ? 2 : 4;
  5003. ++count;
  5004. }
  5005. if (count > POINT_TO_PROCESS_LIMIT) {
  5006. return null;
  5007. }
  5008. }
  5009. pos = lineSize * (height - 1);
  5010. j0 = i * width1;
  5011. if (data[pos] !== 0) {
  5012. points[j0] = 8;
  5013. ++count;
  5014. }
  5015. for (j = 1; j < width; j++) {
  5016. if (data[pos] !== data[pos + 1]) {
  5017. points[j0 + j] = data[pos] ? 4 : 8;
  5018. ++count;
  5019. }
  5020. pos++;
  5021. }
  5022. if (data[pos] !== 0) {
  5023. points[j0 + j] = 4;
  5024. ++count;
  5025. }
  5026. if (count > POINT_TO_PROCESS_LIMIT) {
  5027. return null;
  5028. }
  5029. // building outlines
  5030. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5031. var outlines = [];
  5032. for (i = 0; count && i <= height; i++) {
  5033. var p = i * width1;
  5034. var end = p + width;
  5035. while (p < end && !points[p]) {
  5036. p++;
  5037. }
  5038. if (p === end) {
  5039. continue;
  5040. }
  5041. var coords = [p % width1, i];
  5042. var type = points[p], p0 = p, pp;
  5043. do {
  5044. var step = steps[type];
  5045. do {
  5046. p += step;
  5047. } while (!points[p]);
  5048. pp = points[p];
  5049. if (pp !== 5 && pp !== 10) {
  5050. // set new direction
  5051. type = pp;
  5052. // delete mark
  5053. points[p] = 0;
  5054. } else { // type is 5 or 10, ie, a crossing
  5055. // set new direction
  5056. type = pp & ((0x33 * type) >> 4);
  5057. // set new type for "future hit"
  5058. points[p] &= (type >> 2 | type << 2);
  5059. }
  5060. coords.push(p % width1);
  5061. coords.push((p / width1) | 0);
  5062. --count;
  5063. } while (p0 !== p);
  5064. outlines.push(coords);
  5065. --i;
  5066. }
  5067. var drawOutline = function(c) {
  5068. c.save();
  5069. // the path shall be painted in [0..1]x[0..1] space
  5070. c.scale(1 / width, -1 / height);
  5071. c.translate(0, -height);
  5072. c.beginPath();
  5073. for (var i = 0, ii = outlines.length; i < ii; i++) {
  5074. var o = outlines[i];
  5075. c.moveTo(o[0], o[1]);
  5076. for (var j = 2, jj = o.length; j < jj; j += 2) {
  5077. c.lineTo(o[j], o[j+1]);
  5078. }
  5079. }
  5080. c.fill();
  5081. c.beginPath();
  5082. c.restore();
  5083. };
  5084. return drawOutline;
  5085. }
  5086. var CanvasExtraState = (function CanvasExtraStateClosure() {
  5087. function CanvasExtraState(old) {
  5088. // Are soft masks and alpha values shapes or opacities?
  5089. this.alphaIsShape = false;
  5090. this.fontSize = 0;
  5091. this.fontSizeScale = 1;
  5092. this.textMatrix = IDENTITY_MATRIX;
  5093. this.fontMatrix = FONT_IDENTITY_MATRIX;
  5094. this.leading = 0;
  5095. // Current point (in user coordinates)
  5096. this.x = 0;
  5097. this.y = 0;
  5098. // Start of text line (in text coordinates)
  5099. this.lineX = 0;
  5100. this.lineY = 0;
  5101. // Character and word spacing
  5102. this.charSpacing = 0;
  5103. this.wordSpacing = 0;
  5104. this.textHScale = 1;
  5105. this.textRenderingMode = TextRenderingMode.FILL;
  5106. this.textRise = 0;
  5107. // Color spaces
  5108. this.fillColorSpace = ColorSpace.singletons.gray;
  5109. this.fillColorSpaceObj = null;
  5110. this.strokeColorSpace = ColorSpace.singletons.gray;
  5111. this.strokeColorSpaceObj = null;
  5112. this.fillColorObj = null;
  5113. this.strokeColorObj = null;
  5114. // Default fore and background colors
  5115. this.fillColor = '#000000';
  5116. this.strokeColor = '#000000';
  5117. // Note: fill alpha applies to all non-stroking operations
  5118. this.fillAlpha = 1;
  5119. this.strokeAlpha = 1;
  5120. this.lineWidth = 1;
  5121. this.activeSMask = null; // nonclonable field (see the save method below)
  5122. this.old = old;
  5123. }
  5124. CanvasExtraState.prototype = {
  5125. clone: function CanvasExtraState_clone() {
  5126. return Object.create(this);
  5127. },
  5128. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  5129. this.x = x;
  5130. this.y = y;
  5131. }
  5132. };
  5133. return CanvasExtraState;
  5134. })();
  5135. var CanvasGraphics = (function CanvasGraphicsClosure() {
  5136. // Defines the time the executeOperatorList is going to be executing
  5137. // before it stops and shedules a continue of execution.
  5138. var EXECUTION_TIME = 15;
  5139. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  5140. this.ctx = canvasCtx;
  5141. this.current = new CanvasExtraState();
  5142. this.stateStack = [];
  5143. this.pendingClip = null;
  5144. this.pendingEOFill = false;
  5145. this.res = null;
  5146. this.xobjs = null;
  5147. this.commonObjs = commonObjs;
  5148. this.objs = objs;
  5149. this.imageLayer = imageLayer;
  5150. this.groupStack = [];
  5151. this.processingType3 = null;
  5152. // Patterns are painted relative to the initial page/form transform, see pdf
  5153. // spec 8.7.2 NOTE 1.
  5154. this.baseTransform = null;
  5155. this.baseTransformStack = [];
  5156. this.groupLevel = 0;
  5157. this.smaskStack = [];
  5158. this.smaskCounter = 0;
  5159. this.tempSMask = null;
  5160. if (canvasCtx) {
  5161. addContextCurrentTransform(canvasCtx);
  5162. }
  5163. }
  5164. function putBinaryImageData(ctx, imgData) {
  5165. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  5166. ctx.putImageData(imgData, 0, 0);
  5167. return;
  5168. }
  5169. // Put the image data to the canvas in chunks, rather than putting the
  5170. // whole image at once. This saves JS memory, because the ImageData object
  5171. // is smaller. It also possibly saves C++ memory within the implementation
  5172. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  5173. // the data passed to putImageData()). |n| shouldn't be too small, however,
  5174. // because too many putImageData() calls will slow things down.
  5175. //
  5176. // Note: as written, if the last chunk is partial, the putImageData() call
  5177. // will (conceptually) put pixels past the bounds of the canvas. But
  5178. // that's ok; any such pixels are ignored.
  5179. var height = imgData.height, width = imgData.width;
  5180. var fullChunkHeight = 16;
  5181. var fracChunks = height / fullChunkHeight;
  5182. var fullChunks = Math.floor(fracChunks);
  5183. var totalChunks = Math.ceil(fracChunks);
  5184. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  5185. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  5186. var srcPos = 0, destPos;
  5187. var src = imgData.data;
  5188. var dest = chunkImgData.data;
  5189. var i, j, thisChunkHeight, elemsInThisChunk;
  5190. // There are multiple forms in which the pixel data can be passed, and
  5191. // imgData.kind tells us which one this is.
  5192. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  5193. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  5194. var srcLength = src.byteLength;
  5195. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  5196. new Uint32ArrayView(dest);
  5197. var dest32DataLength = dest32.length;
  5198. var fullSrcDiff = (width + 7) >> 3;
  5199. var white = 0xFFFFFFFF;
  5200. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  5201. 0xFF000000 : 0x000000FF;
  5202. for (i = 0; i < totalChunks; i++) {
  5203. thisChunkHeight =
  5204. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  5205. destPos = 0;
  5206. for (j = 0; j < thisChunkHeight; j++) {
  5207. var srcDiff = srcLength - srcPos;
  5208. var k = 0;
  5209. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  5210. var kEndUnrolled = kEnd & ~7;
  5211. var mask = 0;
  5212. var srcByte = 0;
  5213. for (; k < kEndUnrolled; k += 8) {
  5214. srcByte = src[srcPos++];
  5215. dest32[destPos++] = (srcByte & 128) ? white : black;
  5216. dest32[destPos++] = (srcByte & 64) ? white : black;
  5217. dest32[destPos++] = (srcByte & 32) ? white : black;
  5218. dest32[destPos++] = (srcByte & 16) ? white : black;
  5219. dest32[destPos++] = (srcByte & 8) ? white : black;
  5220. dest32[destPos++] = (srcByte & 4) ? white : black;
  5221. dest32[destPos++] = (srcByte & 2) ? white : black;
  5222. dest32[destPos++] = (srcByte & 1) ? white : black;
  5223. }
  5224. for (; k < kEnd; k++) {
  5225. if (mask === 0) {
  5226. srcByte = src[srcPos++];
  5227. mask = 128;
  5228. }
  5229. dest32[destPos++] = (srcByte & mask) ? white : black;
  5230. mask >>= 1;
  5231. }
  5232. }
  5233. // We ran out of input. Make all remaining pixels transparent.
  5234. while (destPos < dest32DataLength) {
  5235. dest32[destPos++] = 0;
  5236. }
  5237. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5238. }
  5239. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  5240. // RGBA, 32-bits per pixel.
  5241. j = 0;
  5242. elemsInThisChunk = width * fullChunkHeight * 4;
  5243. for (i = 0; i < fullChunks; i++) {
  5244. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5245. srcPos += elemsInThisChunk;
  5246. ctx.putImageData(chunkImgData, 0, j);
  5247. j += fullChunkHeight;
  5248. }
  5249. if (i < totalChunks) {
  5250. elemsInThisChunk = width * partialChunkHeight * 4;
  5251. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5252. ctx.putImageData(chunkImgData, 0, j);
  5253. }
  5254. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  5255. // RGB, 24-bits per pixel.
  5256. thisChunkHeight = fullChunkHeight;
  5257. elemsInThisChunk = width * thisChunkHeight;
  5258. for (i = 0; i < totalChunks; i++) {
  5259. if (i >= fullChunks) {
  5260. thisChunkHeight =partialChunkHeight;
  5261. elemsInThisChunk = width * thisChunkHeight;
  5262. }
  5263. destPos = 0;
  5264. for (j = elemsInThisChunk; j--;) {
  5265. dest[destPos++] = src[srcPos++];
  5266. dest[destPos++] = src[srcPos++];
  5267. dest[destPos++] = src[srcPos++];
  5268. dest[destPos++] = 255;
  5269. }
  5270. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5271. }
  5272. } else {
  5273. error('bad image kind: ' + imgData.kind);
  5274. }
  5275. }
  5276. function putBinaryImageMask(ctx, imgData) {
  5277. var height = imgData.height, width = imgData.width;
  5278. var fullChunkHeight = 16;
  5279. var fracChunks = height / fullChunkHeight;
  5280. var fullChunks = Math.floor(fracChunks);
  5281. var totalChunks = Math.ceil(fracChunks);
  5282. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  5283. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  5284. var srcPos = 0;
  5285. var src = imgData.data;
  5286. var dest = chunkImgData.data;
  5287. for (var i = 0; i < totalChunks; i++) {
  5288. var thisChunkHeight =
  5289. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  5290. // Expand the mask so it can be used by the canvas. Any required
  5291. // inversion has already been handled.
  5292. var destPos = 3; // alpha component offset
  5293. for (var j = 0; j < thisChunkHeight; j++) {
  5294. var mask = 0;
  5295. for (var k = 0; k < width; k++) {
  5296. if (!mask) {
  5297. var elem = src[srcPos++];
  5298. mask = 128;
  5299. }
  5300. dest[destPos] = (elem & mask) ? 0 : 255;
  5301. destPos += 4;
  5302. mask >>= 1;
  5303. }
  5304. }
  5305. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5306. }
  5307. }
  5308. function copyCtxState(sourceCtx, destCtx) {
  5309. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  5310. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  5311. 'globalCompositeOperation', 'font'];
  5312. for (var i = 0, ii = properties.length; i < ii; i++) {
  5313. var property = properties[i];
  5314. if (property in sourceCtx) {
  5315. destCtx[property] = sourceCtx[property];
  5316. }
  5317. }
  5318. if ('setLineDash' in sourceCtx) {
  5319. destCtx.setLineDash(sourceCtx.getLineDash());
  5320. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5321. } else if ('mozDash' in sourceCtx) {
  5322. destCtx.mozDash = sourceCtx.mozDash;
  5323. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  5324. }
  5325. }
  5326. function genericComposeSMask(maskCtx, layerCtx, width, height,
  5327. subtype, backdrop) {
  5328. var addBackdropFn;
  5329. if (backdrop) {
  5330. addBackdropFn = function (r0, g0, b0, bytes) {
  5331. var length = bytes.length;
  5332. for (var i = 3; i < length; i += 4) {
  5333. var alpha = bytes[i] / 255;
  5334. if (alpha === 0) {
  5335. bytes[i - 3] = r0;
  5336. bytes[i - 2] = g0;
  5337. bytes[i - 1] = b0;
  5338. } else if (alpha < 1) {
  5339. var alpha_ = 1 - alpha;
  5340. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) | 0;
  5341. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) | 0;
  5342. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) | 0;
  5343. }
  5344. }
  5345. }.bind(null, backdrop[0], backdrop[1], backdrop[2]);
  5346. } else {
  5347. addBackdropFn = function () {};
  5348. }
  5349. var composeFn;
  5350. if (subtype === 'Luminosity') {
  5351. composeFn = function (maskDataBytes, layerDataBytes) {
  5352. var length = maskDataBytes.length;
  5353. for (var i = 3; i < length; i += 4) {
  5354. var y = ((maskDataBytes[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  5355. (maskDataBytes[i - 2] * 152) + // * 0.59 ....
  5356. (maskDataBytes[i - 1] * 28)) | 0; // * 0.11 ....
  5357. layerDataBytes[i] = (layerDataBytes[i] * y) >> 16;
  5358. }
  5359. };
  5360. } else {
  5361. composeFn = function (maskDataBytes, layerDataBytes) {
  5362. var length = maskDataBytes.length;
  5363. for (var i = 3; i < length; i += 4) {
  5364. var alpha = maskDataBytes[i];
  5365. layerDataBytes[i] = (layerDataBytes[i] * alpha / 255) | 0;
  5366. }
  5367. };
  5368. }
  5369. // processing image in chunks to save memory
  5370. var PIXELS_TO_PROCESS = 65536;
  5371. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5372. for (var row = 0; row < height; row += chunkSize) {
  5373. var chunkHeight = Math.min(chunkSize, height - row);
  5374. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  5375. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  5376. addBackdropFn(maskData.data);
  5377. composeFn(maskData.data, layerData.data);
  5378. maskCtx.putImageData(layerData, 0, row);
  5379. }
  5380. }
  5381. function composeSMask(ctx, smask, layerCtx) {
  5382. var mask = smask.canvas;
  5383. var maskCtx = smask.context;
  5384. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  5385. smask.offsetX, smask.offsetY);
  5386. var backdrop;
  5387. if (smask.backdrop) {
  5388. var cs = smask.colorSpace || ColorSpace.singletons.rgb;
  5389. backdrop = cs.getRgb(smask.backdrop, 0);
  5390. }
  5391. if (WebGLUtils.isEnabled) {
  5392. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  5393. {subtype: smask.subtype, backdrop: backdrop});
  5394. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5395. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  5396. return;
  5397. }
  5398. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  5399. smask.subtype, backdrop);
  5400. ctx.drawImage(mask, 0, 0);
  5401. }
  5402. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  5403. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  5404. var NORMAL_CLIP = {};
  5405. var EO_CLIP = {};
  5406. CanvasGraphics.prototype = {
  5407. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  5408. // For pdfs that use blend modes we have to clear the canvas else certain
  5409. // blend modes can look wrong since we'd be blending with a white
  5410. // backdrop. The problem with a transparent backdrop though is we then
  5411. // don't get sub pixel anti aliasing on text, so we fill with white if
  5412. // we can.
  5413. var width = this.ctx.canvas.width;
  5414. var height = this.ctx.canvas.height;
  5415. if (transparency) {
  5416. this.ctx.clearRect(0, 0, width, height);
  5417. } else {
  5418. this.ctx.mozOpaque = true;
  5419. this.ctx.save();
  5420. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  5421. this.ctx.fillRect(0, 0, width, height);
  5422. this.ctx.restore();
  5423. }
  5424. var transform = viewport.transform;
  5425. this.ctx.save();
  5426. this.ctx.transform.apply(this.ctx, transform);
  5427. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  5428. if (this.imageLayer) {
  5429. this.imageLayer.beginLayout();
  5430. }
  5431. },
  5432. executeOperatorList: function CanvasGraphics_executeOperatorList(
  5433. operatorList,
  5434. executionStartIdx, continueCallback,
  5435. stepper) {
  5436. var argsArray = operatorList.argsArray;
  5437. var fnArray = operatorList.fnArray;
  5438. var i = executionStartIdx || 0;
  5439. var argsArrayLen = argsArray.length;
  5440. // Sometimes the OperatorList to execute is empty.
  5441. if (argsArrayLen == i) {
  5442. return i;
  5443. }
  5444. var endTime = Date.now() + EXECUTION_TIME;
  5445. var commonObjs = this.commonObjs;
  5446. var objs = this.objs;
  5447. var fnId;
  5448. while (true) {
  5449. if (stepper && i === stepper.nextBreakPoint) {
  5450. stepper.breakIt(i, continueCallback);
  5451. return i;
  5452. }
  5453. fnId = fnArray[i];
  5454. if (fnId !== OPS.dependency) {
  5455. this[fnId].apply(this, argsArray[i]);
  5456. } else {
  5457. var deps = argsArray[i];
  5458. for (var n = 0, nn = deps.length; n < nn; n++) {
  5459. var depObjId = deps[n];
  5460. var common = depObjId.substring(0, 2) == 'g_';
  5461. // If the promise isn't resolved yet, add the continueCallback
  5462. // to the promise and bail out.
  5463. if (!common && !objs.isResolved(depObjId)) {
  5464. objs.get(depObjId, continueCallback);
  5465. return i;
  5466. }
  5467. if (common && !commonObjs.isResolved(depObjId)) {
  5468. commonObjs.get(depObjId, continueCallback);
  5469. return i;
  5470. }
  5471. }
  5472. }
  5473. i++;
  5474. // If the entire operatorList was executed, stop as were done.
  5475. if (i == argsArrayLen) {
  5476. return i;
  5477. }
  5478. // If the execution took longer then a certain amount of time and
  5479. // `continueCallback` is specified, interrupt the execution.
  5480. if (continueCallback && Date.now() > endTime) {
  5481. continueCallback();
  5482. return i;
  5483. }
  5484. // If the operatorList isn't executed completely yet OR the execution
  5485. // time was short enough, do another execution round.
  5486. }
  5487. },
  5488. endDrawing: function CanvasGraphics_endDrawing() {
  5489. this.ctx.restore();
  5490. CachedCanvases.clear();
  5491. WebGLUtils.clear();
  5492. if (this.imageLayer) {
  5493. this.imageLayer.endLayout();
  5494. }
  5495. },
  5496. // Graphics state
  5497. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  5498. this.current.lineWidth = width;
  5499. this.ctx.lineWidth = width;
  5500. },
  5501. setLineCap: function CanvasGraphics_setLineCap(style) {
  5502. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5503. },
  5504. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  5505. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5506. },
  5507. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  5508. this.ctx.miterLimit = limit;
  5509. },
  5510. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  5511. var ctx = this.ctx;
  5512. if ('setLineDash' in ctx) {
  5513. ctx.setLineDash(dashArray);
  5514. ctx.lineDashOffset = dashPhase;
  5515. } else {
  5516. ctx.mozDash = dashArray;
  5517. ctx.mozDashOffset = dashPhase;
  5518. }
  5519. },
  5520. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  5521. // Maybe if we one day fully support color spaces this will be important
  5522. // for now we can ignore.
  5523. // TODO set rendering intent?
  5524. },
  5525. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  5526. // There's no way to control this with canvas, but we can safely ignore.
  5527. // TODO set flatness?
  5528. },
  5529. setGState: function CanvasGraphics_setGState(states) {
  5530. for (var i = 0, ii = states.length; i < ii; i++) {
  5531. var state = states[i];
  5532. var key = state[0];
  5533. var value = state[1];
  5534. switch (key) {
  5535. case 'LW':
  5536. this.setLineWidth(value);
  5537. break;
  5538. case 'LC':
  5539. this.setLineCap(value);
  5540. break;
  5541. case 'LJ':
  5542. this.setLineJoin(value);
  5543. break;
  5544. case 'ML':
  5545. this.setMiterLimit(value);
  5546. break;
  5547. case 'D':
  5548. this.setDash(value[0], value[1]);
  5549. break;
  5550. case 'RI':
  5551. this.setRenderingIntent(value);
  5552. break;
  5553. case 'FL':
  5554. this.setFlatness(value);
  5555. break;
  5556. case 'Font':
  5557. this.setFont(value[0], value[1]);
  5558. break;
  5559. case 'CA':
  5560. this.current.strokeAlpha = state[1];
  5561. break;
  5562. case 'ca':
  5563. this.current.fillAlpha = state[1];
  5564. this.ctx.globalAlpha = state[1];
  5565. break;
  5566. case 'BM':
  5567. if (value && value.name && (value.name !== 'Normal')) {
  5568. var mode = value.name.replace(/([A-Z])/g,
  5569. function(c) {
  5570. return '-' + c.toLowerCase();
  5571. }
  5572. ).substring(1);
  5573. this.ctx.globalCompositeOperation = mode;
  5574. if (this.ctx.globalCompositeOperation !== mode) {
  5575. warn('globalCompositeOperation "' + mode +
  5576. '" is not supported');
  5577. }
  5578. } else {
  5579. this.ctx.globalCompositeOperation = 'source-over';
  5580. }
  5581. break;
  5582. case 'SMask':
  5583. if (this.current.activeSMask) {
  5584. this.endSMaskGroup();
  5585. }
  5586. this.current.activeSMask = value ? this.tempSMask : null;
  5587. if (this.current.activeSMask) {
  5588. this.beginSMaskGroup();
  5589. }
  5590. this.tempSMask = null;
  5591. break;
  5592. }
  5593. }
  5594. },
  5595. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  5596. var activeSMask = this.current.activeSMask;
  5597. var drawnWidth = activeSMask.canvas.width;
  5598. var drawnHeight = activeSMask.canvas.height;
  5599. var cacheId = 'smaskGroupAt' + this.groupLevel;
  5600. var scratchCanvas = CachedCanvases.getCanvas(
  5601. cacheId, drawnWidth, drawnHeight, true);
  5602. var currentCtx = this.ctx;
  5603. var currentTransform = currentCtx.mozCurrentTransform;
  5604. this.ctx.save();
  5605. var groupCtx = scratchCanvas.context;
  5606. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  5607. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  5608. groupCtx.transform.apply(groupCtx, currentTransform);
  5609. copyCtxState(currentCtx, groupCtx);
  5610. this.ctx = groupCtx;
  5611. this.setGState([
  5612. ['BM', 'Normal'],
  5613. ['ca', 1],
  5614. ['CA', 1]
  5615. ]);
  5616. this.groupStack.push(currentCtx);
  5617. this.groupLevel++;
  5618. },
  5619. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  5620. var groupCtx = this.ctx;
  5621. this.groupLevel--;
  5622. this.ctx = this.groupStack.pop();
  5623. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  5624. this.ctx.restore();
  5625. },
  5626. save: function CanvasGraphics_save() {
  5627. this.ctx.save();
  5628. var old = this.current;
  5629. this.stateStack.push(old);
  5630. this.current = old.clone();
  5631. if (this.current.activeSMask) {
  5632. this.current.activeSMask = null;
  5633. }
  5634. },
  5635. restore: function CanvasGraphics_restore() {
  5636. var prev = this.stateStack.pop();
  5637. if (prev) {
  5638. if (this.current.activeSMask) {
  5639. this.endSMaskGroup();
  5640. }
  5641. this.current = prev;
  5642. this.ctx.restore();
  5643. }
  5644. },
  5645. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  5646. this.ctx.transform(a, b, c, d, e, f);
  5647. },
  5648. // Path
  5649. constructPath: function CanvasGraphics_constructPath(ops, args) {
  5650. var ctx = this.ctx;
  5651. var current = this.current;
  5652. var x = current.x, y = current.y;
  5653. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  5654. switch (ops[i] | 0) {
  5655. case OPS.moveTo:
  5656. x = args[j++];
  5657. y = args[j++];
  5658. ctx.moveTo(x, y);
  5659. break;
  5660. case OPS.lineTo:
  5661. x = args[j++];
  5662. y = args[j++];
  5663. ctx.lineTo(x, y);
  5664. break;
  5665. case OPS.curveTo:
  5666. x = args[j + 4];
  5667. y = args[j + 5];
  5668. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  5669. x, y);
  5670. j += 6;
  5671. break;
  5672. case OPS.curveTo2:
  5673. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  5674. args[j + 2], args[j + 3]);
  5675. x = args[j + 2];
  5676. y = args[j + 3];
  5677. j += 4;
  5678. break;
  5679. case OPS.curveTo3:
  5680. x = args[j + 2];
  5681. y = args[j + 3];
  5682. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  5683. j += 4;
  5684. break;
  5685. case OPS.closePath:
  5686. ctx.closePath();
  5687. break;
  5688. }
  5689. }
  5690. current.setCurrentPoint(x, y);
  5691. },
  5692. closePath: function CanvasGraphics_closePath() {
  5693. this.ctx.closePath();
  5694. },
  5695. rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
  5696. if (width === 0) {
  5697. width = this.getSinglePixelWidth();
  5698. }
  5699. if (height === 0) {
  5700. height = this.getSinglePixelWidth();
  5701. }
  5702. this.ctx.rect(x, y, width, height);
  5703. },
  5704. stroke: function CanvasGraphics_stroke(consumePath) {
  5705. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  5706. var ctx = this.ctx;
  5707. var strokeColor = this.current.strokeColor;
  5708. if (this.current.lineWidth === 0) {
  5709. ctx.lineWidth = this.getSinglePixelWidth();
  5710. }
  5711. // For stroke we want to temporarily change the global alpha to the
  5712. // stroking alpha.
  5713. ctx.globalAlpha = this.current.strokeAlpha;
  5714. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  5715. strokeColor.type === 'Pattern') {
  5716. // for patterns, we transform to pattern space, calculate
  5717. // the pattern, call stroke, and restore to user space
  5718. ctx.save();
  5719. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  5720. ctx.stroke();
  5721. ctx.restore();
  5722. } else {
  5723. ctx.stroke();
  5724. }
  5725. if (consumePath) {
  5726. this.consumePath();
  5727. }
  5728. // Restore the global alpha to the fill alpha
  5729. ctx.globalAlpha = this.current.fillAlpha;
  5730. },
  5731. closeStroke: function CanvasGraphics_closeStroke() {
  5732. this.closePath();
  5733. this.stroke();
  5734. },
  5735. fill: function CanvasGraphics_fill(consumePath) {
  5736. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  5737. var ctx = this.ctx;
  5738. var fillColor = this.current.fillColor;
  5739. var needRestore = false;
  5740. if (fillColor && fillColor.hasOwnProperty('type') &&
  5741. fillColor.type === 'Pattern') {
  5742. ctx.save();
  5743. ctx.fillStyle = fillColor.getPattern(ctx, this);
  5744. needRestore = true;
  5745. }
  5746. if (this.pendingEOFill) {
  5747. if (ctx.mozFillRule !== undefined) {
  5748. ctx.mozFillRule = 'evenodd';
  5749. ctx.fill();
  5750. ctx.mozFillRule = 'nonzero';
  5751. } else {
  5752. try {
  5753. ctx.fill('evenodd');
  5754. } catch (ex) {
  5755. // shouldn't really happen, but browsers might think differently
  5756. ctx.fill();
  5757. }
  5758. }
  5759. this.pendingEOFill = false;
  5760. } else {
  5761. ctx.fill();
  5762. }
  5763. if (needRestore) {
  5764. ctx.restore();
  5765. }
  5766. if (consumePath) {
  5767. this.consumePath();
  5768. }
  5769. },
  5770. eoFill: function CanvasGraphics_eoFill() {
  5771. this.pendingEOFill = true;
  5772. this.fill();
  5773. },
  5774. fillStroke: function CanvasGraphics_fillStroke() {
  5775. this.fill(false);
  5776. this.stroke(false);
  5777. this.consumePath();
  5778. },
  5779. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  5780. this.pendingEOFill = true;
  5781. this.fillStroke();
  5782. },
  5783. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  5784. this.closePath();
  5785. this.fillStroke();
  5786. },
  5787. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  5788. this.pendingEOFill = true;
  5789. this.closePath();
  5790. this.fillStroke();
  5791. },
  5792. endPath: function CanvasGraphics_endPath() {
  5793. this.consumePath();
  5794. },
  5795. // Clipping
  5796. clip: function CanvasGraphics_clip() {
  5797. this.pendingClip = NORMAL_CLIP;
  5798. },
  5799. eoClip: function CanvasGraphics_eoClip() {
  5800. this.pendingClip = EO_CLIP;
  5801. },
  5802. // Text
  5803. beginText: function CanvasGraphics_beginText() {
  5804. this.current.textMatrix = IDENTITY_MATRIX;
  5805. this.current.x = this.current.lineX = 0;
  5806. this.current.y = this.current.lineY = 0;
  5807. },
  5808. endText: function CanvasGraphics_endText() {
  5809. var paths = this.pendingTextPaths;
  5810. var ctx = this.ctx;
  5811. if (paths === undefined) {
  5812. ctx.beginPath();
  5813. return;
  5814. }
  5815. ctx.save();
  5816. ctx.beginPath();
  5817. for (var i = 0; i < paths.length; i++) {
  5818. var path = paths[i];
  5819. ctx.setTransform.apply(ctx, path.transform);
  5820. ctx.translate(path.x, path.y);
  5821. path.addToPath(ctx, path.fontSize);
  5822. }
  5823. ctx.restore();
  5824. ctx.clip();
  5825. ctx.beginPath();
  5826. delete this.pendingTextPaths;
  5827. },
  5828. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  5829. this.current.charSpacing = spacing;
  5830. },
  5831. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  5832. this.current.wordSpacing = spacing;
  5833. },
  5834. setHScale: function CanvasGraphics_setHScale(scale) {
  5835. this.current.textHScale = scale / 100;
  5836. },
  5837. setLeading: function CanvasGraphics_setLeading(leading) {
  5838. this.current.leading = -leading;
  5839. },
  5840. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  5841. var fontObj = this.commonObjs.get(fontRefName);
  5842. var current = this.current;
  5843. if (!fontObj) {
  5844. error('Can\'t find font for ' + fontRefName);
  5845. }
  5846. current.fontMatrix = (fontObj.fontMatrix ?
  5847. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  5848. // A valid matrix needs all main diagonal elements to be non-zero
  5849. // This also ensures we bypass FF bugzilla bug #719844.
  5850. if (current.fontMatrix[0] === 0 ||
  5851. current.fontMatrix[3] === 0) {
  5852. warn('Invalid font matrix for font ' + fontRefName);
  5853. }
  5854. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  5855. // and in some docs this can be negative (inverted x-y axes).
  5856. if (size < 0) {
  5857. size = -size;
  5858. current.fontDirection = -1;
  5859. } else {
  5860. current.fontDirection = 1;
  5861. }
  5862. this.current.font = fontObj;
  5863. this.current.fontSize = size;
  5864. if (fontObj.isType3Font) {
  5865. return; // we don't need ctx.font for Type3 fonts
  5866. }
  5867. var name = fontObj.loadedName || 'sans-serif';
  5868. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  5869. (fontObj.bold ? 'bold' : 'normal');
  5870. var italic = fontObj.italic ? 'italic' : 'normal';
  5871. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  5872. // Some font backends cannot handle fonts below certain size.
  5873. // Keeping the font at minimal size and using the fontSizeScale to change
  5874. // the current transformation matrix before the fillText/strokeText.
  5875. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  5876. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  5877. this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
  5878. size / MIN_FONT_SIZE;
  5879. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  5880. this.ctx.font = rule;
  5881. },
  5882. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  5883. this.current.textRenderingMode = mode;
  5884. },
  5885. setTextRise: function CanvasGraphics_setTextRise(rise) {
  5886. this.current.textRise = rise;
  5887. },
  5888. moveText: function CanvasGraphics_moveText(x, y) {
  5889. this.current.x = this.current.lineX += x;
  5890. this.current.y = this.current.lineY += y;
  5891. },
  5892. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  5893. this.setLeading(-y);
  5894. this.moveText(x, y);
  5895. },
  5896. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  5897. this.current.textMatrix = [a, b, c, d, e, f];
  5898. this.current.x = this.current.lineX = 0;
  5899. this.current.y = this.current.lineY = 0;
  5900. },
  5901. nextLine: function CanvasGraphics_nextLine() {
  5902. this.moveText(0, this.current.leading);
  5903. },
  5904. applyTextTransforms: function CanvasGraphics_applyTextTransforms() {
  5905. var ctx = this.ctx;
  5906. var current = this.current;
  5907. ctx.transform.apply(ctx, current.textMatrix);
  5908. ctx.translate(current.x, current.y + current.textRise);
  5909. if (current.fontDirection > 0) {
  5910. ctx.scale(current.textHScale, -1);
  5911. } else {
  5912. ctx.scale(-current.textHScale, 1);
  5913. }
  5914. },
  5915. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  5916. var ctx = this.ctx;
  5917. var current = this.current;
  5918. var font = current.font;
  5919. var fontSize = current.fontSize / current.fontSizeScale;
  5920. var textRenderingMode = current.textRenderingMode;
  5921. var fillStrokeMode = textRenderingMode &
  5922. TextRenderingMode.FILL_STROKE_MASK;
  5923. var isAddToPathSet = !!(textRenderingMode &
  5924. TextRenderingMode.ADD_TO_PATH_FLAG);
  5925. var addToPath;
  5926. if (font.disableFontFace || isAddToPathSet) {
  5927. addToPath = font.getPathGenerator(this.commonObjs, character);
  5928. }
  5929. if (font.disableFontFace) {
  5930. ctx.save();
  5931. ctx.translate(x, y);
  5932. ctx.beginPath();
  5933. addToPath(ctx, fontSize);
  5934. if (fillStrokeMode === TextRenderingMode.FILL ||
  5935. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5936. ctx.fill();
  5937. }
  5938. if (fillStrokeMode === TextRenderingMode.STROKE ||
  5939. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5940. ctx.stroke();
  5941. }
  5942. ctx.restore();
  5943. } else {
  5944. if (fillStrokeMode === TextRenderingMode.FILL ||
  5945. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5946. ctx.fillText(character, x, y);
  5947. }
  5948. if (fillStrokeMode === TextRenderingMode.STROKE ||
  5949. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5950. ctx.strokeText(character, x, y);
  5951. }
  5952. }
  5953. if (isAddToPathSet) {
  5954. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  5955. paths.push({
  5956. transform: ctx.mozCurrentTransform,
  5957. x: x,
  5958. y: y,
  5959. fontSize: fontSize,
  5960. addToPath: addToPath
  5961. });
  5962. }
  5963. },
  5964. get isFontSubpixelAAEnabled() {
  5965. // Checks if anti-aliasing is enabled when scaled text is painted.
  5966. // On Windows GDI scaled fonts looks bad.
  5967. var ctx = document.createElement('canvas').getContext('2d');
  5968. ctx.scale(1.5, 1);
  5969. ctx.fillText('I', 0, 10);
  5970. var data = ctx.getImageData(0, 0, 10, 10).data;
  5971. var enabled = false;
  5972. for (var i = 3; i < data.length; i += 4) {
  5973. if (data[i] > 0 && data[i] < 255) {
  5974. enabled = true;
  5975. break;
  5976. }
  5977. }
  5978. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  5979. },
  5980. showText: function CanvasGraphics_showText(glyphs) {
  5981. var ctx = this.ctx;
  5982. var current = this.current;
  5983. var font = current.font;
  5984. var fontSize = current.fontSize;
  5985. var fontSizeScale = current.fontSizeScale;
  5986. var charSpacing = current.charSpacing;
  5987. var wordSpacing = current.wordSpacing;
  5988. var textHScale = current.textHScale * current.fontDirection;
  5989. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  5990. var glyphsLength = glyphs.length;
  5991. var vertical = font.vertical;
  5992. var defaultVMetrics = font.defaultVMetrics;
  5993. var i, glyph, width;
  5994. if (fontSize === 0) {
  5995. return;
  5996. }
  5997. // Type3 fonts - each glyph is a "mini-PDF"
  5998. if (font.isType3Font) {
  5999. ctx.save();
  6000. ctx.transform.apply(ctx, current.textMatrix);
  6001. ctx.translate(current.x, current.y);
  6002. ctx.scale(textHScale, 1);
  6003. for (i = 0; i < glyphsLength; ++i) {
  6004. glyph = glyphs[i];
  6005. if (glyph === null) {
  6006. // word break
  6007. this.ctx.translate(wordSpacing, 0);
  6008. current.x += wordSpacing * textHScale;
  6009. continue;
  6010. }
  6011. this.processingType3 = glyph;
  6012. this.save();
  6013. ctx.scale(fontSize, fontSize);
  6014. ctx.transform.apply(ctx, fontMatrix);
  6015. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  6016. this.executeOperatorList(operatorList);
  6017. this.restore();
  6018. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  6019. width = ((transformed[0] * fontSize + charSpacing) *
  6020. current.fontDirection);
  6021. ctx.translate(width, 0);
  6022. current.x += width * textHScale;
  6023. }
  6024. ctx.restore();
  6025. this.processingType3 = null;
  6026. } else {
  6027. ctx.save();
  6028. this.applyTextTransforms();
  6029. var lineWidth = current.lineWidth;
  6030. var a1 = current.textMatrix[0], b1 = current.textMatrix[1];
  6031. var scale = Math.sqrt(a1 * a1 + b1 * b1);
  6032. if (scale === 0 || lineWidth === 0) {
  6033. lineWidth = this.getSinglePixelWidth();
  6034. } else {
  6035. lineWidth /= scale;
  6036. }
  6037. if (fontSizeScale != 1.0) {
  6038. ctx.scale(fontSizeScale, fontSizeScale);
  6039. lineWidth /= fontSizeScale;
  6040. }
  6041. ctx.lineWidth = lineWidth;
  6042. var x = 0;
  6043. for (i = 0; i < glyphsLength; ++i) {
  6044. glyph = glyphs[i];
  6045. if (glyph === null) {
  6046. // word break
  6047. x += current.fontDirection * wordSpacing;
  6048. continue;
  6049. }
  6050. var restoreNeeded = false;
  6051. var character = glyph.fontChar;
  6052. var vmetric = glyph.vmetric || defaultVMetrics;
  6053. if (vertical) {
  6054. var vx = glyph.vmetric ? vmetric[1] : glyph.width * 0.5;
  6055. vx = -vx * fontSize * current.fontMatrix[0];
  6056. var vy = vmetric[2] * fontSize * current.fontMatrix[0];
  6057. }
  6058. width = vmetric ? -vmetric[0] : glyph.width;
  6059. var charWidth = width * fontSize * current.fontMatrix[0] +
  6060. charSpacing * current.fontDirection;
  6061. var accent = glyph.accent;
  6062. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  6063. if (vertical) {
  6064. scaledX = vx / fontSizeScale;
  6065. scaledY = (x + vy) / fontSizeScale;
  6066. } else {
  6067. scaledX = x / fontSizeScale;
  6068. scaledY = 0;
  6069. }
  6070. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  6071. // some standard fonts may not have the exact width, trying to
  6072. // rescale per character
  6073. var measuredWidth = ctx.measureText(character).width * 1000 /
  6074. current.fontSize * current.fontSizeScale;
  6075. var characterScaleX = width / measuredWidth;
  6076. restoreNeeded = true;
  6077. ctx.save();
  6078. ctx.scale(characterScaleX, 1);
  6079. scaledX /= characterScaleX;
  6080. if (accent) {
  6081. scaledAccentX /= characterScaleX;
  6082. }
  6083. }
  6084. this.paintChar(character, scaledX, scaledY);
  6085. if (accent) {
  6086. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  6087. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  6088. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  6089. }
  6090. x += charWidth;
  6091. if (restoreNeeded) {
  6092. ctx.restore();
  6093. }
  6094. }
  6095. if (vertical) {
  6096. current.y -= x * textHScale;
  6097. } else {
  6098. current.x += x * textHScale;
  6099. }
  6100. ctx.restore();
  6101. }
  6102. },
  6103. showSpacedText: function CanvasGraphics_showSpacedText(arr) {
  6104. var current = this.current;
  6105. var font = current.font;
  6106. var fontSize = current.fontSize;
  6107. // TJ array's number is independent from fontMatrix
  6108. var textHScale = current.textHScale * 0.001 * current.fontDirection;
  6109. var arrLength = arr.length;
  6110. var vertical = font.vertical;
  6111. for (var i = 0; i < arrLength; ++i) {
  6112. var e = arr[i];
  6113. if (isNum(e)) {
  6114. var spacingLength = -e * fontSize * textHScale;
  6115. if (vertical) {
  6116. current.y += spacingLength;
  6117. } else {
  6118. current.x += spacingLength;
  6119. }
  6120. } else {
  6121. this.showText(e);
  6122. }
  6123. }
  6124. },
  6125. nextLineShowText: function CanvasGraphics_nextLineShowText(text) {
  6126. this.nextLine();
  6127. this.showText(text);
  6128. },
  6129. nextLineSetSpacingShowText:
  6130. function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing,
  6131. charSpacing,
  6132. text) {
  6133. this.setWordSpacing(wordSpacing);
  6134. this.setCharSpacing(charSpacing);
  6135. this.nextLineShowText(text);
  6136. },
  6137. // Type3 fonts
  6138. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  6139. // We can safely ignore this since the width should be the same
  6140. // as the width in the Widths array.
  6141. },
  6142. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  6143. yWidth,
  6144. llx,
  6145. lly,
  6146. urx,
  6147. ury) {
  6148. // TODO According to the spec we're also suppose to ignore any operators
  6149. // that set color or include images while processing this type3 font.
  6150. this.rectangle(llx, lly, urx - llx, ury - lly);
  6151. this.clip();
  6152. this.endPath();
  6153. },
  6154. // Color
  6155. setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) {
  6156. this.current.strokeColorSpace = ColorSpace.fromIR(raw);
  6157. },
  6158. setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) {
  6159. this.current.fillColorSpace = ColorSpace.fromIR(raw);
  6160. },
  6161. setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) {
  6162. var cs = this.current.strokeColorSpace;
  6163. var rgbColor = cs.getRgb(arguments, 0);
  6164. var color = Util.makeCssRgb(rgbColor);
  6165. this.ctx.strokeStyle = color;
  6166. this.current.strokeColor = color;
  6167. },
  6168. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) {
  6169. var pattern;
  6170. if (IR[0] == 'TilingPattern') {
  6171. var args = IR[1];
  6172. var base = cs.base;
  6173. var color;
  6174. if (base) {
  6175. color = base.getRgb(args, 0);
  6176. }
  6177. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  6178. this.commonObjs, this.baseTransform);
  6179. } else {
  6180. pattern = getShadingPatternFromIR(IR);
  6181. }
  6182. return pattern;
  6183. },
  6184. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  6185. var cs = this.current.strokeColorSpace;
  6186. if (cs.name == 'Pattern') {
  6187. this.current.strokeColor = this.getColorN_Pattern(arguments, cs);
  6188. } else {
  6189. this.setStrokeColor.apply(this, arguments);
  6190. }
  6191. },
  6192. setFillColor: function CanvasGraphics_setFillColor(/*...*/) {
  6193. var cs = this.current.fillColorSpace;
  6194. var rgbColor = cs.getRgb(arguments, 0);
  6195. var color = Util.makeCssRgb(rgbColor);
  6196. this.ctx.fillStyle = color;
  6197. this.current.fillColor = color;
  6198. },
  6199. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  6200. var cs = this.current.fillColorSpace;
  6201. if (cs.name == 'Pattern') {
  6202. this.current.fillColor = this.getColorN_Pattern(arguments, cs);
  6203. } else {
  6204. this.setFillColor.apply(this, arguments);
  6205. }
  6206. },
  6207. setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {
  6208. this.current.strokeColorSpace = ColorSpace.singletons.gray;
  6209. var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);
  6210. var color = Util.makeCssRgb(rgbColor);
  6211. this.ctx.strokeStyle = color;
  6212. this.current.strokeColor = color;
  6213. },
  6214. setFillGray: function CanvasGraphics_setFillGray(gray) {
  6215. this.current.fillColorSpace = ColorSpace.singletons.gray;
  6216. var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);
  6217. var color = Util.makeCssRgb(rgbColor);
  6218. this.ctx.fillStyle = color;
  6219. this.current.fillColor = color;
  6220. },
  6221. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  6222. this.current.strokeColorSpace = ColorSpace.singletons.rgb;
  6223. var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);
  6224. var color = Util.makeCssRgb(rgbColor);
  6225. this.ctx.strokeStyle = color;
  6226. this.current.strokeColor = color;
  6227. },
  6228. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  6229. this.current.fillColorSpace = ColorSpace.singletons.rgb;
  6230. var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);
  6231. var color = Util.makeCssRgb(rgbColor);
  6232. this.ctx.fillStyle = color;
  6233. this.current.fillColor = color;
  6234. },
  6235. setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) {
  6236. this.current.strokeColorSpace = ColorSpace.singletons.cmyk;
  6237. var color = Util.makeCssCmyk(arguments);
  6238. this.ctx.strokeStyle = color;
  6239. this.current.strokeColor = color;
  6240. },
  6241. setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) {
  6242. this.current.fillColorSpace = ColorSpace.singletons.cmyk;
  6243. var color = Util.makeCssCmyk(arguments);
  6244. this.ctx.fillStyle = color;
  6245. this.current.fillColor = color;
  6246. },
  6247. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  6248. var ctx = this.ctx;
  6249. this.save();
  6250. var pattern = getShadingPatternFromIR(patternIR);
  6251. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  6252. var inv = ctx.mozCurrentTransformInverse;
  6253. if (inv) {
  6254. var canvas = ctx.canvas;
  6255. var width = canvas.width;
  6256. var height = canvas.height;
  6257. var bl = Util.applyTransform([0, 0], inv);
  6258. var br = Util.applyTransform([0, height], inv);
  6259. var ul = Util.applyTransform([width, 0], inv);
  6260. var ur = Util.applyTransform([width, height], inv);
  6261. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6262. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6263. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6264. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6265. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6266. } else {
  6267. // HACK to draw the gradient onto an infinite rectangle.
  6268. // PDF gradients are drawn across the entire image while
  6269. // Canvas only allows gradients to be drawn in a rectangle
  6270. // The following bug should allow us to remove this.
  6271. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  6272. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6273. }
  6274. this.restore();
  6275. },
  6276. // Images
  6277. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  6278. error('Should not call beginInlineImage');
  6279. },
  6280. beginImageData: function CanvasGraphics_beginImageData() {
  6281. error('Should not call beginImageData');
  6282. },
  6283. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  6284. bbox) {
  6285. this.save();
  6286. this.baseTransformStack.push(this.baseTransform);
  6287. if (matrix && isArray(matrix) && 6 == matrix.length) {
  6288. this.transform.apply(this, matrix);
  6289. }
  6290. this.baseTransform = this.ctx.mozCurrentTransform;
  6291. if (bbox && isArray(bbox) && 4 == bbox.length) {
  6292. var width = bbox[2] - bbox[0];
  6293. var height = bbox[3] - bbox[1];
  6294. this.rectangle(bbox[0], bbox[1], width, height);
  6295. this.clip();
  6296. this.endPath();
  6297. }
  6298. },
  6299. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  6300. this.restore();
  6301. this.baseTransform = this.baseTransformStack.pop();
  6302. },
  6303. beginGroup: function CanvasGraphics_beginGroup(group) {
  6304. this.save();
  6305. var currentCtx = this.ctx;
  6306. // TODO non-isolated groups - according to Rik at adobe non-isolated
  6307. // group results aren't usually that different and they even have tools
  6308. // that ignore this setting. Notes from Rik on implmenting:
  6309. // - When you encounter an transparency group, create a new canvas with
  6310. // the dimensions of the bbox
  6311. // - copy the content from the previous canvas to the new canvas
  6312. // - draw as usual
  6313. // - remove the backdrop alpha:
  6314. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  6315. // value of your transparency group and 'alphaBackdrop' the alpha of the
  6316. // backdrop
  6317. // - remove background color:
  6318. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  6319. if (!group.isolated) {
  6320. info('TODO: Support non-isolated groups.');
  6321. }
  6322. // TODO knockout - supposedly possible with the clever use of compositing
  6323. // modes.
  6324. if (group.knockout) {
  6325. warn('Knockout groups not supported.');
  6326. }
  6327. var currentTransform = currentCtx.mozCurrentTransform;
  6328. if (group.matrix) {
  6329. currentCtx.transform.apply(currentCtx, group.matrix);
  6330. }
  6331. assert(group.bbox, 'Bounding box is required.');
  6332. // Based on the current transform figure out how big the bounding box
  6333. // will actually be.
  6334. var bounds = Util.getAxialAlignedBoundingBox(
  6335. group.bbox,
  6336. currentCtx.mozCurrentTransform);
  6337. // Clip the bounding box to the current canvas.
  6338. var canvasBounds = [0,
  6339. 0,
  6340. currentCtx.canvas.width,
  6341. currentCtx.canvas.height];
  6342. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6343. // Use ceil in case we're between sizes so we don't create canvas that is
  6344. // too small and make the canvas at least 1x1 pixels.
  6345. var offsetX = Math.floor(bounds[0]);
  6346. var offsetY = Math.floor(bounds[1]);
  6347. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6348. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6349. var scaleX = 1, scaleY = 1;
  6350. if (drawnWidth > MAX_GROUP_SIZE) {
  6351. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6352. drawnWidth = MAX_GROUP_SIZE;
  6353. }
  6354. if (drawnHeight > MAX_GROUP_SIZE) {
  6355. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6356. drawnHeight = MAX_GROUP_SIZE;
  6357. }
  6358. var cacheId = 'groupAt' + this.groupLevel;
  6359. if (group.smask) {
  6360. // Using two cache entries is case if masks are used one after another.
  6361. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  6362. }
  6363. var scratchCanvas = CachedCanvases.getCanvas(
  6364. cacheId, drawnWidth, drawnHeight, true);
  6365. var groupCtx = scratchCanvas.context;
  6366. // Since we created a new canvas that is just the size of the bounding box
  6367. // we have to translate the group ctx.
  6368. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6369. groupCtx.translate(-offsetX, -offsetY);
  6370. groupCtx.transform.apply(groupCtx, currentTransform);
  6371. if (group.smask) {
  6372. // Saving state and cached mask to be used in setGState.
  6373. this.smaskStack.push({
  6374. canvas: scratchCanvas.canvas,
  6375. context: groupCtx,
  6376. offsetX: offsetX,
  6377. offsetY: offsetY,
  6378. scaleX: scaleX,
  6379. scaleY: scaleY,
  6380. subtype: group.smask.subtype,
  6381. backdrop: group.smask.backdrop,
  6382. colorSpace: group.colorSpace && ColorSpace.fromIR(group.colorSpace)
  6383. });
  6384. } else {
  6385. // Setup the current ctx so when the group is popped we draw it at the
  6386. // right location.
  6387. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6388. currentCtx.translate(offsetX, offsetY);
  6389. currentCtx.scale(scaleX, scaleY);
  6390. }
  6391. // The transparency group inherits all off the current graphics state
  6392. // except the blend mode, soft mask, and alpha constants.
  6393. copyCtxState(currentCtx, groupCtx);
  6394. this.ctx = groupCtx;
  6395. this.setGState([
  6396. ['BM', 'Normal'],
  6397. ['ca', 1],
  6398. ['CA', 1]
  6399. ]);
  6400. this.groupStack.push(currentCtx);
  6401. this.groupLevel++;
  6402. },
  6403. endGroup: function CanvasGraphics_endGroup(group) {
  6404. this.groupLevel--;
  6405. var groupCtx = this.ctx;
  6406. this.ctx = this.groupStack.pop();
  6407. // Turn off image smoothing to avoid sub pixel interpolation which can
  6408. // look kind of blurry for some pdfs.
  6409. if (this.ctx.imageSmoothingEnabled !== undefined) {
  6410. this.ctx.imageSmoothingEnabled = false;
  6411. } else {
  6412. this.ctx.mozImageSmoothingEnabled = false;
  6413. }
  6414. if (group.smask) {
  6415. this.tempSMask = this.smaskStack.pop();
  6416. } else {
  6417. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6418. }
  6419. this.restore();
  6420. },
  6421. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  6422. this.save();
  6423. this.current = new CanvasExtraState();
  6424. },
  6425. endAnnotations: function CanvasGraphics_endAnnotations() {
  6426. this.restore();
  6427. },
  6428. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  6429. matrix) {
  6430. this.save();
  6431. if (rect && isArray(rect) && 4 == rect.length) {
  6432. var width = rect[2] - rect[0];
  6433. var height = rect[3] - rect[1];
  6434. this.rectangle(rect[0], rect[1], width, height);
  6435. this.clip();
  6436. this.endPath();
  6437. }
  6438. this.transform.apply(this, transform);
  6439. this.transform.apply(this, matrix);
  6440. },
  6441. endAnnotation: function CanvasGraphics_endAnnotation() {
  6442. this.restore();
  6443. },
  6444. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  6445. var domImage = this.objs.get(objId);
  6446. if (!domImage) {
  6447. warn('Dependent image isn\'t ready yet');
  6448. return;
  6449. }
  6450. this.save();
  6451. var ctx = this.ctx;
  6452. // scale the image to the unit square
  6453. ctx.scale(1 / w, -1 / h);
  6454. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  6455. 0, -h, w, h);
  6456. if (this.imageLayer) {
  6457. var currentTransform = ctx.mozCurrentTransformInverse;
  6458. var position = this.getCanvasPosition(0, 0);
  6459. this.imageLayer.appendImage({
  6460. objId: objId,
  6461. left: position[0],
  6462. top: position[1],
  6463. width: w / currentTransform[0],
  6464. height: h / currentTransform[3]
  6465. });
  6466. }
  6467. this.restore();
  6468. },
  6469. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  6470. var ctx = this.ctx;
  6471. var width = img.width, height = img.height;
  6472. var glyph = this.processingType3;
  6473. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  6474. var MAX_SIZE_TO_COMPILE = 1000;
  6475. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  6476. glyph.compiled =
  6477. compileType3Glyph({data: img.data, width: width, height: height});
  6478. } else {
  6479. glyph.compiled = null;
  6480. }
  6481. }
  6482. if (glyph && glyph.compiled) {
  6483. glyph.compiled(ctx);
  6484. return;
  6485. }
  6486. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6487. var maskCtx = maskCanvas.context;
  6488. maskCtx.save();
  6489. putBinaryImageMask(maskCtx, img);
  6490. maskCtx.globalCompositeOperation = 'source-in';
  6491. var fillColor = this.current.fillColor;
  6492. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6493. fillColor.type === 'Pattern') ?
  6494. fillColor.getPattern(maskCtx, this) : fillColor;
  6495. maskCtx.fillRect(0, 0, width, height);
  6496. maskCtx.restore();
  6497. this.paintInlineImageXObject(maskCanvas.canvas);
  6498. },
  6499. paintImageMaskXObjectRepeat:
  6500. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  6501. scaleY, positions) {
  6502. var width = imgData.width;
  6503. var height = imgData.height;
  6504. var ctx = this.ctx;
  6505. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6506. var maskCtx = maskCanvas.context;
  6507. maskCtx.save();
  6508. putBinaryImageMask(maskCtx, imgData);
  6509. maskCtx.globalCompositeOperation = 'source-in';
  6510. var fillColor = this.current.fillColor;
  6511. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6512. fillColor.type === 'Pattern') ?
  6513. fillColor.getPattern(maskCtx, this) : fillColor;
  6514. maskCtx.fillRect(0, 0, width, height);
  6515. maskCtx.restore();
  6516. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  6517. ctx.save();
  6518. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  6519. ctx.scale(1, -1);
  6520. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  6521. 0, -1, 1, 1);
  6522. ctx.restore();
  6523. }
  6524. },
  6525. paintImageMaskXObjectGroup:
  6526. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  6527. var ctx = this.ctx;
  6528. for (var i = 0, ii = images.length; i < ii; i++) {
  6529. var image = images[i];
  6530. var width = image.width, height = image.height;
  6531. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6532. var maskCtx = maskCanvas.context;
  6533. maskCtx.save();
  6534. putBinaryImageMask(maskCtx, image);
  6535. maskCtx.globalCompositeOperation = 'source-in';
  6536. var fillColor = this.current.fillColor;
  6537. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6538. fillColor.type === 'Pattern') ?
  6539. fillColor.getPattern(maskCtx, this) : fillColor;
  6540. maskCtx.fillRect(0, 0, width, height);
  6541. maskCtx.restore();
  6542. ctx.save();
  6543. ctx.transform.apply(ctx, image.transform);
  6544. ctx.scale(1, -1);
  6545. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  6546. 0, -1, 1, 1);
  6547. ctx.restore();
  6548. }
  6549. },
  6550. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  6551. var imgData = this.objs.get(objId);
  6552. if (!imgData) {
  6553. warn('Dependent image isn\'t ready yet');
  6554. return;
  6555. }
  6556. this.paintInlineImageXObject(imgData);
  6557. },
  6558. paintImageXObjectRepeat:
  6559. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  6560. positions) {
  6561. var imgData = this.objs.get(objId);
  6562. if (!imgData) {
  6563. warn('Dependent image isn\'t ready yet');
  6564. return;
  6565. }
  6566. var width = imgData.width;
  6567. var height = imgData.height;
  6568. var map = [];
  6569. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  6570. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  6571. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  6572. }
  6573. this.paintInlineImageXObjectGroup(imgData, map);
  6574. },
  6575. paintInlineImageXObject:
  6576. function CanvasGraphics_paintInlineImageXObject(imgData) {
  6577. var width = imgData.width;
  6578. var height = imgData.height;
  6579. var ctx = this.ctx;
  6580. this.save();
  6581. // scale the image to the unit square
  6582. ctx.scale(1 / width, -1 / height);
  6583. var currentTransform = ctx.mozCurrentTransformInverse;
  6584. var a = currentTransform[0], b = currentTransform[1];
  6585. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  6586. var c = currentTransform[2], d = currentTransform[3];
  6587. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  6588. var imgToPaint, tmpCanvas;
  6589. // instanceof HTMLElement does not work in jsdom node.js module
  6590. if (imgData instanceof HTMLElement || !imgData.data) {
  6591. imgToPaint = imgData;
  6592. } else {
  6593. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  6594. var tmpCtx = tmpCanvas.context;
  6595. putBinaryImageData(tmpCtx, imgData);
  6596. imgToPaint = tmpCanvas.canvas;
  6597. }
  6598. var paintWidth = width, paintHeight = height;
  6599. var tmpCanvasId = 'prescale1';
  6600. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  6601. // pixels during drawImage operation, painting on the temporary canvas(es)
  6602. // that are twice smaller in size
  6603. while ((widthScale > 2 && paintWidth > 1) ||
  6604. (heightScale > 2 && paintHeight > 1)) {
  6605. var newWidth = paintWidth, newHeight = paintHeight;
  6606. if (widthScale > 2 && paintWidth > 1) {
  6607. newWidth = Math.ceil(paintWidth / 2);
  6608. widthScale /= paintWidth / newWidth;
  6609. }
  6610. if (heightScale > 2 && paintHeight > 1) {
  6611. newHeight = Math.ceil(paintHeight / 2);
  6612. heightScale /= paintHeight / newHeight;
  6613. }
  6614. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  6615. tmpCtx = tmpCanvas.context;
  6616. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  6617. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  6618. 0, 0, newWidth, newHeight);
  6619. imgToPaint = tmpCanvas.canvas;
  6620. paintWidth = newWidth;
  6621. paintHeight = newHeight;
  6622. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  6623. }
  6624. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  6625. 0, -height, width, height);
  6626. if (this.imageLayer) {
  6627. var position = this.getCanvasPosition(0, -height);
  6628. this.imageLayer.appendImage({
  6629. imgData: imgData,
  6630. left: position[0],
  6631. top: position[1],
  6632. width: width / currentTransform[0],
  6633. height: height / currentTransform[3]
  6634. });
  6635. }
  6636. this.restore();
  6637. },
  6638. paintInlineImageXObjectGroup:
  6639. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  6640. var ctx = this.ctx;
  6641. var w = imgData.width;
  6642. var h = imgData.height;
  6643. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  6644. var tmpCtx = tmpCanvas.context;
  6645. putBinaryImageData(tmpCtx, imgData);
  6646. for (var i = 0, ii = map.length; i < ii; i++) {
  6647. var entry = map[i];
  6648. ctx.save();
  6649. ctx.transform.apply(ctx, entry.transform);
  6650. ctx.scale(1, -1);
  6651. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  6652. 0, -1, 1, 1);
  6653. if (this.imageLayer) {
  6654. var position = this.getCanvasPosition(entry.x, entry.y);
  6655. this.imageLayer.appendImage({
  6656. imgData: imgData,
  6657. left: position[0],
  6658. top: position[1],
  6659. width: w,
  6660. height: h
  6661. });
  6662. }
  6663. ctx.restore();
  6664. }
  6665. },
  6666. paintSolidColorImageMask:
  6667. function CanvasGraphics_paintSolidColorImageMask() {
  6668. this.ctx.fillRect(0, 0, 1, 1);
  6669. },
  6670. // Marked content
  6671. markPoint: function CanvasGraphics_markPoint(tag) {
  6672. // TODO Marked content.
  6673. },
  6674. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  6675. // TODO Marked content.
  6676. },
  6677. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  6678. // TODO Marked content.
  6679. },
  6680. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  6681. tag, properties) {
  6682. // TODO Marked content.
  6683. },
  6684. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  6685. // TODO Marked content.
  6686. },
  6687. // Compatibility
  6688. beginCompat: function CanvasGraphics_beginCompat() {
  6689. // TODO ignore undefined operators (should we do that anyway?)
  6690. },
  6691. endCompat: function CanvasGraphics_endCompat() {
  6692. // TODO stop ignoring undefined operators
  6693. },
  6694. // Helper functions
  6695. consumePath: function CanvasGraphics_consumePath() {
  6696. var ctx = this.ctx;
  6697. if (this.pendingClip) {
  6698. if (this.pendingClip == EO_CLIP) {
  6699. if (ctx.mozFillRule !== undefined) {
  6700. ctx.mozFillRule = 'evenodd';
  6701. ctx.clip();
  6702. ctx.mozFillRule = 'nonzero';
  6703. } else {
  6704. try {
  6705. ctx.clip('evenodd');
  6706. } catch (ex) {
  6707. // shouldn't really happen, but browsers might think differently
  6708. ctx.clip();
  6709. }
  6710. }
  6711. } else {
  6712. ctx.clip();
  6713. }
  6714. this.pendingClip = null;
  6715. }
  6716. ctx.beginPath();
  6717. },
  6718. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  6719. var inverse = this.ctx.mozCurrentTransformInverse;
  6720. // max of the current horizontal and vertical scale
  6721. return Math.sqrt(Math.max(
  6722. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  6723. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  6724. },
  6725. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  6726. var transform = this.ctx.mozCurrentTransform;
  6727. return [
  6728. transform[0] * x + transform[2] * y + transform[4],
  6729. transform[1] * x + transform[3] * y + transform[5]
  6730. ];
  6731. }
  6732. };
  6733. for (var op in OPS) {
  6734. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  6735. }
  6736. return CanvasGraphics;
  6737. })();
  6738. var WebGLUtils = (function WebGLUtilsClosure() {
  6739. function loadShader(gl, code, shaderType) {
  6740. var shader = gl.createShader(shaderType);
  6741. gl.shaderSource(shader, code);
  6742. gl.compileShader(shader);
  6743. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  6744. if (!compiled) {
  6745. var errorMsg = gl.getShaderInfoLog(shader);
  6746. throw new Error('Error during shader compilation: ' + errorMsg);
  6747. }
  6748. return shader;
  6749. }
  6750. function createVertexShader(gl, code) {
  6751. return loadShader(gl, code, gl.VERTEX_SHADER);
  6752. }
  6753. function createFragmentShader(gl, code) {
  6754. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  6755. }
  6756. function createProgram(gl, shaders) {
  6757. var program = gl.createProgram();
  6758. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  6759. gl.attachShader(program, shaders[i]);
  6760. }
  6761. gl.linkProgram(program);
  6762. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  6763. if (!linked) {
  6764. var errorMsg = gl.getProgramInfoLog(program);
  6765. throw new Error('Error during program linking: ' + errorMsg);
  6766. }
  6767. return program;
  6768. }
  6769. function createTexture(gl, image, textureId) {
  6770. gl.activeTexture(textureId);
  6771. var texture = gl.createTexture();
  6772. gl.bindTexture(gl.TEXTURE_2D, texture);
  6773. // Set the parameters so we can render any size image.
  6774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6778. // Upload the image into the texture.
  6779. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  6780. return texture;
  6781. }
  6782. var currentGL, currentCanvas;
  6783. function generageGL() {
  6784. if (currentGL) {
  6785. return;
  6786. }
  6787. currentCanvas = document.createElement('canvas');
  6788. currentGL = currentCanvas.getContext('webgl',
  6789. { premultipliedalpha: false });
  6790. }
  6791. var smaskVertexShaderCode = '\
  6792. attribute vec2 a_position; \
  6793. attribute vec2 a_texCoord; \
  6794. \
  6795. uniform vec2 u_resolution; \
  6796. \
  6797. varying vec2 v_texCoord; \
  6798. \
  6799. void main() { \
  6800. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  6801. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  6802. \
  6803. v_texCoord = a_texCoord; \
  6804. } ';
  6805. var smaskFragmentShaderCode = '\
  6806. precision mediump float; \
  6807. \
  6808. uniform vec4 u_backdrop; \
  6809. uniform int u_subtype; \
  6810. uniform sampler2D u_image; \
  6811. uniform sampler2D u_mask; \
  6812. \
  6813. varying vec2 v_texCoord; \
  6814. \
  6815. void main() { \
  6816. vec4 imageColor = texture2D(u_image, v_texCoord); \
  6817. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  6818. if (u_backdrop.a > 0.0) { \
  6819. maskColor.rgb = maskColor.rgb * maskColor.a + \
  6820. u_backdrop.rgb * (1.0 - maskColor.a); \
  6821. } \
  6822. float lum; \
  6823. if (u_subtype == 0) { \
  6824. lum = maskColor.a; \
  6825. } else { \
  6826. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  6827. maskColor.b * 0.11; \
  6828. } \
  6829. imageColor.a *= lum; \
  6830. imageColor.rgb *= imageColor.a; \
  6831. gl_FragColor = imageColor; \
  6832. } ';
  6833. var smaskCache = null;
  6834. function initSmaskGL() {
  6835. var canvas, gl;
  6836. generageGL();
  6837. canvas = currentCanvas;
  6838. currentCanvas = null;
  6839. gl = currentGL;
  6840. currentGL = null;
  6841. // setup a GLSL program
  6842. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  6843. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  6844. var program = createProgram(gl, [vertexShader, fragmentShader]);
  6845. gl.useProgram(program);
  6846. var cache = {};
  6847. cache.gl = gl;
  6848. cache.canvas = canvas;
  6849. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  6850. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  6851. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  6852. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  6853. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  6854. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  6855. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  6856. // provide texture coordinates for the rectangle.
  6857. var texCoordBuffer = gl.createBuffer();
  6858. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  6859. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  6860. 0.0, 0.0,
  6861. 1.0, 0.0,
  6862. 0.0, 1.0,
  6863. 0.0, 1.0,
  6864. 1.0, 0.0,
  6865. 1.0, 1.0]), gl.STATIC_DRAW);
  6866. gl.enableVertexAttribArray(texCoordLocation);
  6867. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  6868. gl.uniform1i(texLayerLocation, 0);
  6869. gl.uniform1i(texMaskLocation, 1);
  6870. smaskCache = cache;
  6871. }
  6872. function composeSMask(layer, mask, properties) {
  6873. var width = layer.width, height = layer.height;
  6874. if (!smaskCache) {
  6875. initSmaskGL();
  6876. }
  6877. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  6878. canvas.width = width;
  6879. canvas.height = height;
  6880. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  6881. gl.uniform2f(cache.resolutionLocation, width, height);
  6882. if (properties.backdrop) {
  6883. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  6884. properties.backdrop[1], properties.backdrop[2], 1);
  6885. } else {
  6886. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  6887. }
  6888. gl.uniform1i(cache.subtypeLocation,
  6889. properties.subtype === 'Luminosity' ? 1 : 0);
  6890. // Create a textures
  6891. var texture = createTexture(gl, layer, gl.TEXTURE0);
  6892. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  6893. // Create a buffer and put a single clipspace rectangle in
  6894. // it (2 triangles)
  6895. var buffer = gl.createBuffer();
  6896. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  6897. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  6898. 0, 0,
  6899. width, 0,
  6900. 0, height,
  6901. 0, height,
  6902. width, 0,
  6903. width, height]), gl.STATIC_DRAW);
  6904. gl.enableVertexAttribArray(cache.positionLocation);
  6905. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  6906. // draw
  6907. gl.clearColor(0, 0, 0, 0);
  6908. gl.enable(gl.BLEND);
  6909. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  6910. gl.clear(gl.COLOR_BUFFER_BIT);
  6911. gl.drawArrays(gl.TRIANGLES, 0, 6);
  6912. gl.flush();
  6913. gl.deleteTexture(texture);
  6914. gl.deleteTexture(maskTexture);
  6915. gl.deleteBuffer(buffer);
  6916. return canvas;
  6917. }
  6918. var figuresVertexShaderCode = '\
  6919. attribute vec2 a_position; \
  6920. attribute vec3 a_color; \
  6921. \
  6922. uniform vec2 u_resolution; \
  6923. uniform vec2 u_scale; \
  6924. uniform vec2 u_offset; \
  6925. \
  6926. varying vec4 v_color; \
  6927. \
  6928. void main() { \
  6929. vec2 position = (a_position + u_offset) * u_scale; \
  6930. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  6931. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  6932. \
  6933. v_color = vec4(a_color / 255.0, 1.0); \
  6934. } ';
  6935. var figuresFragmentShaderCode = '\
  6936. precision mediump float; \
  6937. \
  6938. varying vec4 v_color; \
  6939. \
  6940. void main() { \
  6941. gl_FragColor = v_color; \
  6942. } ';
  6943. var figuresCache = null;
  6944. function initFiguresGL() {
  6945. var canvas, gl;
  6946. generageGL();
  6947. canvas = currentCanvas;
  6948. currentCanvas = null;
  6949. gl = currentGL;
  6950. currentGL = null;
  6951. // setup a GLSL program
  6952. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  6953. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  6954. var program = createProgram(gl, [vertexShader, fragmentShader]);
  6955. gl.useProgram(program);
  6956. var cache = {};
  6957. cache.gl = gl;
  6958. cache.canvas = canvas;
  6959. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  6960. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  6961. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  6962. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  6963. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  6964. figuresCache = cache;
  6965. }
  6966. function drawFigures(width, height, backgroundColor, figures, context) {
  6967. if (!figuresCache) {
  6968. initFiguresGL();
  6969. }
  6970. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  6971. canvas.width = width;
  6972. canvas.height = height;
  6973. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  6974. gl.uniform2f(cache.resolutionLocation, width, height);
  6975. // count triangle points
  6976. var count = 0;
  6977. var i, ii, rows;
  6978. for (i = 0, ii = figures.length; i < ii; i++) {
  6979. switch (figures[i].type) {
  6980. case 'lattice':
  6981. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  6982. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  6983. break;
  6984. case 'triangles':
  6985. count += figures[i].coords.length;
  6986. break;
  6987. }
  6988. }
  6989. // transfer data
  6990. var coords = new Float32Array(count * 2);
  6991. var colors = new Uint8Array(count * 3);
  6992. var coordsMap = context.coords, colorsMap = context.colors;
  6993. var pIndex = 0, cIndex = 0;
  6994. for (i = 0, ii = figures.length; i < ii; i++) {
  6995. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  6996. switch (figure.type) {
  6997. case 'lattice':
  6998. var cols = figure.verticesPerRow;
  6999. rows = (ps.length / cols) | 0;
  7000. for (var row = 1; row < rows; row++) {
  7001. var offset = row * cols + 1;
  7002. for (var col = 1; col < cols; col++, offset++) {
  7003. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  7004. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  7005. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  7006. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  7007. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  7008. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  7009. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  7010. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  7011. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  7012. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  7013. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  7014. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  7015. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  7016. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  7017. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  7018. coords[pIndex + 6] = coords[pIndex + 2];
  7019. coords[pIndex + 7] = coords[pIndex + 3];
  7020. coords[pIndex + 8] = coords[pIndex + 4];
  7021. coords[pIndex + 9] = coords[pIndex + 5];
  7022. coords[pIndex + 10] = coordsMap[ps[offset]];
  7023. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  7024. colors[cIndex + 9] = colors[cIndex + 3];
  7025. colors[cIndex + 10] = colors[cIndex + 4];
  7026. colors[cIndex + 11] = colors[cIndex + 5];
  7027. colors[cIndex + 12] = colors[cIndex + 6];
  7028. colors[cIndex + 13] = colors[cIndex + 7];
  7029. colors[cIndex + 14] = colors[cIndex + 8];
  7030. colors[cIndex + 15] = colorsMap[cs[offset]];
  7031. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  7032. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  7033. pIndex += 12;
  7034. cIndex += 18;
  7035. }
  7036. }
  7037. break;
  7038. case 'triangles':
  7039. for (var j = 0, jj = ps.length; j < jj; j++) {
  7040. coords[pIndex] = coordsMap[ps[j]];
  7041. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  7042. colors[cIndex] = colorsMap[cs[i]];
  7043. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  7044. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  7045. pIndex += 2;
  7046. cIndex += 3;
  7047. }
  7048. break;
  7049. }
  7050. }
  7051. // draw
  7052. if (backgroundColor) {
  7053. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  7054. backgroundColor[2] / 255, 1.0);
  7055. } else {
  7056. gl.clearColor(0, 0, 0, 0);
  7057. }
  7058. gl.clear(gl.COLOR_BUFFER_BIT);
  7059. var coordsBuffer = gl.createBuffer();
  7060. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  7061. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  7062. gl.enableVertexAttribArray(cache.positionLocation);
  7063. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  7064. var colorsBuffer = gl.createBuffer();
  7065. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  7066. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  7067. gl.enableVertexAttribArray(cache.colorLocation);
  7068. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  7069. 0, 0);
  7070. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  7071. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  7072. gl.drawArrays(gl.TRIANGLES, 0, count);
  7073. gl.flush();
  7074. gl.deleteBuffer(coordsBuffer);
  7075. gl.deleteBuffer(colorsBuffer);
  7076. return canvas;
  7077. }
  7078. function cleanup() {
  7079. smaskCache = null;
  7080. figuresCache = null;
  7081. }
  7082. return {
  7083. get isEnabled() {
  7084. if (PDFJS.disableWebGL) {
  7085. return false;
  7086. }
  7087. var enabled = false;
  7088. try {
  7089. generageGL();
  7090. enabled = !!currentGL;
  7091. } catch (e) { }
  7092. return shadow(this, 'isEnabled', enabled);
  7093. },
  7094. composeSMask: composeSMask,
  7095. drawFigures: drawFigures,
  7096. clear: cleanup
  7097. };
  7098. })();
  7099. var ShadingIRs = {};
  7100. ShadingIRs.RadialAxial = {
  7101. fromIR: function RadialAxial_fromIR(raw) {
  7102. var type = raw[1];
  7103. var colorStops = raw[2];
  7104. var p0 = raw[3];
  7105. var p1 = raw[4];
  7106. var r0 = raw[5];
  7107. var r1 = raw[6];
  7108. return {
  7109. type: 'Pattern',
  7110. getPattern: function RadialAxial_getPattern(ctx) {
  7111. var grad;
  7112. if (type === 'axial') {
  7113. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  7114. } else if (type === 'radial') {
  7115. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  7116. }
  7117. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  7118. var c = colorStops[i];
  7119. grad.addColorStop(c[0], c[1]);
  7120. }
  7121. return grad;
  7122. }
  7123. };
  7124. }
  7125. };
  7126. var createMeshCanvas = (function createMeshCanvasClosure() {
  7127. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7128. // Very basic Gouraud-shaded triangle rasterization algorithm.
  7129. var coords = context.coords, colors = context.colors;
  7130. var bytes = data.data, rowSize = data.width * 4;
  7131. var tmp;
  7132. if (coords[p1 + 1] > coords[p2 + 1]) {
  7133. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  7134. }
  7135. if (coords[p2 + 1] > coords[p3 + 1]) {
  7136. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  7137. }
  7138. if (coords[p1 + 1] > coords[p2 + 1]) {
  7139. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  7140. }
  7141. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7142. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7143. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7144. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7145. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7146. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7147. if (y1 >= y3) {
  7148. return;
  7149. }
  7150. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  7151. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  7152. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  7153. var minY = Math.round(y1), maxY = Math.round(y3);
  7154. var xa, car, cag, cab;
  7155. var xb, cbr, cbg, cbb;
  7156. var k;
  7157. for (var y = minY; y <= maxY; y++) {
  7158. if (y < y2) {
  7159. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  7160. xa = x1 - (x1 - x2) * k;
  7161. car = c1r - (c1r - c2r) * k;
  7162. cag = c1g - (c1g - c2g) * k;
  7163. cab = c1b - (c1b - c2b) * k;
  7164. } else {
  7165. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  7166. xa = x2 - (x2 - x3) * k;
  7167. car = c2r - (c2r - c3r) * k;
  7168. cag = c2g - (c2g - c3g) * k;
  7169. cab = c2b - (c2b - c3b) * k;
  7170. }
  7171. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  7172. xb = x1 - (x1 - x3) * k;
  7173. cbr = c1r - (c1r - c3r) * k;
  7174. cbg = c1g - (c1g - c3g) * k;
  7175. cbb = c1b - (c1b - c3b) * k;
  7176. var x1_ = Math.round(Math.min(xa, xb));
  7177. var x2_ = Math.round(Math.max(xa, xb));
  7178. var j = rowSize * y + x1_ * 4;
  7179. for (var x = x1_; x <= x2_; x++) {
  7180. k = (xa - x) / (xa - xb);
  7181. k = k < 0 ? 0 : k > 1 ? 1 : k;
  7182. bytes[j++] = (car - (car - cbr) * k) | 0;
  7183. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  7184. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  7185. bytes[j++] = 255;
  7186. }
  7187. }
  7188. }
  7189. function drawFigure(data, figure, context) {
  7190. var ps = figure.coords;
  7191. var cs = figure.colors;
  7192. var i, ii;
  7193. switch (figure.type) {
  7194. case 'lattice':
  7195. var verticesPerRow = figure.verticesPerRow;
  7196. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  7197. var cols = verticesPerRow - 1;
  7198. for (i = 0; i < rows; i++) {
  7199. var q = i * verticesPerRow;
  7200. for (var j = 0; j < cols; j++, q++) {
  7201. drawTriangle(data, context,
  7202. ps[q], ps[q + 1], ps[q + verticesPerRow],
  7203. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7204. drawTriangle(data, context,
  7205. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  7206. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7207. }
  7208. }
  7209. break;
  7210. case 'triangles':
  7211. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7212. drawTriangle(data, context,
  7213. ps[i], ps[i + 1], ps[i + 2],
  7214. cs[i], cs[i + 1], cs[i + 2]);
  7215. }
  7216. break;
  7217. default:
  7218. error('illigal figure');
  7219. break;
  7220. }
  7221. }
  7222. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  7223. backgroundColor) {
  7224. // we will increase scale on some weird factor to let antialiasing take
  7225. // care of "rough" edges
  7226. var EXPECTED_SCALE = 1.1;
  7227. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  7228. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  7229. var offsetX = Math.floor(bounds[0]);
  7230. var offsetY = Math.floor(bounds[1]);
  7231. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  7232. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  7233. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  7234. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7235. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  7236. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7237. var scaleX = boundsWidth / width;
  7238. var scaleY = boundsHeight / height;
  7239. var context = {
  7240. coords: coords,
  7241. colors: colors,
  7242. offsetX: -offsetX,
  7243. offsetY: -offsetY,
  7244. scaleX: 1 / scaleX,
  7245. scaleY: 1 / scaleY
  7246. };
  7247. var canvas, tmpCanvas, i, ii;
  7248. if (WebGLUtils.isEnabled) {
  7249. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  7250. figures, context);
  7251. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  7252. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  7253. tmpCanvas.context.drawImage(canvas, 0, 0);
  7254. canvas = tmpCanvas.canvas;
  7255. } else {
  7256. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  7257. var tmpCtx = tmpCanvas.context;
  7258. var data = tmpCtx.createImageData(width, height);
  7259. if (backgroundColor) {
  7260. var bytes = data.data;
  7261. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  7262. bytes[i] = backgroundColor[0];
  7263. bytes[i + 1] = backgroundColor[1];
  7264. bytes[i + 2] = backgroundColor[2];
  7265. bytes[i + 3] = 255;
  7266. }
  7267. }
  7268. for (i = 0; i < figures.length; i++) {
  7269. drawFigure(data, figures[i], context);
  7270. }
  7271. tmpCtx.putImageData(data, 0, 0);
  7272. canvas = tmpCanvas.canvas;
  7273. }
  7274. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  7275. scaleX: scaleX, scaleY: scaleY};
  7276. }
  7277. return createMeshCanvas;
  7278. })();
  7279. ShadingIRs.Mesh = {
  7280. fromIR: function Mesh_fromIR(raw) {
  7281. //var type = raw[1];
  7282. var coords = raw[2];
  7283. var colors = raw[3];
  7284. var figures = raw[4];
  7285. var bounds = raw[5];
  7286. var matrix = raw[6];
  7287. //var bbox = raw[7];
  7288. var background = raw[8];
  7289. return {
  7290. type: 'Pattern',
  7291. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  7292. var combinedScale;
  7293. // Obtain scale from matrix and current transformation matrix.
  7294. if (shadingFill) {
  7295. combinedScale = Util.singularValueDecompose2dScale(
  7296. ctx.mozCurrentTransform);
  7297. } else {
  7298. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  7299. var curMatrixScale = Util.singularValueDecompose2dScale(
  7300. owner.baseTransform);
  7301. combinedScale = [matrixScale[0] * curMatrixScale[0],
  7302. matrixScale[1] * curMatrixScale[1]];
  7303. }
  7304. // Rasterizing on the main thread since sending/queue large canvases
  7305. // might cause OOM.
  7306. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  7307. coords, colors, figures, shadingFill ? null : background);
  7308. if (!shadingFill) {
  7309. ctx.setTransform.apply(ctx, owner.baseTransform);
  7310. if (matrix) {
  7311. ctx.transform.apply(ctx, matrix);
  7312. }
  7313. }
  7314. ctx.translate(temporaryPatternCanvas.offsetX,
  7315. temporaryPatternCanvas.offsetY);
  7316. ctx.scale(temporaryPatternCanvas.scaleX,
  7317. temporaryPatternCanvas.scaleY);
  7318. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  7319. }
  7320. };
  7321. }
  7322. };
  7323. ShadingIRs.Dummy = {
  7324. fromIR: function Dummy_fromIR() {
  7325. return {
  7326. type: 'Pattern',
  7327. getPattern: function Dummy_fromIR_getPattern() {
  7328. return 'hotpink';
  7329. }
  7330. };
  7331. }
  7332. };
  7333. function getShadingPatternFromIR(raw) {
  7334. var shadingIR = ShadingIRs[raw[0]];
  7335. if (!shadingIR) {
  7336. error('Unknown IR type: ' + raw[0]);
  7337. }
  7338. return shadingIR.fromIR(raw);
  7339. }
  7340. var TilingPattern = (function TilingPatternClosure() {
  7341. var PaintType = {
  7342. COLORED: 1,
  7343. UNCOLORED: 2
  7344. };
  7345. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  7346. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  7347. this.name = IR[1][0].name;
  7348. this.operatorList = IR[2];
  7349. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7350. this.bbox = IR[4];
  7351. this.xstep = IR[5];
  7352. this.ystep = IR[6];
  7353. this.paintType = IR[7];
  7354. this.tilingType = IR[8];
  7355. this.color = color;
  7356. this.objs = objs;
  7357. this.commonObjs = commonObjs;
  7358. this.baseTransform = baseTransform;
  7359. this.type = 'Pattern';
  7360. this.ctx = ctx;
  7361. }
  7362. TilingPattern.prototype = {
  7363. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  7364. var operatorList = this.operatorList;
  7365. var bbox = this.bbox;
  7366. var xstep = this.xstep;
  7367. var ystep = this.ystep;
  7368. var paintType = this.paintType;
  7369. var tilingType = this.tilingType;
  7370. var color = this.color;
  7371. var objs = this.objs;
  7372. var commonObjs = this.commonObjs;
  7373. info('TilingType: ' + tilingType);
  7374. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  7375. var topLeft = [x0, y0];
  7376. // we want the canvas to be as large as the step size
  7377. var botRight = [x0 + xstep, y0 + ystep];
  7378. var width = botRight[0] - topLeft[0];
  7379. var height = botRight[1] - topLeft[1];
  7380. // Obtain scale from matrix and current transformation matrix.
  7381. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  7382. var curMatrixScale = Util.singularValueDecompose2dScale(
  7383. this.baseTransform);
  7384. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  7385. matrixScale[1] * curMatrixScale[1]];
  7386. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  7387. // Use width and height values that are as close as possible to the end
  7388. // result when the pattern is used. Too low value makes the pattern look
  7389. // blurry. Too large value makes it look too crispy.
  7390. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  7391. MAX_PATTERN_SIZE);
  7392. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  7393. MAX_PATTERN_SIZE);
  7394. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  7395. var tmpCtx = tmpCanvas.context;
  7396. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  7397. graphics.groupLevel = owner.groupLevel;
  7398. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  7399. this.setScale(width, height, xstep, ystep);
  7400. this.transformToScale(graphics);
  7401. // transform coordinates to pattern space
  7402. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  7403. graphics.transform.apply(graphics, tmpTranslate);
  7404. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  7405. graphics.executeOperatorList(operatorList);
  7406. return tmpCanvas.canvas;
  7407. },
  7408. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  7409. this.scale = [width / xstep, height / ystep];
  7410. },
  7411. transformToScale: function TilingPattern_transformToScale(graphics) {
  7412. var scale = this.scale;
  7413. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  7414. graphics.transform.apply(graphics, tmpScale);
  7415. },
  7416. scaleToContext: function TilingPattern_scaleToContext() {
  7417. var scale = this.scale;
  7418. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  7419. },
  7420. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  7421. if (bbox && isArray(bbox) && 4 == bbox.length) {
  7422. var bboxWidth = x1 - x0;
  7423. var bboxHeight = y1 - y0;
  7424. graphics.rectangle(x0, y0, bboxWidth, bboxHeight);
  7425. graphics.clip();
  7426. graphics.endPath();
  7427. }
  7428. },
  7429. setFillAndStrokeStyleToContext:
  7430. function setFillAndStrokeStyleToContext(context, paintType, color) {
  7431. switch (paintType) {
  7432. case PaintType.COLORED:
  7433. var ctx = this.ctx;
  7434. context.fillStyle = ctx.fillStyle;
  7435. context.strokeStyle = ctx.strokeStyle;
  7436. break;
  7437. case PaintType.UNCOLORED:
  7438. var rgbColor = ColorSpace.singletons.rgb.getRgb(color, 0);
  7439. var cssColor = Util.makeCssRgb(rgbColor);
  7440. context.fillStyle = cssColor;
  7441. context.strokeStyle = cssColor;
  7442. break;
  7443. default:
  7444. error('Unsupported paint type: ' + paintType);
  7445. }
  7446. },
  7447. getPattern: function TilingPattern_getPattern(ctx, owner) {
  7448. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  7449. ctx = this.ctx;
  7450. ctx.setTransform.apply(ctx, this.baseTransform);
  7451. ctx.transform.apply(ctx, this.matrix);
  7452. this.scaleToContext();
  7453. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  7454. }
  7455. };
  7456. return TilingPattern;
  7457. })();
  7458. PDFJS.disableFontFace = false;
  7459. var FontLoader = {
  7460. insertRule: function fontLoaderInsertRule(rule) {
  7461. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  7462. if (!styleElement) {
  7463. styleElement = document.createElement('style');
  7464. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  7465. document.documentElement.getElementsByTagName('head')[0].appendChild(
  7466. styleElement);
  7467. }
  7468. var styleSheet = styleElement.sheet;
  7469. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  7470. },
  7471. clear: function fontLoaderClear() {
  7472. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  7473. if (styleElement) {
  7474. styleElement.parentNode.removeChild(styleElement);
  7475. }
  7476. },
  7477. get loadTestFont() {
  7478. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  7479. // height.
  7480. return shadow(this, 'loadTestFont', atob(
  7481. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  7482. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  7483. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  7484. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  7485. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  7486. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  7487. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  7488. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  7489. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  7490. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  7491. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  7492. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  7493. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  7494. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7495. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7496. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7497. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  7498. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  7499. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  7500. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  7501. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  7502. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  7503. ));
  7504. },
  7505. loadTestFontId: 0,
  7506. loadingContext: {
  7507. requests: [],
  7508. nextRequestId: 0
  7509. },
  7510. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  7511. if (isWorker) {
  7512. return false;
  7513. }
  7514. // User agent string sniffing is bad, but there is no reliable way to tell
  7515. // if font is fully loaded and ready to be used with canvas.
  7516. var userAgent = window.navigator.userAgent;
  7517. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  7518. if (m && m[1] >= 14) {
  7519. return true;
  7520. }
  7521. // TODO other browsers
  7522. return false;
  7523. })(),
  7524. bind: function fontLoaderBind(fonts, callback) {
  7525. assert(!isWorker, 'bind() shall be called from main thread');
  7526. var rules = [], fontsToLoad = [];
  7527. for (var i = 0, ii = fonts.length; i < ii; i++) {
  7528. var font = fonts[i];
  7529. // Add the font to the DOM only once or skip if the font
  7530. // is already loaded.
  7531. if (font.attached || font.loading === false) {
  7532. continue;
  7533. }
  7534. font.attached = true;
  7535. var rule = font.bindDOM();
  7536. if (rule) {
  7537. rules.push(rule);
  7538. fontsToLoad.push(font);
  7539. }
  7540. }
  7541. var request = FontLoader.queueLoadingCallback(callback);
  7542. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  7543. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  7544. } else {
  7545. request.complete();
  7546. }
  7547. },
  7548. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  7549. function LoadLoader_completeRequest() {
  7550. assert(!request.end, 'completeRequest() cannot be called twice');
  7551. request.end = Date.now();
  7552. // sending all completed requests in order how they were queued
  7553. while (context.requests.length > 0 && context.requests[0].end) {
  7554. var otherRequest = context.requests.shift();
  7555. setTimeout(otherRequest.callback, 0);
  7556. }
  7557. }
  7558. var context = FontLoader.loadingContext;
  7559. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  7560. var request = {
  7561. id: requestId,
  7562. complete: LoadLoader_completeRequest,
  7563. callback: callback,
  7564. started: Date.now()
  7565. };
  7566. context.requests.push(request);
  7567. return request;
  7568. },
  7569. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  7570. fonts,
  7571. request) {
  7572. /** Hack begin */
  7573. // There's currently no event when a font has finished downloading so the
  7574. // following code is a dirty hack to 'guess' when a font is
  7575. // ready. It's assumed fonts are loaded in order, so add a known test
  7576. // font after the desired fonts and then test for the loading of that
  7577. // test font.
  7578. function int32(data, offset) {
  7579. return (data.charCodeAt(offset) << 24) |
  7580. (data.charCodeAt(offset + 1) << 16) |
  7581. (data.charCodeAt(offset + 2) << 8) |
  7582. (data.charCodeAt(offset + 3) & 0xff);
  7583. }
  7584. function spliceString(s, offset, remove, insert) {
  7585. var chunk1 = s.substr(0, offset);
  7586. var chunk2 = s.substr(offset + remove);
  7587. return chunk1 + insert + chunk2;
  7588. }
  7589. var i, ii;
  7590. var canvas = document.createElement('canvas');
  7591. canvas.width = 1;
  7592. canvas.height = 1;
  7593. var ctx = canvas.getContext('2d');
  7594. var called = 0;
  7595. function isFontReady(name, callback) {
  7596. called++;
  7597. // With setTimeout clamping this gives the font ~100ms to load.
  7598. if(called > 30) {
  7599. warn('Load test font never loaded.');
  7600. callback();
  7601. return;
  7602. }
  7603. ctx.font = '30px ' + name;
  7604. ctx.fillText('.', 0, 20);
  7605. var imageData = ctx.getImageData(0, 0, 1, 1);
  7606. if (imageData.data[3] > 0) {
  7607. callback();
  7608. return;
  7609. }
  7610. setTimeout(isFontReady.bind(null, name, callback));
  7611. }
  7612. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  7613. // Chromium seems to cache fonts based on a hash of the actual font data,
  7614. // so the font must be modified for each load test else it will appear to
  7615. // be loaded already.
  7616. // TODO: This could maybe be made faster by avoiding the btoa of the full
  7617. // font by splitting it in chunks before hand and padding the font id.
  7618. var data = this.loadTestFont;
  7619. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  7620. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  7621. loadTestFontId);
  7622. // CFF checksum is important for IE, adjusting it
  7623. var CFF_CHECKSUM_OFFSET = 16;
  7624. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  7625. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  7626. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  7627. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  7628. }
  7629. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  7630. checksum = (checksum - XXXX_VALUE +
  7631. int32(loadTestFontId + 'XXX', i)) | 0;
  7632. }
  7633. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  7634. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  7635. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  7636. url + '}';
  7637. FontLoader.insertRule(rule);
  7638. var names = [];
  7639. for (i = 0, ii = fonts.length; i < ii; i++) {
  7640. names.push(fonts[i].loadedName);
  7641. }
  7642. names.push(loadTestFontId);
  7643. var div = document.createElement('div');
  7644. div.setAttribute('style',
  7645. 'visibility: hidden;' +
  7646. 'width: 10px; height: 10px;' +
  7647. 'position: absolute; top: 0px; left: 0px;');
  7648. for (i = 0, ii = names.length; i < ii; ++i) {
  7649. var span = document.createElement('span');
  7650. span.textContent = 'Hi';
  7651. span.style.fontFamily = names[i];
  7652. div.appendChild(span);
  7653. }
  7654. document.body.appendChild(div);
  7655. isFontReady(loadTestFontId, function() {
  7656. document.body.removeChild(div);
  7657. request.complete();
  7658. });
  7659. /** Hack end */
  7660. }
  7661. };
  7662. var FontFace = (function FontFaceClosure() {
  7663. function FontFace(name, file, properties) {
  7664. this.compiledGlyphs = {};
  7665. if (arguments.length === 1) {
  7666. // importing translated data
  7667. var data = arguments[0];
  7668. for (var i in data) {
  7669. this[i] = data[i];
  7670. }
  7671. return;
  7672. }
  7673. }
  7674. FontFace.prototype = {
  7675. bindDOM: function FontFace_bindDOM() {
  7676. if (!this.data) {
  7677. return null;
  7678. }
  7679. if (PDFJS.disableFontFace) {
  7680. this.disableFontFace = true;
  7681. return null;
  7682. }
  7683. var data = bytesToString(new Uint8Array(this.data));
  7684. var fontName = this.loadedName;
  7685. // Add the font-face rule to the document
  7686. var url = ('url(data:' + this.mimetype + ';base64,' +
  7687. window.btoa(data) + ');');
  7688. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  7689. FontLoader.insertRule(rule);
  7690. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  7691. globalScope['FontInspector'].enabled) {
  7692. globalScope['FontInspector'].fontAdded(this, url);
  7693. }
  7694. return rule;
  7695. },
  7696. getPathGenerator: function (objs, character) {
  7697. if (!(character in this.compiledGlyphs)) {
  7698. var js = objs.get(this.loadedName + '_path_' + character);
  7699. /*jshint -W054 */
  7700. this.compiledGlyphs[character] = new Function('c', 'size', js);
  7701. }
  7702. return this.compiledGlyphs[character];
  7703. }
  7704. };
  7705. return FontFace;
  7706. })();
  7707. }).call((typeof window === 'undefined') ? this : window);
  7708. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  7709. // workerSrc is not set -- using last script url to define default location
  7710. PDFJS.workerSrc = (function () {
  7711. 'use strict';
  7712. var scriptTagContainer = document.body ||
  7713. document.getElementsByTagName('head')[0];
  7714. var pdfjsSrc = scriptTagContainer.lastChild.src;
  7715. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  7716. })();
  7717. }