pdf.js 248 KB

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