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