pdf.js 240 KB

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