pdf.js 263 KB

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