pdf.js 300 KB

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