pdf.js 239 KB

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