pdf.js 337 KB

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