pdf.js 273 KB

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