pdf.js 359 KB

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