pdf.js 421 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555
  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. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/build/pdf', ['exports'], factory);
  19. } else if (typeof exports !== 'undefined') {
  20. factory(exports);
  21. } else {
  22. factory(root['pdfjsDistBuildPdf'] = {});
  23. }
  24. }(this, function (exports) {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. var pdfjsVersion = '1.6.258';
  28. var pdfjsBuild = '6906623';
  29. var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  30. var pdfjsLibs = {};
  31. (function pdfjsWrapper() {
  32. (function (root, factory) {
  33. factory(root.pdfjsSharedUtil = {});
  34. }(this, function (exports) {
  35. var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
  36. var FONT_IDENTITY_MATRIX = [
  37. 0.001,
  38. 0,
  39. 0,
  40. 0.001,
  41. 0,
  42. 0
  43. ];
  44. var TextRenderingMode = {
  45. FILL: 0,
  46. STROKE: 1,
  47. FILL_STROKE: 2,
  48. INVISIBLE: 3,
  49. FILL_ADD_TO_PATH: 4,
  50. STROKE_ADD_TO_PATH: 5,
  51. FILL_STROKE_ADD_TO_PATH: 6,
  52. ADD_TO_PATH: 7,
  53. FILL_STROKE_MASK: 3,
  54. ADD_TO_PATH_FLAG: 4
  55. };
  56. var ImageKind = {
  57. GRAYSCALE_1BPP: 1,
  58. RGB_24BPP: 2,
  59. RGBA_32BPP: 3
  60. };
  61. var AnnotationType = {
  62. TEXT: 1,
  63. LINK: 2,
  64. FREETEXT: 3,
  65. LINE: 4,
  66. SQUARE: 5,
  67. CIRCLE: 6,
  68. POLYGON: 7,
  69. POLYLINE: 8,
  70. HIGHLIGHT: 9,
  71. UNDERLINE: 10,
  72. SQUIGGLY: 11,
  73. STRIKEOUT: 12,
  74. STAMP: 13,
  75. CARET: 14,
  76. INK: 15,
  77. POPUP: 16,
  78. FILEATTACHMENT: 17,
  79. SOUND: 18,
  80. MOVIE: 19,
  81. WIDGET: 20,
  82. SCREEN: 21,
  83. PRINTERMARK: 22,
  84. TRAPNET: 23,
  85. WATERMARK: 24,
  86. THREED: 25,
  87. REDACT: 26
  88. };
  89. var AnnotationFlag = {
  90. INVISIBLE: 0x01,
  91. HIDDEN: 0x02,
  92. PRINT: 0x04,
  93. NOZOOM: 0x08,
  94. NOROTATE: 0x10,
  95. NOVIEW: 0x20,
  96. READONLY: 0x40,
  97. LOCKED: 0x80,
  98. TOGGLENOVIEW: 0x100,
  99. LOCKEDCONTENTS: 0x200
  100. };
  101. var AnnotationFieldFlag = {
  102. READONLY: 0x0000001,
  103. REQUIRED: 0x0000002,
  104. NOEXPORT: 0x0000004,
  105. MULTILINE: 0x0001000,
  106. PASSWORD: 0x0002000,
  107. NOTOGGLETOOFF: 0x0004000,
  108. RADIO: 0x0008000,
  109. PUSHBUTTON: 0x0010000,
  110. COMBO: 0x0020000,
  111. EDIT: 0x0040000,
  112. SORT: 0x0080000,
  113. FILESELECT: 0x0100000,
  114. MULTISELECT: 0x0200000,
  115. DONOTSPELLCHECK: 0x0400000,
  116. DONOTSCROLL: 0x0800000,
  117. COMB: 0x1000000,
  118. RICHTEXT: 0x2000000,
  119. RADIOSINUNISON: 0x2000000,
  120. COMMITONSELCHANGE: 0x4000000
  121. };
  122. var AnnotationBorderStyleType = {
  123. SOLID: 1,
  124. DASHED: 2,
  125. BEVELED: 3,
  126. INSET: 4,
  127. UNDERLINE: 5
  128. };
  129. var StreamType = {
  130. UNKNOWN: 0,
  131. FLATE: 1,
  132. LZW: 2,
  133. DCT: 3,
  134. JPX: 4,
  135. JBIG: 5,
  136. A85: 6,
  137. AHX: 7,
  138. CCF: 8,
  139. RL: 9
  140. };
  141. var FontType = {
  142. UNKNOWN: 0,
  143. TYPE1: 1,
  144. TYPE1C: 2,
  145. CIDFONTTYPE0: 3,
  146. CIDFONTTYPE0C: 4,
  147. TRUETYPE: 5,
  148. CIDFONTTYPE2: 6,
  149. TYPE3: 7,
  150. OPENTYPE: 8,
  151. TYPE0: 9,
  152. MMTYPE1: 10
  153. };
  154. var VERBOSITY_LEVELS = {
  155. errors: 0,
  156. warnings: 1,
  157. infos: 5
  158. };
  159. // All the possible operations for an operator list.
  160. var OPS = {
  161. // Intentionally start from 1 so it is easy to spot bad operators that will be
  162. // 0's.
  163. dependency: 1,
  164. setLineWidth: 2,
  165. setLineCap: 3,
  166. setLineJoin: 4,
  167. setMiterLimit: 5,
  168. setDash: 6,
  169. setRenderingIntent: 7,
  170. setFlatness: 8,
  171. setGState: 9,
  172. save: 10,
  173. restore: 11,
  174. transform: 12,
  175. moveTo: 13,
  176. lineTo: 14,
  177. curveTo: 15,
  178. curveTo2: 16,
  179. curveTo3: 17,
  180. closePath: 18,
  181. rectangle: 19,
  182. stroke: 20,
  183. closeStroke: 21,
  184. fill: 22,
  185. eoFill: 23,
  186. fillStroke: 24,
  187. eoFillStroke: 25,
  188. closeFillStroke: 26,
  189. closeEOFillStroke: 27,
  190. endPath: 28,
  191. clip: 29,
  192. eoClip: 30,
  193. beginText: 31,
  194. endText: 32,
  195. setCharSpacing: 33,
  196. setWordSpacing: 34,
  197. setHScale: 35,
  198. setLeading: 36,
  199. setFont: 37,
  200. setTextRenderingMode: 38,
  201. setTextRise: 39,
  202. moveText: 40,
  203. setLeadingMoveText: 41,
  204. setTextMatrix: 42,
  205. nextLine: 43,
  206. showText: 44,
  207. showSpacedText: 45,
  208. nextLineShowText: 46,
  209. nextLineSetSpacingShowText: 47,
  210. setCharWidth: 48,
  211. setCharWidthAndBounds: 49,
  212. setStrokeColorSpace: 50,
  213. setFillColorSpace: 51,
  214. setStrokeColor: 52,
  215. setStrokeColorN: 53,
  216. setFillColor: 54,
  217. setFillColorN: 55,
  218. setStrokeGray: 56,
  219. setFillGray: 57,
  220. setStrokeRGBColor: 58,
  221. setFillRGBColor: 59,
  222. setStrokeCMYKColor: 60,
  223. setFillCMYKColor: 61,
  224. shadingFill: 62,
  225. beginInlineImage: 63,
  226. beginImageData: 64,
  227. endInlineImage: 65,
  228. paintXObject: 66,
  229. markPoint: 67,
  230. markPointProps: 68,
  231. beginMarkedContent: 69,
  232. beginMarkedContentProps: 70,
  233. endMarkedContent: 71,
  234. beginCompat: 72,
  235. endCompat: 73,
  236. paintFormXObjectBegin: 74,
  237. paintFormXObjectEnd: 75,
  238. beginGroup: 76,
  239. endGroup: 77,
  240. beginAnnotations: 78,
  241. endAnnotations: 79,
  242. beginAnnotation: 80,
  243. endAnnotation: 81,
  244. paintJpegXObject: 82,
  245. paintImageMaskXObject: 83,
  246. paintImageMaskXObjectGroup: 84,
  247. paintImageXObject: 85,
  248. paintInlineImageXObject: 86,
  249. paintInlineImageXObjectGroup: 87,
  250. paintImageXObjectRepeat: 88,
  251. paintImageMaskXObjectRepeat: 89,
  252. paintSolidColorImageMask: 90,
  253. constructPath: 91
  254. };
  255. var verbosity = VERBOSITY_LEVELS.warnings;
  256. function setVerbosityLevel(level) {
  257. verbosity = level;
  258. }
  259. function getVerbosityLevel() {
  260. return verbosity;
  261. }
  262. // A notice for devs. These are good for things that are helpful to devs, such
  263. // as warning that Workers were disabled, which is important to devs but not
  264. // end users.
  265. function info(msg) {
  266. if (verbosity >= VERBOSITY_LEVELS.infos) {
  267. console.log('Info: ' + msg);
  268. }
  269. }
  270. // Non-fatal warnings.
  271. function warn(msg) {
  272. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  273. console.log('Warning: ' + msg);
  274. }
  275. }
  276. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  277. function deprecated(details) {
  278. console.log('Deprecated API usage: ' + details);
  279. }
  280. // Fatal errors that should trigger the fallback UI and halt execution by
  281. // throwing an exception.
  282. function error(msg) {
  283. if (verbosity >= VERBOSITY_LEVELS.errors) {
  284. console.log('Error: ' + msg);
  285. console.log(backtrace());
  286. }
  287. throw new Error(msg);
  288. }
  289. function backtrace() {
  290. try {
  291. throw new Error();
  292. } catch (e) {
  293. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  294. }
  295. }
  296. function assert(cond, msg) {
  297. if (!cond) {
  298. error(msg);
  299. }
  300. }
  301. var UNSUPPORTED_FEATURES = {
  302. unknown: 'unknown',
  303. forms: 'forms',
  304. javaScript: 'javaScript',
  305. smask: 'smask',
  306. shadingPattern: 'shadingPattern',
  307. font: 'font'
  308. };
  309. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  310. function isSameOrigin(baseUrl, otherUrl) {
  311. try {
  312. var base = new URL(baseUrl);
  313. if (!base.origin || base.origin === 'null') {
  314. return false;
  315. }
  316. } // non-HTTP url
  317. catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  324. function isValidUrl(url, allowRelative) {
  325. if (!url || typeof url !== 'string') {
  326. return false;
  327. }
  328. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  329. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  330. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  331. if (!protocol) {
  332. return allowRelative;
  333. }
  334. protocol = protocol[0].toLowerCase();
  335. switch (protocol) {
  336. case 'http':
  337. case 'https':
  338. case 'ftp':
  339. case 'mailto':
  340. case 'tel':
  341. return true;
  342. default:
  343. return false;
  344. }
  345. }
  346. function shadow(obj, prop, value) {
  347. Object.defineProperty(obj, prop, {
  348. value: value,
  349. enumerable: true,
  350. configurable: true,
  351. writable: false
  352. });
  353. return value;
  354. }
  355. function getLookupTableFactory(initializer) {
  356. var lookup;
  357. return function () {
  358. if (initializer) {
  359. lookup = Object.create(null);
  360. initializer(lookup);
  361. initializer = null;
  362. }
  363. return lookup;
  364. };
  365. }
  366. var PasswordResponses = {
  367. NEED_PASSWORD: 1,
  368. INCORRECT_PASSWORD: 2
  369. };
  370. var PasswordException = function PasswordExceptionClosure() {
  371. function PasswordException(msg, code) {
  372. this.name = 'PasswordException';
  373. this.message = msg;
  374. this.code = code;
  375. }
  376. PasswordException.prototype = new Error();
  377. PasswordException.constructor = PasswordException;
  378. return PasswordException;
  379. }();
  380. var UnknownErrorException = function UnknownErrorExceptionClosure() {
  381. function UnknownErrorException(msg, details) {
  382. this.name = 'UnknownErrorException';
  383. this.message = msg;
  384. this.details = details;
  385. }
  386. UnknownErrorException.prototype = new Error();
  387. UnknownErrorException.constructor = UnknownErrorException;
  388. return UnknownErrorException;
  389. }();
  390. var InvalidPDFException = function InvalidPDFExceptionClosure() {
  391. function InvalidPDFException(msg) {
  392. this.name = 'InvalidPDFException';
  393. this.message = msg;
  394. }
  395. InvalidPDFException.prototype = new Error();
  396. InvalidPDFException.constructor = InvalidPDFException;
  397. return InvalidPDFException;
  398. }();
  399. var MissingPDFException = function MissingPDFExceptionClosure() {
  400. function MissingPDFException(msg) {
  401. this.name = 'MissingPDFException';
  402. this.message = msg;
  403. }
  404. MissingPDFException.prototype = new Error();
  405. MissingPDFException.constructor = MissingPDFException;
  406. return MissingPDFException;
  407. }();
  408. var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
  409. function UnexpectedResponseException(msg, status) {
  410. this.name = 'UnexpectedResponseException';
  411. this.message = msg;
  412. this.status = status;
  413. }
  414. UnexpectedResponseException.prototype = new Error();
  415. UnexpectedResponseException.constructor = UnexpectedResponseException;
  416. return UnexpectedResponseException;
  417. }();
  418. var NotImplementedException = function NotImplementedExceptionClosure() {
  419. function NotImplementedException(msg) {
  420. this.message = msg;
  421. }
  422. NotImplementedException.prototype = new Error();
  423. NotImplementedException.prototype.name = 'NotImplementedException';
  424. NotImplementedException.constructor = NotImplementedException;
  425. return NotImplementedException;
  426. }();
  427. var MissingDataException = function MissingDataExceptionClosure() {
  428. function MissingDataException(begin, end) {
  429. this.begin = begin;
  430. this.end = end;
  431. this.message = 'Missing data [' + begin + ', ' + end + ')';
  432. }
  433. MissingDataException.prototype = new Error();
  434. MissingDataException.prototype.name = 'MissingDataException';
  435. MissingDataException.constructor = MissingDataException;
  436. return MissingDataException;
  437. }();
  438. var XRefParseException = function XRefParseExceptionClosure() {
  439. function XRefParseException(msg) {
  440. this.message = msg;
  441. }
  442. XRefParseException.prototype = new Error();
  443. XRefParseException.prototype.name = 'XRefParseException';
  444. XRefParseException.constructor = XRefParseException;
  445. return XRefParseException;
  446. }();
  447. var NullCharactersRegExp = /\x00/g;
  448. function removeNullCharacters(str) {
  449. if (typeof str !== 'string') {
  450. warn('The argument for removeNullCharacters must be a string.');
  451. return str;
  452. }
  453. return str.replace(NullCharactersRegExp, '');
  454. }
  455. function bytesToString(bytes) {
  456. assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
  457. var length = bytes.length;
  458. var MAX_ARGUMENT_COUNT = 8192;
  459. if (length < MAX_ARGUMENT_COUNT) {
  460. return String.fromCharCode.apply(null, bytes);
  461. }
  462. var strBuf = [];
  463. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  464. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  465. var chunk = bytes.subarray(i, chunkEnd);
  466. strBuf.push(String.fromCharCode.apply(null, chunk));
  467. }
  468. return strBuf.join('');
  469. }
  470. function stringToBytes(str) {
  471. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  472. var length = str.length;
  473. var bytes = new Uint8Array(length);
  474. for (var i = 0; i < length; ++i) {
  475. bytes[i] = str.charCodeAt(i) & 0xFF;
  476. }
  477. return bytes;
  478. }
  479. /**
  480. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  481. * @param {Array|Uint8Array|string} arr
  482. * @returns {number}
  483. */
  484. function arrayByteLength(arr) {
  485. if (arr.length !== undefined) {
  486. return arr.length;
  487. }
  488. assert(arr.byteLength !== undefined);
  489. return arr.byteLength;
  490. }
  491. /**
  492. * Combines array items (arrays) into single Uint8Array object.
  493. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  494. * @returns {Uint8Array}
  495. */
  496. function arraysToBytes(arr) {
  497. // Shortcut: if first and only item is Uint8Array, return it.
  498. if (arr.length === 1 && arr[0] instanceof Uint8Array) {
  499. return arr[0];
  500. }
  501. var resultLength = 0;
  502. var i, ii = arr.length;
  503. var item, itemLength;
  504. for (i = 0; i < ii; i++) {
  505. item = arr[i];
  506. itemLength = arrayByteLength(item);
  507. resultLength += itemLength;
  508. }
  509. var pos = 0;
  510. var data = new Uint8Array(resultLength);
  511. for (i = 0; i < ii; i++) {
  512. item = arr[i];
  513. if (!(item instanceof Uint8Array)) {
  514. if (typeof item === 'string') {
  515. item = stringToBytes(item);
  516. } else {
  517. item = new Uint8Array(item);
  518. }
  519. }
  520. itemLength = item.byteLength;
  521. data.set(item, pos);
  522. pos += itemLength;
  523. }
  524. return data;
  525. }
  526. function string32(value) {
  527. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  528. }
  529. function log2(x) {
  530. var n = 1, i = 0;
  531. while (x > n) {
  532. n <<= 1;
  533. i++;
  534. }
  535. return i;
  536. }
  537. function readInt8(data, start) {
  538. return data[start] << 24 >> 24;
  539. }
  540. function readUint16(data, offset) {
  541. return data[offset] << 8 | data[offset + 1];
  542. }
  543. function readUint32(data, offset) {
  544. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  545. }
  546. // Lazy test the endianness of the platform
  547. // NOTE: This will be 'true' for simulated TypedArrays
  548. function isLittleEndian() {
  549. var buffer8 = new Uint8Array(2);
  550. buffer8[0] = 1;
  551. var buffer16 = new Uint16Array(buffer8.buffer);
  552. return buffer16[0] === 1;
  553. }
  554. // Checks if it's possible to eval JS expressions.
  555. function isEvalSupported() {
  556. try {
  557. new Function('');
  558. return true;
  559. } catch (e) {
  560. return false;
  561. }
  562. }
  563. var Uint32ArrayView = function Uint32ArrayViewClosure() {
  564. function Uint32ArrayView(buffer, length) {
  565. this.buffer = buffer;
  566. this.byteLength = buffer.length;
  567. this.length = length === undefined ? this.byteLength >> 2 : length;
  568. ensureUint32ArrayViewProps(this.length);
  569. }
  570. Uint32ArrayView.prototype = Object.create(null);
  571. var uint32ArrayViewSetters = 0;
  572. function createUint32ArrayProp(index) {
  573. return {
  574. get: function () {
  575. var buffer = this.buffer, offset = index << 2;
  576. return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
  577. },
  578. set: function (value) {
  579. var buffer = this.buffer, offset = index << 2;
  580. buffer[offset] = value & 255;
  581. buffer[offset + 1] = value >> 8 & 255;
  582. buffer[offset + 2] = value >> 16 & 255;
  583. buffer[offset + 3] = value >>> 24 & 255;
  584. }
  585. };
  586. }
  587. function ensureUint32ArrayViewProps(length) {
  588. while (uint32ArrayViewSetters < length) {
  589. Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
  590. uint32ArrayViewSetters++;
  591. }
  592. }
  593. return Uint32ArrayView;
  594. }();
  595. exports.Uint32ArrayView = Uint32ArrayView;
  596. var IDENTITY_MATRIX = [
  597. 1,
  598. 0,
  599. 0,
  600. 1,
  601. 0,
  602. 0
  603. ];
  604. var Util = function UtilClosure() {
  605. function Util() {
  606. }
  607. var rgbBuf = [
  608. 'rgb(',
  609. 0,
  610. ',',
  611. 0,
  612. ',',
  613. 0,
  614. ')'
  615. ];
  616. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  617. // creating many intermediate strings.
  618. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  619. rgbBuf[1] = r;
  620. rgbBuf[3] = g;
  621. rgbBuf[5] = b;
  622. return rgbBuf.join('');
  623. };
  624. // Concatenates two transformation matrices together and returns the result.
  625. Util.transform = function Util_transform(m1, m2) {
  626. return [
  627. m1[0] * m2[0] + m1[2] * m2[1],
  628. m1[1] * m2[0] + m1[3] * m2[1],
  629. m1[0] * m2[2] + m1[2] * m2[3],
  630. m1[1] * m2[2] + m1[3] * m2[3],
  631. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  632. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  633. ];
  634. };
  635. // For 2d affine transforms
  636. Util.applyTransform = function Util_applyTransform(p, m) {
  637. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  638. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  639. return [
  640. xt,
  641. yt
  642. ];
  643. };
  644. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  645. var d = m[0] * m[3] - m[1] * m[2];
  646. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  647. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  648. return [
  649. xt,
  650. yt
  651. ];
  652. };
  653. // Applies the transform to the rectangle and finds the minimum axially
  654. // aligned bounding box.
  655. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
  656. var p1 = Util.applyTransform(r, m);
  657. var p2 = Util.applyTransform(r.slice(2, 4), m);
  658. var p3 = Util.applyTransform([
  659. r[0],
  660. r[3]
  661. ], m);
  662. var p4 = Util.applyTransform([
  663. r[2],
  664. r[1]
  665. ], m);
  666. return [
  667. Math.min(p1[0], p2[0], p3[0], p4[0]),
  668. Math.min(p1[1], p2[1], p3[1], p4[1]),
  669. Math.max(p1[0], p2[0], p3[0], p4[0]),
  670. Math.max(p1[1], p2[1], p3[1], p4[1])
  671. ];
  672. };
  673. Util.inverseTransform = function Util_inverseTransform(m) {
  674. var d = m[0] * m[3] - m[1] * m[2];
  675. return [
  676. m[3] / d,
  677. -m[1] / d,
  678. -m[2] / d,
  679. m[0] / d,
  680. (m[2] * m[5] - m[4] * m[3]) / d,
  681. (m[4] * m[1] - m[5] * m[0]) / d
  682. ];
  683. };
  684. // Apply a generic 3d matrix M on a 3-vector v:
  685. // | a b c | | X |
  686. // | d e f | x | Y |
  687. // | g h i | | Z |
  688. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  689. // with v as [X,Y,Z]
  690. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  691. return [
  692. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  693. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  694. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  695. ];
  696. };
  697. // This calculation uses Singular Value Decomposition.
  698. // The SVD can be represented with formula A = USV. We are interested in the
  699. // matrix S here because it represents the scale values.
  700. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
  701. var transpose = [
  702. m[0],
  703. m[2],
  704. m[1],
  705. m[3]
  706. ];
  707. // Multiply matrix m with its transpose.
  708. var a = m[0] * transpose[0] + m[1] * transpose[2];
  709. var b = m[0] * transpose[1] + m[1] * transpose[3];
  710. var c = m[2] * transpose[0] + m[3] * transpose[2];
  711. var d = m[2] * transpose[1] + m[3] * transpose[3];
  712. // Solve the second degree polynomial to get roots.
  713. var first = (a + d) / 2;
  714. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  715. var sx = first + second || 1;
  716. var sy = first - second || 1;
  717. // Scale values are the square roots of the eigenvalues.
  718. return [
  719. Math.sqrt(sx),
  720. Math.sqrt(sy)
  721. ];
  722. };
  723. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  724. // For coordinate systems whose origin lies in the bottom-left, this
  725. // means normalization to (BL,TR) ordering. For systems with origin in the
  726. // top-left, this means (TL,BR) ordering.
  727. Util.normalizeRect = function Util_normalizeRect(rect) {
  728. var r = rect.slice(0);
  729. // clone rect
  730. if (rect[0] > rect[2]) {
  731. r[0] = rect[2];
  732. r[2] = rect[0];
  733. }
  734. if (rect[1] > rect[3]) {
  735. r[1] = rect[3];
  736. r[3] = rect[1];
  737. }
  738. return r;
  739. };
  740. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  741. // intersection of rect1 and rect2. If no intersection, returns 'false'
  742. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  743. Util.intersect = function Util_intersect(rect1, rect2) {
  744. function compare(a, b) {
  745. return a - b;
  746. }
  747. // Order points along the axes
  748. var orderedX = [
  749. rect1[0],
  750. rect1[2],
  751. rect2[0],
  752. rect2[2]
  753. ].sort(compare), orderedY = [
  754. rect1[1],
  755. rect1[3],
  756. rect2[1],
  757. rect2[3]
  758. ].sort(compare), result = [];
  759. rect1 = Util.normalizeRect(rect1);
  760. rect2 = Util.normalizeRect(rect2);
  761. // X: first and second points belong to different rectangles?
  762. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  763. // Intersection must be between second and third points
  764. result[0] = orderedX[1];
  765. result[2] = orderedX[2];
  766. } else {
  767. return false;
  768. }
  769. // Y: first and second points belong to different rectangles?
  770. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  771. // Intersection must be between second and third points
  772. result[1] = orderedY[1];
  773. result[3] = orderedY[2];
  774. } else {
  775. return false;
  776. }
  777. return result;
  778. };
  779. Util.sign = function Util_sign(num) {
  780. return num < 0 ? -1 : 1;
  781. };
  782. var ROMAN_NUMBER_MAP = [
  783. '',
  784. 'C',
  785. 'CC',
  786. 'CCC',
  787. 'CD',
  788. 'D',
  789. 'DC',
  790. 'DCC',
  791. 'DCCC',
  792. 'CM',
  793. '',
  794. 'X',
  795. 'XX',
  796. 'XXX',
  797. 'XL',
  798. 'L',
  799. 'LX',
  800. 'LXX',
  801. 'LXXX',
  802. 'XC',
  803. '',
  804. 'I',
  805. 'II',
  806. 'III',
  807. 'IV',
  808. 'V',
  809. 'VI',
  810. 'VII',
  811. 'VIII',
  812. 'IX'
  813. ];
  814. /**
  815. * Converts positive integers to (upper case) Roman numerals.
  816. * @param {integer} number - The number that should be converted.
  817. * @param {boolean} lowerCase - Indicates if the result should be converted
  818. * to lower case letters. The default is false.
  819. * @return {string} The resulting Roman number.
  820. */
  821. Util.toRoman = function Util_toRoman(number, lowerCase) {
  822. assert(isInt(number) && number > 0, 'The number should be a positive integer.');
  823. var pos, romanBuf = [];
  824. // Thousands
  825. while (number >= 1000) {
  826. number -= 1000;
  827. romanBuf.push('M');
  828. }
  829. // Hundreds
  830. pos = number / 100 | 0;
  831. number %= 100;
  832. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  833. // Tens
  834. pos = number / 10 | 0;
  835. number %= 10;
  836. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  837. // Ones
  838. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  839. var romanStr = romanBuf.join('');
  840. return lowerCase ? romanStr.toLowerCase() : romanStr;
  841. };
  842. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  843. Array.prototype.push.apply(arr1, arr2);
  844. };
  845. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  846. Array.prototype.unshift.apply(arr1, arr2);
  847. };
  848. Util.extendObj = function extendObj(obj1, obj2) {
  849. for (var key in obj2) {
  850. obj1[key] = obj2[key];
  851. }
  852. };
  853. Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
  854. while (dict && !dict.has(name)) {
  855. dict = dict.get('Parent');
  856. }
  857. if (!dict) {
  858. return null;
  859. }
  860. return getArray ? dict.getArray(name) : dict.get(name);
  861. };
  862. Util.inherit = function Util_inherit(sub, base, prototype) {
  863. sub.prototype = Object.create(base.prototype);
  864. sub.prototype.constructor = sub;
  865. for (var prop in prototype) {
  866. sub.prototype[prop] = prototype[prop];
  867. }
  868. };
  869. Util.loadScript = function Util_loadScript(src, callback) {
  870. var script = document.createElement('script');
  871. var loaded = false;
  872. script.setAttribute('src', src);
  873. if (callback) {
  874. script.onload = function () {
  875. if (!loaded) {
  876. callback();
  877. }
  878. loaded = true;
  879. };
  880. }
  881. document.getElementsByTagName('head')[0].appendChild(script);
  882. };
  883. return Util;
  884. }();
  885. /**
  886. * PDF page viewport created based on scale, rotation and offset.
  887. * @class
  888. * @alias PageViewport
  889. */
  890. var PageViewport = function PageViewportClosure() {
  891. /**
  892. * @constructor
  893. * @private
  894. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  895. * @param scale {number} scale of the viewport.
  896. * @param rotation {number} rotations of the viewport in degrees.
  897. * @param offsetX {number} offset X
  898. * @param offsetY {number} offset Y
  899. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  900. */
  901. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  902. this.viewBox = viewBox;
  903. this.scale = scale;
  904. this.rotation = rotation;
  905. this.offsetX = offsetX;
  906. this.offsetY = offsetY;
  907. // creating transform to convert pdf coordinate system to the normal
  908. // canvas like coordinates taking in account scale and rotation
  909. var centerX = (viewBox[2] + viewBox[0]) / 2;
  910. var centerY = (viewBox[3] + viewBox[1]) / 2;
  911. var rotateA, rotateB, rotateC, rotateD;
  912. rotation = rotation % 360;
  913. rotation = rotation < 0 ? rotation + 360 : rotation;
  914. switch (rotation) {
  915. case 180:
  916. rotateA = -1;
  917. rotateB = 0;
  918. rotateC = 0;
  919. rotateD = 1;
  920. break;
  921. case 90:
  922. rotateA = 0;
  923. rotateB = 1;
  924. rotateC = 1;
  925. rotateD = 0;
  926. break;
  927. case 270:
  928. rotateA = 0;
  929. rotateB = -1;
  930. rotateC = -1;
  931. rotateD = 0;
  932. break;
  933. //case 0:
  934. default:
  935. rotateA = 1;
  936. rotateB = 0;
  937. rotateC = 0;
  938. rotateD = -1;
  939. break;
  940. }
  941. if (dontFlip) {
  942. rotateC = -rotateC;
  943. rotateD = -rotateD;
  944. }
  945. var offsetCanvasX, offsetCanvasY;
  946. var width, height;
  947. if (rotateA === 0) {
  948. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  949. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  950. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  951. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  952. } else {
  953. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  954. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  955. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  956. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  957. }
  958. // creating transform for the following operations:
  959. // translate(-centerX, -centerY), rotate and flip vertically,
  960. // scale, and translate(offsetCanvasX, offsetCanvasY)
  961. this.transform = [
  962. rotateA * scale,
  963. rotateB * scale,
  964. rotateC * scale,
  965. rotateD * scale,
  966. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  967. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  968. ];
  969. this.width = width;
  970. this.height = height;
  971. this.fontScale = scale;
  972. }
  973. PageViewport.prototype = /** @lends PageViewport.prototype */
  974. {
  975. /**
  976. * Clones viewport with additional properties.
  977. * @param args {Object} (optional) If specified, may contain the 'scale' or
  978. * 'rotation' properties to override the corresponding properties in
  979. * the cloned viewport.
  980. * @returns {PageViewport} Cloned viewport.
  981. */
  982. clone: function PageViewPort_clone(args) {
  983. args = args || {};
  984. var scale = 'scale' in args ? args.scale : this.scale;
  985. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  986. return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
  987. },
  988. /**
  989. * Converts PDF point to the viewport coordinates. For examples, useful for
  990. * converting PDF location into canvas pixel coordinates.
  991. * @param x {number} X coordinate.
  992. * @param y {number} Y coordinate.
  993. * @returns {Object} Object that contains 'x' and 'y' properties of the
  994. * point in the viewport coordinate space.
  995. * @see {@link convertToPdfPoint}
  996. * @see {@link convertToViewportRectangle}
  997. */
  998. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  999. return Util.applyTransform([
  1000. x,
  1001. y
  1002. ], this.transform);
  1003. },
  1004. /**
  1005. * Converts PDF rectangle to the viewport coordinates.
  1006. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  1007. * @returns {Array} Contains corresponding coordinates of the rectangle
  1008. * in the viewport coordinate space.
  1009. * @see {@link convertToViewportPoint}
  1010. */
  1011. convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
  1012. var tl = Util.applyTransform([
  1013. rect[0],
  1014. rect[1]
  1015. ], this.transform);
  1016. var br = Util.applyTransform([
  1017. rect[2],
  1018. rect[3]
  1019. ], this.transform);
  1020. return [
  1021. tl[0],
  1022. tl[1],
  1023. br[0],
  1024. br[1]
  1025. ];
  1026. },
  1027. /**
  1028. * Converts viewport coordinates to the PDF location. For examples, useful
  1029. * for converting canvas pixel location into PDF one.
  1030. * @param x {number} X coordinate.
  1031. * @param y {number} Y coordinate.
  1032. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1033. * point in the PDF coordinate space.
  1034. * @see {@link convertToViewportPoint}
  1035. */
  1036. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  1037. return Util.applyInverseTransform([
  1038. x,
  1039. y
  1040. ], this.transform);
  1041. }
  1042. };
  1043. return PageViewport;
  1044. }();
  1045. var PDFStringTranslateTable = [
  1046. 0,
  1047. 0,
  1048. 0,
  1049. 0,
  1050. 0,
  1051. 0,
  1052. 0,
  1053. 0,
  1054. 0,
  1055. 0,
  1056. 0,
  1057. 0,
  1058. 0,
  1059. 0,
  1060. 0,
  1061. 0,
  1062. 0,
  1063. 0,
  1064. 0,
  1065. 0,
  1066. 0,
  1067. 0,
  1068. 0,
  1069. 0,
  1070. 0x2D8,
  1071. 0x2C7,
  1072. 0x2C6,
  1073. 0x2D9,
  1074. 0x2DD,
  1075. 0x2DB,
  1076. 0x2DA,
  1077. 0x2DC,
  1078. 0,
  1079. 0,
  1080. 0,
  1081. 0,
  1082. 0,
  1083. 0,
  1084. 0,
  1085. 0,
  1086. 0,
  1087. 0,
  1088. 0,
  1089. 0,
  1090. 0,
  1091. 0,
  1092. 0,
  1093. 0,
  1094. 0,
  1095. 0,
  1096. 0,
  1097. 0,
  1098. 0,
  1099. 0,
  1100. 0,
  1101. 0,
  1102. 0,
  1103. 0,
  1104. 0,
  1105. 0,
  1106. 0,
  1107. 0,
  1108. 0,
  1109. 0,
  1110. 0,
  1111. 0,
  1112. 0,
  1113. 0,
  1114. 0,
  1115. 0,
  1116. 0,
  1117. 0,
  1118. 0,
  1119. 0,
  1120. 0,
  1121. 0,
  1122. 0,
  1123. 0,
  1124. 0,
  1125. 0,
  1126. 0,
  1127. 0,
  1128. 0,
  1129. 0,
  1130. 0,
  1131. 0,
  1132. 0,
  1133. 0,
  1134. 0,
  1135. 0,
  1136. 0,
  1137. 0,
  1138. 0,
  1139. 0,
  1140. 0,
  1141. 0,
  1142. 0,
  1143. 0,
  1144. 0,
  1145. 0,
  1146. 0,
  1147. 0,
  1148. 0,
  1149. 0,
  1150. 0,
  1151. 0,
  1152. 0,
  1153. 0,
  1154. 0,
  1155. 0,
  1156. 0,
  1157. 0,
  1158. 0,
  1159. 0,
  1160. 0,
  1161. 0,
  1162. 0,
  1163. 0,
  1164. 0,
  1165. 0,
  1166. 0,
  1167. 0,
  1168. 0,
  1169. 0,
  1170. 0,
  1171. 0,
  1172. 0,
  1173. 0,
  1174. 0x2022,
  1175. 0x2020,
  1176. 0x2021,
  1177. 0x2026,
  1178. 0x2014,
  1179. 0x2013,
  1180. 0x192,
  1181. 0x2044,
  1182. 0x2039,
  1183. 0x203A,
  1184. 0x2212,
  1185. 0x2030,
  1186. 0x201E,
  1187. 0x201C,
  1188. 0x201D,
  1189. 0x2018,
  1190. 0x2019,
  1191. 0x201A,
  1192. 0x2122,
  1193. 0xFB01,
  1194. 0xFB02,
  1195. 0x141,
  1196. 0x152,
  1197. 0x160,
  1198. 0x178,
  1199. 0x17D,
  1200. 0x131,
  1201. 0x142,
  1202. 0x153,
  1203. 0x161,
  1204. 0x17E,
  1205. 0,
  1206. 0x20AC
  1207. ];
  1208. function stringToPDFString(str) {
  1209. var i, n = str.length, strBuf = [];
  1210. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1211. // UTF16BE BOM
  1212. for (i = 2; i < n; i += 2) {
  1213. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1214. }
  1215. } else {
  1216. for (i = 0; i < n; ++i) {
  1217. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1218. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1219. }
  1220. }
  1221. return strBuf.join('');
  1222. }
  1223. function stringToUTF8String(str) {
  1224. return decodeURIComponent(escape(str));
  1225. }
  1226. function utf8StringToString(str) {
  1227. return unescape(encodeURIComponent(str));
  1228. }
  1229. function isEmptyObj(obj) {
  1230. for (var key in obj) {
  1231. return false;
  1232. }
  1233. return true;
  1234. }
  1235. function isBool(v) {
  1236. return typeof v === 'boolean';
  1237. }
  1238. function isInt(v) {
  1239. return typeof v === 'number' && (v | 0) === v;
  1240. }
  1241. function isNum(v) {
  1242. return typeof v === 'number';
  1243. }
  1244. function isString(v) {
  1245. return typeof v === 'string';
  1246. }
  1247. function isArray(v) {
  1248. return v instanceof Array;
  1249. }
  1250. function isArrayBuffer(v) {
  1251. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1252. }
  1253. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1254. function isSpace(ch) {
  1255. return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
  1256. }
  1257. /**
  1258. * Promise Capability object.
  1259. *
  1260. * @typedef {Object} PromiseCapability
  1261. * @property {Promise} promise - A promise object.
  1262. * @property {function} resolve - Fulfills the promise.
  1263. * @property {function} reject - Rejects the promise.
  1264. */
  1265. /**
  1266. * Creates a promise capability object.
  1267. * @alias createPromiseCapability
  1268. *
  1269. * @return {PromiseCapability} A capability object contains:
  1270. * - a Promise, resolve and reject methods.
  1271. */
  1272. function createPromiseCapability() {
  1273. var capability = {};
  1274. capability.promise = new Promise(function (resolve, reject) {
  1275. capability.resolve = resolve;
  1276. capability.reject = reject;
  1277. });
  1278. return capability;
  1279. }
  1280. /**
  1281. * Polyfill for Promises:
  1282. * The following promise implementation tries to generally implement the
  1283. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1284. * - There currently isn't a separate deferred and promise object.
  1285. * - Unhandled rejections eventually show an error if they aren't handled.
  1286. *
  1287. * Based off of the work in:
  1288. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1289. */
  1290. (function PromiseClosure() {
  1291. if (globalScope.Promise) {
  1292. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1293. if (typeof globalScope.Promise.all !== 'function') {
  1294. globalScope.Promise.all = function (iterable) {
  1295. var count = 0, results = [], resolve, reject;
  1296. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1297. resolve = resolve_;
  1298. reject = reject_;
  1299. });
  1300. iterable.forEach(function (p, i) {
  1301. count++;
  1302. p.then(function (result) {
  1303. results[i] = result;
  1304. count--;
  1305. if (count === 0) {
  1306. resolve(results);
  1307. }
  1308. }, reject);
  1309. });
  1310. if (count === 0) {
  1311. resolve(results);
  1312. }
  1313. return promise;
  1314. };
  1315. }
  1316. if (typeof globalScope.Promise.resolve !== 'function') {
  1317. globalScope.Promise.resolve = function (value) {
  1318. return new globalScope.Promise(function (resolve) {
  1319. resolve(value);
  1320. });
  1321. };
  1322. }
  1323. if (typeof globalScope.Promise.reject !== 'function') {
  1324. globalScope.Promise.reject = function (reason) {
  1325. return new globalScope.Promise(function (resolve, reject) {
  1326. reject(reason);
  1327. });
  1328. };
  1329. }
  1330. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1331. globalScope.Promise.prototype.catch = function (onReject) {
  1332. return globalScope.Promise.prototype.then(undefined, onReject);
  1333. };
  1334. }
  1335. return;
  1336. }
  1337. var STATUS_PENDING = 0;
  1338. var STATUS_RESOLVED = 1;
  1339. var STATUS_REJECTED = 2;
  1340. // In an attempt to avoid silent exceptions, unhandled rejections are
  1341. // tracked and if they aren't handled in a certain amount of time an
  1342. // error is logged.
  1343. var REJECTION_TIMEOUT = 500;
  1344. var HandlerManager = {
  1345. handlers: [],
  1346. running: false,
  1347. unhandledRejections: [],
  1348. pendingRejectionCheck: false,
  1349. scheduleHandlers: function scheduleHandlers(promise) {
  1350. if (promise._status === STATUS_PENDING) {
  1351. return;
  1352. }
  1353. this.handlers = this.handlers.concat(promise._handlers);
  1354. promise._handlers = [];
  1355. if (this.running) {
  1356. return;
  1357. }
  1358. this.running = true;
  1359. setTimeout(this.runHandlers.bind(this), 0);
  1360. },
  1361. runHandlers: function runHandlers() {
  1362. var RUN_TIMEOUT = 1;
  1363. // ms
  1364. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1365. while (this.handlers.length > 0) {
  1366. var handler = this.handlers.shift();
  1367. var nextStatus = handler.thisPromise._status;
  1368. var nextValue = handler.thisPromise._value;
  1369. try {
  1370. if (nextStatus === STATUS_RESOLVED) {
  1371. if (typeof handler.onResolve === 'function') {
  1372. nextValue = handler.onResolve(nextValue);
  1373. }
  1374. } else if (typeof handler.onReject === 'function') {
  1375. nextValue = handler.onReject(nextValue);
  1376. nextStatus = STATUS_RESOLVED;
  1377. if (handler.thisPromise._unhandledRejection) {
  1378. this.removeUnhandeledRejection(handler.thisPromise);
  1379. }
  1380. }
  1381. } catch (ex) {
  1382. nextStatus = STATUS_REJECTED;
  1383. nextValue = ex;
  1384. }
  1385. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1386. if (Date.now() >= timeoutAt) {
  1387. break;
  1388. }
  1389. }
  1390. if (this.handlers.length > 0) {
  1391. setTimeout(this.runHandlers.bind(this), 0);
  1392. return;
  1393. }
  1394. this.running = false;
  1395. },
  1396. addUnhandledRejection: function addUnhandledRejection(promise) {
  1397. this.unhandledRejections.push({
  1398. promise: promise,
  1399. time: Date.now()
  1400. });
  1401. this.scheduleRejectionCheck();
  1402. },
  1403. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1404. promise._unhandledRejection = false;
  1405. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1406. if (this.unhandledRejections[i].promise === promise) {
  1407. this.unhandledRejections.splice(i);
  1408. i--;
  1409. }
  1410. }
  1411. },
  1412. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1413. if (this.pendingRejectionCheck) {
  1414. return;
  1415. }
  1416. this.pendingRejectionCheck = true;
  1417. setTimeout(function rejectionCheck() {
  1418. this.pendingRejectionCheck = false;
  1419. var now = Date.now();
  1420. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1421. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1422. var unhandled = this.unhandledRejections[i].promise._value;
  1423. var msg = 'Unhandled rejection: ' + unhandled;
  1424. if (unhandled.stack) {
  1425. msg += '\n' + unhandled.stack;
  1426. }
  1427. warn(msg);
  1428. this.unhandledRejections.splice(i);
  1429. i--;
  1430. }
  1431. }
  1432. if (this.unhandledRejections.length) {
  1433. this.scheduleRejectionCheck();
  1434. }
  1435. }.bind(this), REJECTION_TIMEOUT);
  1436. }
  1437. };
  1438. var Promise = function Promise(resolver) {
  1439. this._status = STATUS_PENDING;
  1440. this._handlers = [];
  1441. try {
  1442. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1443. } catch (e) {
  1444. this._reject(e);
  1445. }
  1446. };
  1447. /**
  1448. * Builds a promise that is resolved when all the passed in promises are
  1449. * resolved.
  1450. * @param {array} promises array of data and/or promises to wait for.
  1451. * @return {Promise} New dependent promise.
  1452. */
  1453. Promise.all = function Promise_all(promises) {
  1454. var resolveAll, rejectAll;
  1455. var deferred = new Promise(function (resolve, reject) {
  1456. resolveAll = resolve;
  1457. rejectAll = reject;
  1458. });
  1459. var unresolved = promises.length;
  1460. var results = [];
  1461. if (unresolved === 0) {
  1462. resolveAll(results);
  1463. return deferred;
  1464. }
  1465. function reject(reason) {
  1466. if (deferred._status === STATUS_REJECTED) {
  1467. return;
  1468. }
  1469. results = [];
  1470. rejectAll(reason);
  1471. }
  1472. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1473. var promise = promises[i];
  1474. var resolve = function (i) {
  1475. return function (value) {
  1476. if (deferred._status === STATUS_REJECTED) {
  1477. return;
  1478. }
  1479. results[i] = value;
  1480. unresolved--;
  1481. if (unresolved === 0) {
  1482. resolveAll(results);
  1483. }
  1484. };
  1485. }(i);
  1486. if (Promise.isPromise(promise)) {
  1487. promise.then(resolve, reject);
  1488. } else {
  1489. resolve(promise);
  1490. }
  1491. }
  1492. return deferred;
  1493. };
  1494. /**
  1495. * Checks if the value is likely a promise (has a 'then' function).
  1496. * @return {boolean} true if value is thenable
  1497. */
  1498. Promise.isPromise = function Promise_isPromise(value) {
  1499. return value && typeof value.then === 'function';
  1500. };
  1501. /**
  1502. * Creates resolved promise
  1503. * @param value resolve value
  1504. * @returns {Promise}
  1505. */
  1506. Promise.resolve = function Promise_resolve(value) {
  1507. return new Promise(function (resolve) {
  1508. resolve(value);
  1509. });
  1510. };
  1511. /**
  1512. * Creates rejected promise
  1513. * @param reason rejection value
  1514. * @returns {Promise}
  1515. */
  1516. Promise.reject = function Promise_reject(reason) {
  1517. return new Promise(function (resolve, reject) {
  1518. reject(reason);
  1519. });
  1520. };
  1521. Promise.prototype = {
  1522. _status: null,
  1523. _value: null,
  1524. _handlers: null,
  1525. _unhandledRejection: null,
  1526. _updateStatus: function Promise__updateStatus(status, value) {
  1527. if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) {
  1528. return;
  1529. }
  1530. if (status === STATUS_RESOLVED && Promise.isPromise(value)) {
  1531. value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED));
  1532. return;
  1533. }
  1534. this._status = status;
  1535. this._value = value;
  1536. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1537. this._unhandledRejection = true;
  1538. HandlerManager.addUnhandledRejection(this);
  1539. }
  1540. HandlerManager.scheduleHandlers(this);
  1541. },
  1542. _resolve: function Promise_resolve(value) {
  1543. this._updateStatus(STATUS_RESOLVED, value);
  1544. },
  1545. _reject: function Promise_reject(reason) {
  1546. this._updateStatus(STATUS_REJECTED, reason);
  1547. },
  1548. then: function Promise_then(onResolve, onReject) {
  1549. var nextPromise = new Promise(function (resolve, reject) {
  1550. this.resolve = resolve;
  1551. this.reject = reject;
  1552. });
  1553. this._handlers.push({
  1554. thisPromise: this,
  1555. onResolve: onResolve,
  1556. onReject: onReject,
  1557. nextPromise: nextPromise
  1558. });
  1559. HandlerManager.scheduleHandlers(this);
  1560. return nextPromise;
  1561. },
  1562. catch: function Promise_catch(onReject) {
  1563. return this.then(undefined, onReject);
  1564. }
  1565. };
  1566. globalScope.Promise = Promise;
  1567. }());
  1568. (function WeakMapClosure() {
  1569. if (globalScope.WeakMap) {
  1570. return;
  1571. }
  1572. var id = 0;
  1573. function WeakMap() {
  1574. this.id = '$weakmap' + id++;
  1575. }
  1576. WeakMap.prototype = {
  1577. has: function (obj) {
  1578. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1579. },
  1580. get: function (obj, defaultValue) {
  1581. return this.has(obj) ? obj[this.id] : defaultValue;
  1582. },
  1583. set: function (obj, value) {
  1584. Object.defineProperty(obj, this.id, {
  1585. value: value,
  1586. enumerable: false,
  1587. configurable: true
  1588. });
  1589. },
  1590. delete: function (obj) {
  1591. delete obj[this.id];
  1592. }
  1593. };
  1594. globalScope.WeakMap = WeakMap;
  1595. }());
  1596. var StatTimer = function StatTimerClosure() {
  1597. function rpad(str, pad, length) {
  1598. while (str.length < length) {
  1599. str += pad;
  1600. }
  1601. return str;
  1602. }
  1603. function StatTimer() {
  1604. this.started = Object.create(null);
  1605. this.times = [];
  1606. this.enabled = true;
  1607. }
  1608. StatTimer.prototype = {
  1609. time: function StatTimer_time(name) {
  1610. if (!this.enabled) {
  1611. return;
  1612. }
  1613. if (name in this.started) {
  1614. warn('Timer is already running for ' + name);
  1615. }
  1616. this.started[name] = Date.now();
  1617. },
  1618. timeEnd: function StatTimer_timeEnd(name) {
  1619. if (!this.enabled) {
  1620. return;
  1621. }
  1622. if (!(name in this.started)) {
  1623. warn('Timer has not been started for ' + name);
  1624. }
  1625. this.times.push({
  1626. 'name': name,
  1627. 'start': this.started[name],
  1628. 'end': Date.now()
  1629. });
  1630. // Remove timer from started so it can be called again.
  1631. delete this.started[name];
  1632. },
  1633. toString: function StatTimer_toString() {
  1634. var i, ii;
  1635. var times = this.times;
  1636. var out = '';
  1637. // Find the longest name for padding purposes.
  1638. var longest = 0;
  1639. for (i = 0, ii = times.length; i < ii; ++i) {
  1640. var name = times[i]['name'];
  1641. if (name.length > longest) {
  1642. longest = name.length;
  1643. }
  1644. }
  1645. for (i = 0, ii = times.length; i < ii; ++i) {
  1646. var span = times[i];
  1647. var duration = span.end - span.start;
  1648. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1649. }
  1650. return out;
  1651. }
  1652. };
  1653. return StatTimer;
  1654. }();
  1655. var createBlob = function createBlob(data, contentType) {
  1656. if (typeof Blob !== 'undefined') {
  1657. return new Blob([data], { type: contentType });
  1658. }
  1659. warn('The "Blob" constructor is not supported.');
  1660. };
  1661. var createObjectURL = function createObjectURLClosure() {
  1662. // Blob/createObjectURL is not available, falling back to data schema.
  1663. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1664. return function createObjectURL(data, contentType, forceDataSchema) {
  1665. if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
  1666. var blob = createBlob(data, contentType);
  1667. return URL.createObjectURL(blob);
  1668. }
  1669. var buffer = 'data:' + contentType + ';base64,';
  1670. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1671. var b1 = data[i] & 0xFF;
  1672. var b2 = data[i + 1] & 0xFF;
  1673. var b3 = data[i + 2] & 0xFF;
  1674. var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4;
  1675. var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
  1676. var d4 = i + 2 < ii ? b3 & 0x3F : 64;
  1677. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1678. }
  1679. return buffer;
  1680. };
  1681. }();
  1682. function MessageHandler(sourceName, targetName, comObj) {
  1683. this.sourceName = sourceName;
  1684. this.targetName = targetName;
  1685. this.comObj = comObj;
  1686. this.callbackIndex = 1;
  1687. this.postMessageTransfers = true;
  1688. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1689. var ah = this.actionHandler = Object.create(null);
  1690. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1691. var data = event.data;
  1692. if (data.targetName !== this.sourceName) {
  1693. return;
  1694. }
  1695. if (data.isReply) {
  1696. var callbackId = data.callbackId;
  1697. if (data.callbackId in callbacksCapabilities) {
  1698. var callback = callbacksCapabilities[callbackId];
  1699. delete callbacksCapabilities[callbackId];
  1700. if ('error' in data) {
  1701. callback.reject(data.error);
  1702. } else {
  1703. callback.resolve(data.data);
  1704. }
  1705. } else {
  1706. error('Cannot resolve callback ' + callbackId);
  1707. }
  1708. } else if (data.action in ah) {
  1709. var action = ah[data.action];
  1710. if (data.callbackId) {
  1711. var sourceName = this.sourceName;
  1712. var targetName = data.sourceName;
  1713. Promise.resolve().then(function () {
  1714. return action[0].call(action[1], data.data);
  1715. }).then(function (result) {
  1716. comObj.postMessage({
  1717. sourceName: sourceName,
  1718. targetName: targetName,
  1719. isReply: true,
  1720. callbackId: data.callbackId,
  1721. data: result
  1722. });
  1723. }, function (reason) {
  1724. if (reason instanceof Error) {
  1725. // Serialize error to avoid "DataCloneError"
  1726. reason = reason + '';
  1727. }
  1728. comObj.postMessage({
  1729. sourceName: sourceName,
  1730. targetName: targetName,
  1731. isReply: true,
  1732. callbackId: data.callbackId,
  1733. error: reason
  1734. });
  1735. });
  1736. } else {
  1737. action[0].call(action[1], data.data);
  1738. }
  1739. } else {
  1740. error('Unknown action from worker: ' + data.action);
  1741. }
  1742. }.bind(this);
  1743. comObj.addEventListener('message', this._onComObjOnMessage);
  1744. }
  1745. MessageHandler.prototype = {
  1746. on: function messageHandlerOn(actionName, handler, scope) {
  1747. var ah = this.actionHandler;
  1748. if (ah[actionName]) {
  1749. error('There is already an actionName called "' + actionName + '"');
  1750. }
  1751. ah[actionName] = [
  1752. handler,
  1753. scope
  1754. ];
  1755. },
  1756. /**
  1757. * Sends a message to the comObj to invoke the action with the supplied data.
  1758. * @param {String} actionName Action to call.
  1759. * @param {JSON} data JSON data to send.
  1760. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1761. */
  1762. send: function messageHandlerSend(actionName, data, transfers) {
  1763. var message = {
  1764. sourceName: this.sourceName,
  1765. targetName: this.targetName,
  1766. action: actionName,
  1767. data: data
  1768. };
  1769. this.postMessage(message, transfers);
  1770. },
  1771. /**
  1772. * Sends a message to the comObj to invoke the action with the supplied data.
  1773. * Expects that other side will callback with the response.
  1774. * @param {String} actionName Action to call.
  1775. * @param {JSON} data JSON data to send.
  1776. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1777. * @returns {Promise} Promise to be resolved with response data.
  1778. */
  1779. sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
  1780. var callbackId = this.callbackIndex++;
  1781. var message = {
  1782. sourceName: this.sourceName,
  1783. targetName: this.targetName,
  1784. action: actionName,
  1785. data: data,
  1786. callbackId: callbackId
  1787. };
  1788. var capability = createPromiseCapability();
  1789. this.callbacksCapabilities[callbackId] = capability;
  1790. try {
  1791. this.postMessage(message, transfers);
  1792. } catch (e) {
  1793. capability.reject(e);
  1794. }
  1795. return capability.promise;
  1796. },
  1797. /**
  1798. * Sends raw message to the comObj.
  1799. * @private
  1800. * @param message {Object} Raw message.
  1801. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1802. */
  1803. postMessage: function (message, transfers) {
  1804. if (transfers && this.postMessageTransfers) {
  1805. this.comObj.postMessage(message, transfers);
  1806. } else {
  1807. this.comObj.postMessage(message);
  1808. }
  1809. },
  1810. destroy: function () {
  1811. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1812. }
  1813. };
  1814. function loadJpegStream(id, imageUrl, objs) {
  1815. var img = new Image();
  1816. img.onload = function loadJpegStream_onloadClosure() {
  1817. objs.resolve(id, img);
  1818. };
  1819. img.onerror = function loadJpegStream_onerrorClosure() {
  1820. objs.resolve(id, null);
  1821. warn('Error during JPEG image loading');
  1822. };
  1823. img.src = imageUrl;
  1824. }
  1825. // Polyfill from https://github.com/Polymer/URL
  1826. /* Any copyright is dedicated to the Public Domain.
  1827. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1828. (function checkURLConstructor(scope) {
  1829. // feature detect for URL constructor
  1830. var hasWorkingUrl = false;
  1831. try {
  1832. if (typeof URL === 'function' && typeof URL.prototype === 'object' && 'origin' in URL.prototype) {
  1833. var u = new URL('b', 'http://a');
  1834. u.pathname = 'c%20d';
  1835. hasWorkingUrl = u.href === 'http://a/c%20d';
  1836. }
  1837. } catch (e) {
  1838. }
  1839. if (hasWorkingUrl) {
  1840. return;
  1841. }
  1842. var relative = Object.create(null);
  1843. relative['ftp'] = 21;
  1844. relative['file'] = 0;
  1845. relative['gopher'] = 70;
  1846. relative['http'] = 80;
  1847. relative['https'] = 443;
  1848. relative['ws'] = 80;
  1849. relative['wss'] = 443;
  1850. var relativePathDotMapping = Object.create(null);
  1851. relativePathDotMapping['%2e'] = '.';
  1852. relativePathDotMapping['.%2e'] = '..';
  1853. relativePathDotMapping['%2e.'] = '..';
  1854. relativePathDotMapping['%2e%2e'] = '..';
  1855. function isRelativeScheme(scheme) {
  1856. return relative[scheme] !== undefined;
  1857. }
  1858. function invalid() {
  1859. clear.call(this);
  1860. this._isInvalid = true;
  1861. }
  1862. function IDNAToASCII(h) {
  1863. if ('' === h) {
  1864. invalid.call(this);
  1865. }
  1866. // XXX
  1867. return h.toLowerCase();
  1868. }
  1869. function percentEscape(c) {
  1870. var unicode = c.charCodeAt(0);
  1871. if (unicode > 0x20 && unicode < 0x7F && // " # < > ? `
  1872. [
  1873. 0x22,
  1874. 0x23,
  1875. 0x3C,
  1876. 0x3E,
  1877. 0x3F,
  1878. 0x60
  1879. ].indexOf(unicode) === -1) {
  1880. return c;
  1881. }
  1882. return encodeURIComponent(c);
  1883. }
  1884. function percentEscapeQuery(c) {
  1885. // XXX This actually needs to encode c using encoding and then
  1886. // convert the bytes one-by-one.
  1887. var unicode = c.charCodeAt(0);
  1888. if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?')
  1889. [
  1890. 0x22,
  1891. 0x23,
  1892. 0x3C,
  1893. 0x3E,
  1894. 0x60
  1895. ].indexOf(unicode) === -1) {
  1896. return c;
  1897. }
  1898. return encodeURIComponent(c);
  1899. }
  1900. var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1901. function parse(input, stateOverride, base) {
  1902. function err(message) {
  1903. errors.push(message);
  1904. }
  1905. var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = [];
  1906. loop:
  1907. while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
  1908. var c = input[cursor];
  1909. switch (state) {
  1910. case 'scheme start':
  1911. if (c && ALPHA.test(c)) {
  1912. buffer += c.toLowerCase();
  1913. // ASCII-safe
  1914. state = 'scheme';
  1915. } else if (!stateOverride) {
  1916. buffer = '';
  1917. state = 'no scheme';
  1918. continue;
  1919. } else {
  1920. err('Invalid scheme.');
  1921. break loop;
  1922. }
  1923. break;
  1924. case 'scheme':
  1925. if (c && ALPHANUMERIC.test(c)) {
  1926. buffer += c.toLowerCase();
  1927. } else // ASCII-safe
  1928. if (':' === c) {
  1929. this._scheme = buffer;
  1930. buffer = '';
  1931. if (stateOverride) {
  1932. break loop;
  1933. }
  1934. if (isRelativeScheme(this._scheme)) {
  1935. this._isRelative = true;
  1936. }
  1937. if ('file' === this._scheme) {
  1938. state = 'relative';
  1939. } else if (this._isRelative && base && base._scheme === this._scheme) {
  1940. state = 'relative or authority';
  1941. } else if (this._isRelative) {
  1942. state = 'authority first slash';
  1943. } else {
  1944. state = 'scheme data';
  1945. }
  1946. } else if (!stateOverride) {
  1947. buffer = '';
  1948. cursor = 0;
  1949. state = 'no scheme';
  1950. continue;
  1951. } else if (EOF === c) {
  1952. break loop;
  1953. } else {
  1954. err('Code point not allowed in scheme: ' + c);
  1955. break loop;
  1956. }
  1957. break;
  1958. case 'scheme data':
  1959. if ('?' === c) {
  1960. this._query = '?';
  1961. state = 'query';
  1962. } else if ('#' === c) {
  1963. this._fragment = '#';
  1964. state = 'fragment';
  1965. } else {
  1966. // XXX error handling
  1967. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1968. this._schemeData += percentEscape(c);
  1969. }
  1970. }
  1971. break;
  1972. case 'no scheme':
  1973. if (!base || !isRelativeScheme(base._scheme)) {
  1974. err('Missing scheme.');
  1975. invalid.call(this);
  1976. } else {
  1977. state = 'relative';
  1978. continue;
  1979. }
  1980. break;
  1981. case 'relative or authority':
  1982. if ('/' === c && '/' === input[cursor + 1]) {
  1983. state = 'authority ignore slashes';
  1984. } else {
  1985. err('Expected /, got: ' + c);
  1986. state = 'relative';
  1987. continue;
  1988. }
  1989. break;
  1990. case 'relative':
  1991. this._isRelative = true;
  1992. if ('file' !== this._scheme) {
  1993. this._scheme = base._scheme;
  1994. }
  1995. if (EOF === c) {
  1996. this._host = base._host;
  1997. this._port = base._port;
  1998. this._path = base._path.slice();
  1999. this._query = base._query;
  2000. this._username = base._username;
  2001. this._password = base._password;
  2002. break loop;
  2003. } else if ('/' === c || '\\' === c) {
  2004. if ('\\' === c) {
  2005. err('\\ is an invalid code point.');
  2006. }
  2007. state = 'relative slash';
  2008. } else if ('?' === c) {
  2009. this._host = base._host;
  2010. this._port = base._port;
  2011. this._path = base._path.slice();
  2012. this._query = '?';
  2013. this._username = base._username;
  2014. this._password = base._password;
  2015. state = 'query';
  2016. } else if ('#' === c) {
  2017. this._host = base._host;
  2018. this._port = base._port;
  2019. this._path = base._path.slice();
  2020. this._query = base._query;
  2021. this._fragment = '#';
  2022. this._username = base._username;
  2023. this._password = base._password;
  2024. state = 'fragment';
  2025. } else {
  2026. var nextC = input[cursor + 1];
  2027. var nextNextC = input[cursor + 2];
  2028. if ('file' !== this._scheme || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC) {
  2029. this._host = base._host;
  2030. this._port = base._port;
  2031. this._username = base._username;
  2032. this._password = base._password;
  2033. this._path = base._path.slice();
  2034. this._path.pop();
  2035. }
  2036. state = 'relative path';
  2037. continue;
  2038. }
  2039. break;
  2040. case 'relative slash':
  2041. if ('/' === c || '\\' === c) {
  2042. if ('\\' === c) {
  2043. err('\\ is an invalid code point.');
  2044. }
  2045. if ('file' === this._scheme) {
  2046. state = 'file host';
  2047. } else {
  2048. state = 'authority ignore slashes';
  2049. }
  2050. } else {
  2051. if ('file' !== this._scheme) {
  2052. this._host = base._host;
  2053. this._port = base._port;
  2054. this._username = base._username;
  2055. this._password = base._password;
  2056. }
  2057. state = 'relative path';
  2058. continue;
  2059. }
  2060. break;
  2061. case 'authority first slash':
  2062. if ('/' === c) {
  2063. state = 'authority second slash';
  2064. } else {
  2065. err('Expected \'/\', got: ' + c);
  2066. state = 'authority ignore slashes';
  2067. continue;
  2068. }
  2069. break;
  2070. case 'authority second slash':
  2071. state = 'authority ignore slashes';
  2072. if ('/' !== c) {
  2073. err('Expected \'/\', got: ' + c);
  2074. continue;
  2075. }
  2076. break;
  2077. case 'authority ignore slashes':
  2078. if ('/' !== c && '\\' !== c) {
  2079. state = 'authority';
  2080. continue;
  2081. } else {
  2082. err('Expected authority, got: ' + c);
  2083. }
  2084. break;
  2085. case 'authority':
  2086. if ('@' === c) {
  2087. if (seenAt) {
  2088. err('@ already seen.');
  2089. buffer += '%40';
  2090. }
  2091. seenAt = true;
  2092. for (var i = 0; i < buffer.length; i++) {
  2093. var cp = buffer[i];
  2094. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  2095. err('Invalid whitespace in authority.');
  2096. continue;
  2097. }
  2098. // XXX check URL code points
  2099. if (':' === cp && null === this._password) {
  2100. this._password = '';
  2101. continue;
  2102. }
  2103. var tempC = percentEscape(cp);
  2104. if (null !== this._password) {
  2105. this._password += tempC;
  2106. } else {
  2107. this._username += tempC;
  2108. }
  2109. }
  2110. buffer = '';
  2111. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2112. cursor -= buffer.length;
  2113. buffer = '';
  2114. state = 'host';
  2115. continue;
  2116. } else {
  2117. buffer += c;
  2118. }
  2119. break;
  2120. case 'file host':
  2121. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2122. if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
  2123. state = 'relative path';
  2124. } else if (buffer.length === 0) {
  2125. state = 'relative path start';
  2126. } else {
  2127. this._host = IDNAToASCII.call(this, buffer);
  2128. buffer = '';
  2129. state = 'relative path start';
  2130. }
  2131. continue;
  2132. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2133. err('Invalid whitespace in file host.');
  2134. } else {
  2135. buffer += c;
  2136. }
  2137. break;
  2138. case 'host':
  2139. case 'hostname':
  2140. if (':' === c && !seenBracket) {
  2141. // XXX host parsing
  2142. this._host = IDNAToASCII.call(this, buffer);
  2143. buffer = '';
  2144. state = 'port';
  2145. if ('hostname' === stateOverride) {
  2146. break loop;
  2147. }
  2148. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2149. this._host = IDNAToASCII.call(this, buffer);
  2150. buffer = '';
  2151. state = 'relative path start';
  2152. if (stateOverride) {
  2153. break loop;
  2154. }
  2155. continue;
  2156. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2157. if ('[' === c) {
  2158. seenBracket = true;
  2159. } else if (']' === c) {
  2160. seenBracket = false;
  2161. }
  2162. buffer += c;
  2163. } else {
  2164. err('Invalid code point in host/hostname: ' + c);
  2165. }
  2166. break;
  2167. case 'port':
  2168. if (/[0-9]/.test(c)) {
  2169. buffer += c;
  2170. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) {
  2171. if ('' !== buffer) {
  2172. var temp = parseInt(buffer, 10);
  2173. if (temp !== relative[this._scheme]) {
  2174. this._port = temp + '';
  2175. }
  2176. buffer = '';
  2177. }
  2178. if (stateOverride) {
  2179. break loop;
  2180. }
  2181. state = 'relative path start';
  2182. continue;
  2183. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2184. err('Invalid code point in port: ' + c);
  2185. } else {
  2186. invalid.call(this);
  2187. }
  2188. break;
  2189. case 'relative path start':
  2190. if ('\\' === c) {
  2191. err('\'\\\' not allowed in path.');
  2192. }
  2193. state = 'relative path';
  2194. if ('/' !== c && '\\' !== c) {
  2195. continue;
  2196. }
  2197. break;
  2198. case 'relative path':
  2199. if (EOF === c || '/' === c || '\\' === c || !stateOverride && ('?' === c || '#' === c)) {
  2200. if ('\\' === c) {
  2201. err('\\ not allowed in relative path.');
  2202. }
  2203. var tmp;
  2204. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  2205. buffer = tmp;
  2206. }
  2207. if ('..' === buffer) {
  2208. this._path.pop();
  2209. if ('/' !== c && '\\' !== c) {
  2210. this._path.push('');
  2211. }
  2212. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  2213. this._path.push('');
  2214. } else if ('.' !== buffer) {
  2215. if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
  2216. buffer = buffer[0] + ':';
  2217. }
  2218. this._path.push(buffer);
  2219. }
  2220. buffer = '';
  2221. if ('?' === c) {
  2222. this._query = '?';
  2223. state = 'query';
  2224. } else if ('#' === c) {
  2225. this._fragment = '#';
  2226. state = 'fragment';
  2227. }
  2228. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2229. buffer += percentEscape(c);
  2230. }
  2231. break;
  2232. case 'query':
  2233. if (!stateOverride && '#' === c) {
  2234. this._fragment = '#';
  2235. state = 'fragment';
  2236. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2237. this._query += percentEscapeQuery(c);
  2238. }
  2239. break;
  2240. case 'fragment':
  2241. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2242. this._fragment += c;
  2243. }
  2244. break;
  2245. }
  2246. cursor++;
  2247. }
  2248. }
  2249. function clear() {
  2250. this._scheme = '';
  2251. this._schemeData = '';
  2252. this._username = '';
  2253. this._password = null;
  2254. this._host = '';
  2255. this._port = '';
  2256. this._path = [];
  2257. this._query = '';
  2258. this._fragment = '';
  2259. this._isInvalid = false;
  2260. this._isRelative = false;
  2261. }
  2262. // Does not process domain names or IP addresses.
  2263. // Does not handle encoding for the query parameter.
  2264. function JURL(url, base)
  2265. /* , encoding */
  2266. {
  2267. if (base !== undefined && !(base instanceof JURL)) {
  2268. base = new JURL(String(base));
  2269. }
  2270. this._url = url;
  2271. clear.call(this);
  2272. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2273. // encoding = encoding || 'utf-8'
  2274. parse.call(this, input, null, base);
  2275. }
  2276. JURL.prototype = {
  2277. toString: function () {
  2278. return this.href;
  2279. },
  2280. get href() {
  2281. if (this._isInvalid) {
  2282. return this._url;
  2283. }
  2284. var authority = '';
  2285. if ('' !== this._username || null !== this._password) {
  2286. authority = this._username + (null !== this._password ? ':' + this._password : '') + '@';
  2287. }
  2288. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  2289. },
  2290. set href(href) {
  2291. clear.call(this);
  2292. parse.call(this, href);
  2293. },
  2294. get protocol() {
  2295. return this._scheme + ':';
  2296. },
  2297. set protocol(protocol) {
  2298. if (this._isInvalid) {
  2299. return;
  2300. }
  2301. parse.call(this, protocol + ':', 'scheme start');
  2302. },
  2303. get host() {
  2304. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  2305. },
  2306. set host(host) {
  2307. if (this._isInvalid || !this._isRelative) {
  2308. return;
  2309. }
  2310. parse.call(this, host, 'host');
  2311. },
  2312. get hostname() {
  2313. return this._host;
  2314. },
  2315. set hostname(hostname) {
  2316. if (this._isInvalid || !this._isRelative) {
  2317. return;
  2318. }
  2319. parse.call(this, hostname, 'hostname');
  2320. },
  2321. get port() {
  2322. return this._port;
  2323. },
  2324. set port(port) {
  2325. if (this._isInvalid || !this._isRelative) {
  2326. return;
  2327. }
  2328. parse.call(this, port, 'port');
  2329. },
  2330. get pathname() {
  2331. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  2332. },
  2333. set pathname(pathname) {
  2334. if (this._isInvalid || !this._isRelative) {
  2335. return;
  2336. }
  2337. this._path = [];
  2338. parse.call(this, pathname, 'relative path start');
  2339. },
  2340. get search() {
  2341. return this._isInvalid || !this._query || '?' === this._query ? '' : this._query;
  2342. },
  2343. set search(search) {
  2344. if (this._isInvalid || !this._isRelative) {
  2345. return;
  2346. }
  2347. this._query = '?';
  2348. if ('?' === search[0]) {
  2349. search = search.slice(1);
  2350. }
  2351. parse.call(this, search, 'query');
  2352. },
  2353. get hash() {
  2354. return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment;
  2355. },
  2356. set hash(hash) {
  2357. if (this._isInvalid) {
  2358. return;
  2359. }
  2360. this._fragment = '#';
  2361. if ('#' === hash[0]) {
  2362. hash = hash.slice(1);
  2363. }
  2364. parse.call(this, hash, 'fragment');
  2365. },
  2366. get origin() {
  2367. var host;
  2368. if (this._isInvalid || !this._scheme) {
  2369. return '';
  2370. }
  2371. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2372. // Gecko throws error for "data://"
  2373. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2374. // Gecko returns String("") for file: mailto:
  2375. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2376. switch (this._scheme) {
  2377. case 'data':
  2378. case 'file':
  2379. case 'javascript':
  2380. case 'mailto':
  2381. return 'null';
  2382. }
  2383. host = this.host;
  2384. if (!host) {
  2385. return '';
  2386. }
  2387. return this._scheme + '://' + host;
  2388. }
  2389. };
  2390. // Copy over the static methods
  2391. var OriginalURL = scope.URL;
  2392. if (OriginalURL) {
  2393. JURL.createObjectURL = function (blob) {
  2394. // IE extension allows a second optional options argument.
  2395. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2396. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2397. };
  2398. JURL.revokeObjectURL = function (url) {
  2399. OriginalURL.revokeObjectURL(url);
  2400. };
  2401. }
  2402. scope.URL = JURL;
  2403. }(globalScope));
  2404. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2405. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2406. exports.OPS = OPS;
  2407. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2408. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2409. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2410. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2411. exports.AnnotationFlag = AnnotationFlag;
  2412. exports.AnnotationType = AnnotationType;
  2413. exports.FontType = FontType;
  2414. exports.ImageKind = ImageKind;
  2415. exports.InvalidPDFException = InvalidPDFException;
  2416. exports.MessageHandler = MessageHandler;
  2417. exports.MissingDataException = MissingDataException;
  2418. exports.MissingPDFException = MissingPDFException;
  2419. exports.NotImplementedException = NotImplementedException;
  2420. exports.PageViewport = PageViewport;
  2421. exports.PasswordException = PasswordException;
  2422. exports.PasswordResponses = PasswordResponses;
  2423. exports.StatTimer = StatTimer;
  2424. exports.StreamType = StreamType;
  2425. exports.TextRenderingMode = TextRenderingMode;
  2426. exports.UnexpectedResponseException = UnexpectedResponseException;
  2427. exports.UnknownErrorException = UnknownErrorException;
  2428. exports.Util = Util;
  2429. exports.XRefParseException = XRefParseException;
  2430. exports.arrayByteLength = arrayByteLength;
  2431. exports.arraysToBytes = arraysToBytes;
  2432. exports.assert = assert;
  2433. exports.bytesToString = bytesToString;
  2434. exports.createBlob = createBlob;
  2435. exports.createPromiseCapability = createPromiseCapability;
  2436. exports.createObjectURL = createObjectURL;
  2437. exports.deprecated = deprecated;
  2438. exports.error = error;
  2439. exports.getLookupTableFactory = getLookupTableFactory;
  2440. exports.getVerbosityLevel = getVerbosityLevel;
  2441. exports.globalScope = globalScope;
  2442. exports.info = info;
  2443. exports.isArray = isArray;
  2444. exports.isArrayBuffer = isArrayBuffer;
  2445. exports.isBool = isBool;
  2446. exports.isEmptyObj = isEmptyObj;
  2447. exports.isInt = isInt;
  2448. exports.isNum = isNum;
  2449. exports.isString = isString;
  2450. exports.isSpace = isSpace;
  2451. exports.isSameOrigin = isSameOrigin;
  2452. exports.isValidUrl = isValidUrl;
  2453. exports.isLittleEndian = isLittleEndian;
  2454. exports.isEvalSupported = isEvalSupported;
  2455. exports.loadJpegStream = loadJpegStream;
  2456. exports.log2 = log2;
  2457. exports.readInt8 = readInt8;
  2458. exports.readUint16 = readUint16;
  2459. exports.readUint32 = readUint32;
  2460. exports.removeNullCharacters = removeNullCharacters;
  2461. exports.setVerbosityLevel = setVerbosityLevel;
  2462. exports.shadow = shadow;
  2463. exports.string32 = string32;
  2464. exports.stringToBytes = stringToBytes;
  2465. exports.stringToPDFString = stringToPDFString;
  2466. exports.stringToUTF8String = stringToUTF8String;
  2467. exports.utf8StringToString = utf8StringToString;
  2468. exports.warn = warn;
  2469. }));
  2470. (function (root, factory) {
  2471. factory(root.pdfjsDisplayDOMUtils = {}, root.pdfjsSharedUtil);
  2472. }(this, function (exports, sharedUtil) {
  2473. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2474. var warn = sharedUtil.warn;
  2475. /**
  2476. * Optimised CSS custom property getter/setter.
  2477. * @class
  2478. */
  2479. var CustomStyle = function CustomStyleClosure() {
  2480. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2481. // animate-css-transforms-firefox-webkit.html
  2482. // in some versions of IE9 it is critical that ms appear in this list
  2483. // before Moz
  2484. var prefixes = [
  2485. 'ms',
  2486. 'Moz',
  2487. 'Webkit',
  2488. 'O'
  2489. ];
  2490. var _cache = Object.create(null);
  2491. function CustomStyle() {
  2492. }
  2493. CustomStyle.getProp = function get(propName, element) {
  2494. // check cache only when no element is given
  2495. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2496. return _cache[propName];
  2497. }
  2498. element = element || document.documentElement;
  2499. var style = element.style, prefixed, uPropName;
  2500. // test standard property first
  2501. if (typeof style[propName] === 'string') {
  2502. return _cache[propName] = propName;
  2503. }
  2504. // capitalize
  2505. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2506. // test vendor specific properties
  2507. for (var i = 0, l = prefixes.length; i < l; i++) {
  2508. prefixed = prefixes[i] + uPropName;
  2509. if (typeof style[prefixed] === 'string') {
  2510. return _cache[propName] = prefixed;
  2511. }
  2512. }
  2513. //if all fails then set to undefined
  2514. return _cache[propName] = 'undefined';
  2515. };
  2516. CustomStyle.setProp = function set(propName, element, str) {
  2517. var prop = this.getProp(propName);
  2518. if (prop !== 'undefined') {
  2519. element.style[prop] = str;
  2520. }
  2521. };
  2522. return CustomStyle;
  2523. }();
  2524. var hasCanvasTypedArrays;
  2525. hasCanvasTypedArrays = function hasCanvasTypedArrays() {
  2526. var canvas = document.createElement('canvas');
  2527. canvas.width = canvas.height = 1;
  2528. var ctx = canvas.getContext('2d');
  2529. var imageData = ctx.createImageData(1, 1);
  2530. return typeof imageData.data.buffer !== 'undefined';
  2531. };
  2532. var LinkTarget = {
  2533. NONE: 0,
  2534. // Default value.
  2535. SELF: 1,
  2536. BLANK: 2,
  2537. PARENT: 3,
  2538. TOP: 4
  2539. };
  2540. var LinkTargetStringMap = [
  2541. '',
  2542. '_self',
  2543. '_blank',
  2544. '_parent',
  2545. '_top'
  2546. ];
  2547. /**
  2548. * @typedef ExternalLinkParameters
  2549. * @typedef {Object} ExternalLinkParameters
  2550. * @property {string} url - An absolute URL.
  2551. * @property {LinkTarget} target - The link target.
  2552. * @property {string} rel - The link relationship.
  2553. */
  2554. /**
  2555. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2556. * @param {HTMLLinkElement} link - The link element.
  2557. * @param {ExternalLinkParameters} params
  2558. */
  2559. function addLinkAttributes(link, params) {
  2560. var url = params && params.url;
  2561. link.href = link.title = url ? removeNullCharacters(url) : '';
  2562. if (url) {
  2563. var target = params.target;
  2564. if (typeof target === 'undefined') {
  2565. target = getDefaultSetting('externalLinkTarget');
  2566. }
  2567. link.target = LinkTargetStringMap[target];
  2568. var rel = params.rel;
  2569. if (typeof rel === 'undefined') {
  2570. rel = getDefaultSetting('externalLinkRel');
  2571. }
  2572. link.rel = rel;
  2573. }
  2574. }
  2575. // Gets the file name from a given URL.
  2576. function getFilenameFromUrl(url) {
  2577. var anchor = url.indexOf('#');
  2578. var query = url.indexOf('?');
  2579. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  2580. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2581. }
  2582. function getDefaultSetting(id) {
  2583. // The list of the settings and their default is maintained for backward
  2584. // compatibility and shall not be extended or modified. See also global.js.
  2585. var globalSettings = sharedUtil.globalScope.PDFJS;
  2586. switch (id) {
  2587. case 'pdfBug':
  2588. return globalSettings ? globalSettings.pdfBug : false;
  2589. case 'disableAutoFetch':
  2590. return globalSettings ? globalSettings.disableAutoFetch : false;
  2591. case 'disableStream':
  2592. return globalSettings ? globalSettings.disableStream : false;
  2593. case 'disableRange':
  2594. return globalSettings ? globalSettings.disableRange : false;
  2595. case 'disableFontFace':
  2596. return globalSettings ? globalSettings.disableFontFace : false;
  2597. case 'disableCreateObjectURL':
  2598. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2599. case 'disableWebGL':
  2600. return globalSettings ? globalSettings.disableWebGL : true;
  2601. case 'cMapUrl':
  2602. return globalSettings ? globalSettings.cMapUrl : null;
  2603. case 'cMapPacked':
  2604. return globalSettings ? globalSettings.cMapPacked : false;
  2605. case 'postMessageTransfers':
  2606. return globalSettings ? globalSettings.postMessageTransfers : true;
  2607. case 'workerSrc':
  2608. return globalSettings ? globalSettings.workerSrc : null;
  2609. case 'disableWorker':
  2610. return globalSettings ? globalSettings.disableWorker : false;
  2611. case 'maxImageSize':
  2612. return globalSettings ? globalSettings.maxImageSize : -1;
  2613. case 'imageResourcesPath':
  2614. return globalSettings ? globalSettings.imageResourcesPath : '';
  2615. case 'isEvalSupported':
  2616. return globalSettings ? globalSettings.isEvalSupported : true;
  2617. case 'externalLinkTarget':
  2618. if (!globalSettings) {
  2619. return LinkTarget.NONE;
  2620. }
  2621. switch (globalSettings.externalLinkTarget) {
  2622. case LinkTarget.NONE:
  2623. case LinkTarget.SELF:
  2624. case LinkTarget.BLANK:
  2625. case LinkTarget.PARENT:
  2626. case LinkTarget.TOP:
  2627. return globalSettings.externalLinkTarget;
  2628. }
  2629. warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  2630. // Reset the external link target, to suppress further warnings.
  2631. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2632. return LinkTarget.NONE;
  2633. case 'externalLinkRel':
  2634. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2635. case 'enableStats':
  2636. return !!(globalSettings && globalSettings.enableStats);
  2637. default:
  2638. throw new Error('Unknown default setting: ' + id);
  2639. }
  2640. }
  2641. function isExternalLinkTargetSet() {
  2642. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2643. switch (externalLinkTarget) {
  2644. case LinkTarget.NONE:
  2645. return false;
  2646. case LinkTarget.SELF:
  2647. case LinkTarget.BLANK:
  2648. case LinkTarget.PARENT:
  2649. case LinkTarget.TOP:
  2650. return true;
  2651. }
  2652. }
  2653. exports.CustomStyle = CustomStyle;
  2654. exports.addLinkAttributes = addLinkAttributes;
  2655. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2656. exports.getFilenameFromUrl = getFilenameFromUrl;
  2657. exports.LinkTarget = LinkTarget;
  2658. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2659. exports.getDefaultSetting = getDefaultSetting;
  2660. }));
  2661. (function (root, factory) {
  2662. factory(root.pdfjsDisplayFontLoader = {}, root.pdfjsSharedUtil);
  2663. }(this, function (exports, sharedUtil) {
  2664. var assert = sharedUtil.assert;
  2665. var bytesToString = sharedUtil.bytesToString;
  2666. var string32 = sharedUtil.string32;
  2667. var shadow = sharedUtil.shadow;
  2668. var warn = sharedUtil.warn;
  2669. function FontLoader(docId) {
  2670. this.docId = docId;
  2671. this.styleElement = null;
  2672. this.nativeFontFaces = [];
  2673. this.loadTestFontId = 0;
  2674. this.loadingContext = {
  2675. requests: [],
  2676. nextRequestId: 0
  2677. };
  2678. }
  2679. FontLoader.prototype = {
  2680. insertRule: function fontLoaderInsertRule(rule) {
  2681. var styleElement = this.styleElement;
  2682. if (!styleElement) {
  2683. styleElement = this.styleElement = document.createElement('style');
  2684. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2685. document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
  2686. }
  2687. var styleSheet = styleElement.sheet;
  2688. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2689. },
  2690. clear: function fontLoaderClear() {
  2691. var styleElement = this.styleElement;
  2692. if (styleElement) {
  2693. styleElement.parentNode.removeChild(styleElement);
  2694. styleElement = this.styleElement = null;
  2695. }
  2696. this.nativeFontFaces.forEach(function (nativeFontFace) {
  2697. document.fonts.delete(nativeFontFace);
  2698. });
  2699. this.nativeFontFaces.length = 0;
  2700. }
  2701. };
  2702. var getLoadTestFont = function () {
  2703. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2704. // height.
  2705. return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==');
  2706. };
  2707. Object.defineProperty(FontLoader.prototype, 'loadTestFont', {
  2708. get: function () {
  2709. return shadow(this, 'loadTestFont', getLoadTestFont());
  2710. },
  2711. configurable: true
  2712. });
  2713. FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) {
  2714. this.nativeFontFaces.push(nativeFontFace);
  2715. document.fonts.add(nativeFontFace);
  2716. };
  2717. FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) {
  2718. var rules = [];
  2719. var fontsToLoad = [];
  2720. var fontLoadPromises = [];
  2721. var getNativeFontPromise = function (nativeFontFace) {
  2722. // Return a promise that is always fulfilled, even when the font fails to
  2723. // load.
  2724. return nativeFontFace.loaded.catch(function (e) {
  2725. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2726. });
  2727. };
  2728. // Firefox Font Loading API does not work with mozPrintCallback --
  2729. // disabling it in this case.
  2730. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported;
  2731. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2732. var font = fonts[i];
  2733. // Add the font to the DOM only once or skip if the font
  2734. // is already loaded.
  2735. if (font.attached || font.loading === false) {
  2736. continue;
  2737. }
  2738. font.attached = true;
  2739. if (isFontLoadingAPISupported) {
  2740. var nativeFontFace = font.createNativeFontFace();
  2741. if (nativeFontFace) {
  2742. this.addNativeFontFace(nativeFontFace);
  2743. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2744. }
  2745. } else {
  2746. var rule = font.createFontFaceRule();
  2747. if (rule) {
  2748. this.insertRule(rule);
  2749. rules.push(rule);
  2750. fontsToLoad.push(font);
  2751. }
  2752. }
  2753. }
  2754. var request = this.queueLoadingCallback(callback);
  2755. if (isFontLoadingAPISupported) {
  2756. Promise.all(fontLoadPromises).then(function () {
  2757. request.complete();
  2758. });
  2759. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2760. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2761. } else {
  2762. request.complete();
  2763. }
  2764. };
  2765. FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) {
  2766. function LoadLoader_completeRequest() {
  2767. assert(!request.end, 'completeRequest() cannot be called twice');
  2768. request.end = Date.now();
  2769. // sending all completed requests in order how they were queued
  2770. while (context.requests.length > 0 && context.requests[0].end) {
  2771. var otherRequest = context.requests.shift();
  2772. setTimeout(otherRequest.callback, 0);
  2773. }
  2774. }
  2775. var context = this.loadingContext;
  2776. var requestId = 'pdfjs-font-loading-' + context.nextRequestId++;
  2777. var request = {
  2778. id: requestId,
  2779. complete: LoadLoader_completeRequest,
  2780. callback: callback,
  2781. started: Date.now()
  2782. };
  2783. context.requests.push(request);
  2784. return request;
  2785. };
  2786. FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) {
  2787. /** Hack begin */
  2788. // There's currently no event when a font has finished downloading so the
  2789. // following code is a dirty hack to 'guess' when a font is
  2790. // ready. It's assumed fonts are loaded in order, so add a known test
  2791. // font after the desired fonts and then test for the loading of that
  2792. // test font.
  2793. function int32(data, offset) {
  2794. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  2795. }
  2796. function spliceString(s, offset, remove, insert) {
  2797. var chunk1 = s.substr(0, offset);
  2798. var chunk2 = s.substr(offset + remove);
  2799. return chunk1 + insert + chunk2;
  2800. }
  2801. var i, ii;
  2802. var canvas = document.createElement('canvas');
  2803. canvas.width = 1;
  2804. canvas.height = 1;
  2805. var ctx = canvas.getContext('2d');
  2806. var called = 0;
  2807. function isFontReady(name, callback) {
  2808. called++;
  2809. // With setTimeout clamping this gives the font ~100ms to load.
  2810. if (called > 30) {
  2811. warn('Load test font never loaded.');
  2812. callback();
  2813. return;
  2814. }
  2815. ctx.font = '30px ' + name;
  2816. ctx.fillText('.', 0, 20);
  2817. var imageData = ctx.getImageData(0, 0, 1, 1);
  2818. if (imageData.data[3] > 0) {
  2819. callback();
  2820. return;
  2821. }
  2822. setTimeout(isFontReady.bind(null, name, callback));
  2823. }
  2824. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2825. // Chromium seems to cache fonts based on a hash of the actual font data,
  2826. // so the font must be modified for each load test else it will appear to
  2827. // be loaded already.
  2828. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2829. // font by splitting it in chunks before hand and padding the font id.
  2830. var data = this.loadTestFont;
  2831. var COMMENT_OFFSET = 976;
  2832. // has to be on 4 byte boundary (for checksum)
  2833. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  2834. // CFF checksum is important for IE, adjusting it
  2835. var CFF_CHECKSUM_OFFSET = 16;
  2836. var XXXX_VALUE = 0x58585858;
  2837. // the "comment" filled with 'X'
  2838. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2839. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2840. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  2841. }
  2842. if (i < loadTestFontId.length) {
  2843. // align to 4 bytes boundary
  2844. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
  2845. }
  2846. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2847. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2848. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}';
  2849. this.insertRule(rule);
  2850. var names = [];
  2851. for (i = 0, ii = fonts.length; i < ii; i++) {
  2852. names.push(fonts[i].loadedName);
  2853. }
  2854. names.push(loadTestFontId);
  2855. var div = document.createElement('div');
  2856. div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
  2857. for (i = 0, ii = names.length; i < ii; ++i) {
  2858. var span = document.createElement('span');
  2859. span.textContent = 'Hi';
  2860. span.style.fontFamily = names[i];
  2861. div.appendChild(span);
  2862. }
  2863. document.body.appendChild(div);
  2864. isFontReady(loadTestFontId, function () {
  2865. document.body.removeChild(div);
  2866. request.complete();
  2867. });
  2868. };
  2869. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts;
  2870. var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() {
  2871. if (typeof navigator === 'undefined') {
  2872. // node.js - we can pretend sync font loading is supported.
  2873. return true;
  2874. }
  2875. var supported = false;
  2876. // User agent string sniffing is bad, but there is no reliable way to tell
  2877. // if font is fully loaded and ready to be used with canvas.
  2878. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2879. if (m && m[1] >= 14) {
  2880. supported = true;
  2881. }
  2882. // TODO other browsers
  2883. return supported;
  2884. };
  2885. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2886. get: function () {
  2887. return shadow(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported());
  2888. },
  2889. enumerable: true,
  2890. configurable: true
  2891. });
  2892. var IsEvalSupportedCached = {
  2893. get value() {
  2894. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2895. }
  2896. };
  2897. var FontFaceObject = function FontFaceObjectClosure() {
  2898. function FontFaceObject(translatedData, options) {
  2899. this.compiledGlyphs = Object.create(null);
  2900. // importing translated data
  2901. for (var i in translatedData) {
  2902. this[i] = translatedData[i];
  2903. }
  2904. this.options = options;
  2905. }
  2906. FontFaceObject.prototype = {
  2907. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2908. if (!this.data) {
  2909. return null;
  2910. }
  2911. if (this.options.disableFontFace) {
  2912. this.disableFontFace = true;
  2913. return null;
  2914. }
  2915. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2916. if (this.options.fontRegistry) {
  2917. this.options.fontRegistry.registerFont(this);
  2918. }
  2919. return nativeFontFace;
  2920. },
  2921. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2922. if (!this.data) {
  2923. return null;
  2924. }
  2925. if (this.options.disableFontFace) {
  2926. this.disableFontFace = true;
  2927. return null;
  2928. }
  2929. var data = bytesToString(new Uint8Array(this.data));
  2930. var fontName = this.loadedName;
  2931. // Add the font-face rule to the document
  2932. var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');';
  2933. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2934. if (this.options.fontRegistry) {
  2935. this.options.fontRegistry.registerFont(this, url);
  2936. }
  2937. return rule;
  2938. },
  2939. getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) {
  2940. if (!(character in this.compiledGlyphs)) {
  2941. var cmds = objs.get(this.loadedName + '_path_' + character);
  2942. var current, i, len;
  2943. // If we can, compile cmds into JS for MAXIMUM SPEED
  2944. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2945. var args, js = '';
  2946. for (i = 0, len = cmds.length; i < len; i++) {
  2947. current = cmds[i];
  2948. if (current.args !== undefined) {
  2949. args = current.args.join(',');
  2950. } else {
  2951. args = '';
  2952. }
  2953. js += 'c.' + current.cmd + '(' + args + ');\n';
  2954. }
  2955. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2956. } else {
  2957. // But fall back on using Function.prototype.apply() if we're
  2958. // blocked from using eval() for whatever reason (like CSP policies)
  2959. this.compiledGlyphs[character] = function (c, size) {
  2960. for (i = 0, len = cmds.length; i < len; i++) {
  2961. current = cmds[i];
  2962. if (current.cmd === 'scale') {
  2963. current.args = [
  2964. size,
  2965. -size
  2966. ];
  2967. }
  2968. c[current.cmd].apply(c, current.args);
  2969. }
  2970. };
  2971. }
  2972. }
  2973. return this.compiledGlyphs[character];
  2974. }
  2975. };
  2976. return FontFaceObject;
  2977. }();
  2978. exports.FontFaceObject = FontFaceObject;
  2979. exports.FontLoader = FontLoader;
  2980. }));
  2981. (function (root, factory) {
  2982. factory(root.pdfjsDisplayMetadata = {}, root.pdfjsSharedUtil);
  2983. }(this, function (exports, sharedUtil) {
  2984. var error = sharedUtil.error;
  2985. function fixMetadata(meta) {
  2986. return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
  2987. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
  2988. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2989. });
  2990. var chars = '';
  2991. for (var i = 0; i < bytes.length; i += 2) {
  2992. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2993. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2994. }
  2995. return '>' + chars;
  2996. });
  2997. }
  2998. function Metadata(meta) {
  2999. if (typeof meta === 'string') {
  3000. // Ghostscript produces invalid metadata
  3001. meta = fixMetadata(meta);
  3002. var parser = new DOMParser();
  3003. meta = parser.parseFromString(meta, 'application/xml');
  3004. } else if (!(meta instanceof Document)) {
  3005. error('Metadata: Invalid metadata object');
  3006. }
  3007. this.metaDocument = meta;
  3008. this.metadata = Object.create(null);
  3009. this.parse();
  3010. }
  3011. Metadata.prototype = {
  3012. parse: function Metadata_parse() {
  3013. var doc = this.metaDocument;
  3014. var rdf = doc.documentElement;
  3015. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3016. // Wrapped in <xmpmeta>
  3017. rdf = rdf.firstChild;
  3018. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3019. rdf = rdf.nextSibling;
  3020. }
  3021. }
  3022. var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
  3023. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3024. return;
  3025. }
  3026. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3027. for (i = 0, length = children.length; i < length; i++) {
  3028. desc = children[i];
  3029. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3030. continue;
  3031. }
  3032. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3033. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3034. entry = desc.childNodes[ii];
  3035. name = entry.nodeName.toLowerCase();
  3036. this.metadata[name] = entry.textContent.trim();
  3037. }
  3038. }
  3039. }
  3040. },
  3041. get: function Metadata_get(name) {
  3042. return this.metadata[name] || null;
  3043. },
  3044. has: function Metadata_has(name) {
  3045. return typeof this.metadata[name] !== 'undefined';
  3046. }
  3047. };
  3048. exports.Metadata = Metadata;
  3049. }));
  3050. (function (root, factory) {
  3051. factory(root.pdfjsDisplaySVG = {}, root.pdfjsSharedUtil);
  3052. }(this, function (exports, sharedUtil) {
  3053. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3054. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3055. var ImageKind = sharedUtil.ImageKind;
  3056. var OPS = sharedUtil.OPS;
  3057. var Util = sharedUtil.Util;
  3058. var isNum = sharedUtil.isNum;
  3059. var isArray = sharedUtil.isArray;
  3060. var warn = sharedUtil.warn;
  3061. var createObjectURL = sharedUtil.createObjectURL;
  3062. var SVG_DEFAULTS = {
  3063. fontStyle: 'normal',
  3064. fontWeight: 'normal',
  3065. fillColor: '#000000'
  3066. };
  3067. var convertImgDataToPng = function convertImgDataToPngClosure() {
  3068. var PNG_HEADER = new Uint8Array([
  3069. 0x89,
  3070. 0x50,
  3071. 0x4e,
  3072. 0x47,
  3073. 0x0d,
  3074. 0x0a,
  3075. 0x1a,
  3076. 0x0a
  3077. ]);
  3078. var CHUNK_WRAPPER_SIZE = 12;
  3079. var crcTable = new Int32Array(256);
  3080. for (var i = 0; i < 256; i++) {
  3081. var c = i;
  3082. for (var h = 0; h < 8; h++) {
  3083. if (c & 1) {
  3084. c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
  3085. } else {
  3086. c = c >> 1 & 0x7fffffff;
  3087. }
  3088. }
  3089. crcTable[i] = c;
  3090. }
  3091. function crc32(data, start, end) {
  3092. var crc = -1;
  3093. for (var i = start; i < end; i++) {
  3094. var a = (crc ^ data[i]) & 0xff;
  3095. var b = crcTable[a];
  3096. crc = crc >>> 8 ^ b;
  3097. }
  3098. return crc ^ -1;
  3099. }
  3100. function writePngChunk(type, body, data, offset) {
  3101. var p = offset;
  3102. var len = body.length;
  3103. data[p] = len >> 24 & 0xff;
  3104. data[p + 1] = len >> 16 & 0xff;
  3105. data[p + 2] = len >> 8 & 0xff;
  3106. data[p + 3] = len & 0xff;
  3107. p += 4;
  3108. data[p] = type.charCodeAt(0) & 0xff;
  3109. data[p + 1] = type.charCodeAt(1) & 0xff;
  3110. data[p + 2] = type.charCodeAt(2) & 0xff;
  3111. data[p + 3] = type.charCodeAt(3) & 0xff;
  3112. p += 4;
  3113. data.set(body, p);
  3114. p += body.length;
  3115. var crc = crc32(data, offset + 4, p);
  3116. data[p] = crc >> 24 & 0xff;
  3117. data[p + 1] = crc >> 16 & 0xff;
  3118. data[p + 2] = crc >> 8 & 0xff;
  3119. data[p + 3] = crc & 0xff;
  3120. }
  3121. function adler32(data, start, end) {
  3122. var a = 1;
  3123. var b = 0;
  3124. for (var i = start; i < end; ++i) {
  3125. a = (a + (data[i] & 0xff)) % 65521;
  3126. b = (b + a) % 65521;
  3127. }
  3128. return b << 16 | a;
  3129. }
  3130. function encode(imgData, kind, forceDataSchema) {
  3131. var width = imgData.width;
  3132. var height = imgData.height;
  3133. var bitDepth, colorType, lineSize;
  3134. var bytes = imgData.data;
  3135. switch (kind) {
  3136. case ImageKind.GRAYSCALE_1BPP:
  3137. colorType = 0;
  3138. bitDepth = 1;
  3139. lineSize = width + 7 >> 3;
  3140. break;
  3141. case ImageKind.RGB_24BPP:
  3142. colorType = 2;
  3143. bitDepth = 8;
  3144. lineSize = width * 3;
  3145. break;
  3146. case ImageKind.RGBA_32BPP:
  3147. colorType = 6;
  3148. bitDepth = 8;
  3149. lineSize = width * 4;
  3150. break;
  3151. default:
  3152. throw new Error('invalid format');
  3153. }
  3154. // prefix every row with predictor 0
  3155. var literals = new Uint8Array((1 + lineSize) * height);
  3156. var offsetLiterals = 0, offsetBytes = 0;
  3157. var y, i;
  3158. for (y = 0; y < height; ++y) {
  3159. literals[offsetLiterals++] = 0;
  3160. // no prediction
  3161. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  3162. offsetBytes += lineSize;
  3163. offsetLiterals += lineSize;
  3164. }
  3165. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3166. // inverting for B/W
  3167. offsetLiterals = 0;
  3168. for (y = 0; y < height; y++) {
  3169. offsetLiterals++;
  3170. // skipping predictor
  3171. for (i = 0; i < lineSize; i++) {
  3172. literals[offsetLiterals++] ^= 0xFF;
  3173. }
  3174. }
  3175. }
  3176. var ihdr = new Uint8Array([
  3177. width >> 24 & 0xff,
  3178. width >> 16 & 0xff,
  3179. width >> 8 & 0xff,
  3180. width & 0xff,
  3181. height >> 24 & 0xff,
  3182. height >> 16 & 0xff,
  3183. height >> 8 & 0xff,
  3184. height & 0xff,
  3185. bitDepth,
  3186. // bit depth
  3187. colorType,
  3188. // color type
  3189. 0x00,
  3190. // compression method
  3191. 0x00,
  3192. // filter method
  3193. 0x00
  3194. ]);
  3195. // interlace method
  3196. var len = literals.length;
  3197. var maxBlockLength = 0xFFFF;
  3198. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3199. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3200. var pi = 0;
  3201. idat[pi++] = 0x78;
  3202. // compression method and flags
  3203. idat[pi++] = 0x9c;
  3204. // flags
  3205. var pos = 0;
  3206. while (len > maxBlockLength) {
  3207. // writing non-final DEFLATE blocks type 0 and length of 65535
  3208. idat[pi++] = 0x00;
  3209. idat[pi++] = 0xff;
  3210. idat[pi++] = 0xff;
  3211. idat[pi++] = 0x00;
  3212. idat[pi++] = 0x00;
  3213. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3214. pi += maxBlockLength;
  3215. pos += maxBlockLength;
  3216. len -= maxBlockLength;
  3217. }
  3218. // writing non-final DEFLATE blocks type 0
  3219. idat[pi++] = 0x01;
  3220. idat[pi++] = len & 0xff;
  3221. idat[pi++] = len >> 8 & 0xff;
  3222. idat[pi++] = ~len & 0xffff & 0xff;
  3223. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3224. idat.set(literals.subarray(pos), pi);
  3225. pi += literals.length - pos;
  3226. var adler = adler32(literals, 0, literals.length);
  3227. // checksum
  3228. idat[pi++] = adler >> 24 & 0xff;
  3229. idat[pi++] = adler >> 16 & 0xff;
  3230. idat[pi++] = adler >> 8 & 0xff;
  3231. idat[pi++] = adler & 0xff;
  3232. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3233. var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  3234. var data = new Uint8Array(pngLength);
  3235. var offset = 0;
  3236. data.set(PNG_HEADER, offset);
  3237. offset += PNG_HEADER.length;
  3238. writePngChunk('IHDR', ihdr, data, offset);
  3239. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3240. writePngChunk('IDATA', idat, data, offset);
  3241. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3242. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3243. return createObjectURL(data, 'image/png', forceDataSchema);
  3244. }
  3245. return function convertImgDataToPng(imgData, forceDataSchema) {
  3246. var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
  3247. return encode(imgData, kind, forceDataSchema);
  3248. };
  3249. }();
  3250. var SVGExtraState = function SVGExtraStateClosure() {
  3251. function SVGExtraState() {
  3252. this.fontSizeScale = 1;
  3253. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3254. this.fontSize = 0;
  3255. this.textMatrix = IDENTITY_MATRIX;
  3256. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3257. this.leading = 0;
  3258. // Current point (in user coordinates)
  3259. this.x = 0;
  3260. this.y = 0;
  3261. // Start of text line (in text coordinates)
  3262. this.lineX = 0;
  3263. this.lineY = 0;
  3264. // Character and word spacing
  3265. this.charSpacing = 0;
  3266. this.wordSpacing = 0;
  3267. this.textHScale = 1;
  3268. this.textRise = 0;
  3269. // Default foreground and background colors
  3270. this.fillColor = SVG_DEFAULTS.fillColor;
  3271. this.strokeColor = '#000000';
  3272. this.fillAlpha = 1;
  3273. this.strokeAlpha = 1;
  3274. this.lineWidth = 1;
  3275. this.lineJoin = '';
  3276. this.lineCap = '';
  3277. this.miterLimit = 0;
  3278. this.dashArray = [];
  3279. this.dashPhase = 0;
  3280. this.dependencies = [];
  3281. // Clipping
  3282. this.activeClipUrl = null;
  3283. this.clipGroup = null;
  3284. this.maskId = '';
  3285. }
  3286. SVGExtraState.prototype = {
  3287. clone: function SVGExtraState_clone() {
  3288. return Object.create(this);
  3289. },
  3290. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3291. this.x = x;
  3292. this.y = y;
  3293. }
  3294. };
  3295. return SVGExtraState;
  3296. }();
  3297. var SVGGraphics = function SVGGraphicsClosure() {
  3298. function opListToTree(opList) {
  3299. var opTree = [];
  3300. var tmp = [];
  3301. var opListLen = opList.length;
  3302. for (var x = 0; x < opListLen; x++) {
  3303. if (opList[x].fn === 'save') {
  3304. opTree.push({
  3305. 'fnId': 92,
  3306. 'fn': 'group',
  3307. 'items': []
  3308. });
  3309. tmp.push(opTree);
  3310. opTree = opTree[opTree.length - 1].items;
  3311. continue;
  3312. }
  3313. if (opList[x].fn === 'restore') {
  3314. opTree = tmp.pop();
  3315. } else {
  3316. opTree.push(opList[x]);
  3317. }
  3318. }
  3319. return opTree;
  3320. }
  3321. /**
  3322. * Formats float number.
  3323. * @param value {number} number to format.
  3324. * @returns {string}
  3325. */
  3326. function pf(value) {
  3327. if (value === (value | 0)) {
  3328. // integer number
  3329. return value.toString();
  3330. }
  3331. var s = value.toFixed(10);
  3332. var i = s.length - 1;
  3333. if (s[i] !== '0') {
  3334. return s;
  3335. }
  3336. // removing trailing zeros
  3337. do {
  3338. i--;
  3339. } while (s[i] === '0');
  3340. return s.substr(0, s[i] === '.' ? i : i + 1);
  3341. }
  3342. /**
  3343. * Formats transform matrix. The standard rotation, scale and translate
  3344. * matrices are replaced by their shorter forms, and for identity matrix
  3345. * returns empty string to save the memory.
  3346. * @param m {Array} matrix to format.
  3347. * @returns {string}
  3348. */
  3349. function pm(m) {
  3350. if (m[4] === 0 && m[5] === 0) {
  3351. if (m[1] === 0 && m[2] === 0) {
  3352. if (m[0] === 1 && m[3] === 1) {
  3353. return '';
  3354. }
  3355. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3356. }
  3357. if (m[0] === m[3] && m[1] === -m[2]) {
  3358. var a = Math.acos(m[0]) * 180 / Math.PI;
  3359. return 'rotate(' + pf(a) + ')';
  3360. }
  3361. } else {
  3362. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3363. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3364. }
  3365. }
  3366. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3367. }
  3368. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3369. this.current = new SVGExtraState();
  3370. this.transformMatrix = IDENTITY_MATRIX;
  3371. // Graphics state matrix
  3372. this.transformStack = [];
  3373. this.extraStack = [];
  3374. this.commonObjs = commonObjs;
  3375. this.objs = objs;
  3376. this.pendingEOFill = false;
  3377. this.embedFonts = false;
  3378. this.embeddedFonts = Object.create(null);
  3379. this.cssStyle = null;
  3380. this.forceDataSchema = !!forceDataSchema;
  3381. }
  3382. var NS = 'http://www.w3.org/2000/svg';
  3383. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3384. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3385. var LINE_CAP_STYLES = [
  3386. 'butt',
  3387. 'round',
  3388. 'square'
  3389. ];
  3390. var LINE_JOIN_STYLES = [
  3391. 'miter',
  3392. 'round',
  3393. 'bevel'
  3394. ];
  3395. var clipCount = 0;
  3396. var maskCount = 0;
  3397. SVGGraphics.prototype = {
  3398. save: function SVGGraphics_save() {
  3399. this.transformStack.push(this.transformMatrix);
  3400. var old = this.current;
  3401. this.extraStack.push(old);
  3402. this.current = old.clone();
  3403. },
  3404. restore: function SVGGraphics_restore() {
  3405. this.transformMatrix = this.transformStack.pop();
  3406. this.current = this.extraStack.pop();
  3407. this.tgrp = null;
  3408. },
  3409. group: function SVGGraphics_group(items) {
  3410. this.save();
  3411. this.executeOpTree(items);
  3412. this.restore();
  3413. },
  3414. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3415. var fnArray = operatorList.fnArray;
  3416. var fnArrayLen = fnArray.length;
  3417. var argsArray = operatorList.argsArray;
  3418. var self = this;
  3419. for (var i = 0; i < fnArrayLen; i++) {
  3420. if (OPS.dependency === fnArray[i]) {
  3421. var deps = argsArray[i];
  3422. for (var n = 0, nn = deps.length; n < nn; n++) {
  3423. var obj = deps[n];
  3424. var common = obj.substring(0, 2) === 'g_';
  3425. var promise;
  3426. if (common) {
  3427. promise = new Promise(function (resolve) {
  3428. self.commonObjs.get(obj, resolve);
  3429. });
  3430. } else {
  3431. promise = new Promise(function (resolve) {
  3432. self.objs.get(obj, resolve);
  3433. });
  3434. }
  3435. this.current.dependencies.push(promise);
  3436. }
  3437. }
  3438. }
  3439. return Promise.all(this.current.dependencies);
  3440. },
  3441. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3442. var transformMatrix = [
  3443. a,
  3444. b,
  3445. c,
  3446. d,
  3447. e,
  3448. f
  3449. ];
  3450. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3451. this.tgrp = null;
  3452. },
  3453. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3454. this.viewport = viewport;
  3455. var svgElement = this._initialize(viewport);
  3456. return this.loadDependencies(operatorList).then(function () {
  3457. this.transformMatrix = IDENTITY_MATRIX;
  3458. var opTree = this.convertOpList(operatorList);
  3459. this.executeOpTree(opTree);
  3460. return svgElement;
  3461. }.bind(this));
  3462. },
  3463. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3464. var argsArray = operatorList.argsArray;
  3465. var fnArray = operatorList.fnArray;
  3466. var fnArrayLen = fnArray.length;
  3467. var REVOPS = [];
  3468. var opList = [];
  3469. for (var op in OPS) {
  3470. REVOPS[OPS[op]] = op;
  3471. }
  3472. for (var x = 0; x < fnArrayLen; x++) {
  3473. var fnId = fnArray[x];
  3474. opList.push({
  3475. 'fnId': fnId,
  3476. 'fn': REVOPS[fnId],
  3477. 'args': argsArray[x]
  3478. });
  3479. }
  3480. return opListToTree(opList);
  3481. },
  3482. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3483. var opTreeLen = opTree.length;
  3484. for (var x = 0; x < opTreeLen; x++) {
  3485. var fn = opTree[x].fn;
  3486. var fnId = opTree[x].fnId;
  3487. var args = opTree[x].args;
  3488. switch (fnId | 0) {
  3489. case OPS.beginText:
  3490. this.beginText();
  3491. break;
  3492. case OPS.setLeading:
  3493. this.setLeading(args);
  3494. break;
  3495. case OPS.setLeadingMoveText:
  3496. this.setLeadingMoveText(args[0], args[1]);
  3497. break;
  3498. case OPS.setFont:
  3499. this.setFont(args);
  3500. break;
  3501. case OPS.showText:
  3502. this.showText(args[0]);
  3503. break;
  3504. case OPS.showSpacedText:
  3505. this.showText(args[0]);
  3506. break;
  3507. case OPS.endText:
  3508. this.endText();
  3509. break;
  3510. case OPS.moveText:
  3511. this.moveText(args[0], args[1]);
  3512. break;
  3513. case OPS.setCharSpacing:
  3514. this.setCharSpacing(args[0]);
  3515. break;
  3516. case OPS.setWordSpacing:
  3517. this.setWordSpacing(args[0]);
  3518. break;
  3519. case OPS.setHScale:
  3520. this.setHScale(args[0]);
  3521. break;
  3522. case OPS.setTextMatrix:
  3523. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3524. break;
  3525. case OPS.setLineWidth:
  3526. this.setLineWidth(args[0]);
  3527. break;
  3528. case OPS.setLineJoin:
  3529. this.setLineJoin(args[0]);
  3530. break;
  3531. case OPS.setLineCap:
  3532. this.setLineCap(args[0]);
  3533. break;
  3534. case OPS.setMiterLimit:
  3535. this.setMiterLimit(args[0]);
  3536. break;
  3537. case OPS.setFillRGBColor:
  3538. this.setFillRGBColor(args[0], args[1], args[2]);
  3539. break;
  3540. case OPS.setStrokeRGBColor:
  3541. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3542. break;
  3543. case OPS.setDash:
  3544. this.setDash(args[0], args[1]);
  3545. break;
  3546. case OPS.setGState:
  3547. this.setGState(args[0]);
  3548. break;
  3549. case OPS.fill:
  3550. this.fill();
  3551. break;
  3552. case OPS.eoFill:
  3553. this.eoFill();
  3554. break;
  3555. case OPS.stroke:
  3556. this.stroke();
  3557. break;
  3558. case OPS.fillStroke:
  3559. this.fillStroke();
  3560. break;
  3561. case OPS.eoFillStroke:
  3562. this.eoFillStroke();
  3563. break;
  3564. case OPS.clip:
  3565. this.clip('nonzero');
  3566. break;
  3567. case OPS.eoClip:
  3568. this.clip('evenodd');
  3569. break;
  3570. case OPS.paintSolidColorImageMask:
  3571. this.paintSolidColorImageMask();
  3572. break;
  3573. case OPS.paintJpegXObject:
  3574. this.paintJpegXObject(args[0], args[1], args[2]);
  3575. break;
  3576. case OPS.paintImageXObject:
  3577. this.paintImageXObject(args[0]);
  3578. break;
  3579. case OPS.paintInlineImageXObject:
  3580. this.paintInlineImageXObject(args[0]);
  3581. break;
  3582. case OPS.paintImageMaskXObject:
  3583. this.paintImageMaskXObject(args[0]);
  3584. break;
  3585. case OPS.paintFormXObjectBegin:
  3586. this.paintFormXObjectBegin(args[0], args[1]);
  3587. break;
  3588. case OPS.paintFormXObjectEnd:
  3589. this.paintFormXObjectEnd();
  3590. break;
  3591. case OPS.closePath:
  3592. this.closePath();
  3593. break;
  3594. case OPS.closeStroke:
  3595. this.closeStroke();
  3596. break;
  3597. case OPS.closeFillStroke:
  3598. this.closeFillStroke();
  3599. break;
  3600. case OPS.nextLine:
  3601. this.nextLine();
  3602. break;
  3603. case OPS.transform:
  3604. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3605. break;
  3606. case OPS.constructPath:
  3607. this.constructPath(args[0], args[1]);
  3608. break;
  3609. case OPS.endPath:
  3610. this.endPath();
  3611. break;
  3612. case 92:
  3613. this.group(opTree[x].items);
  3614. break;
  3615. default:
  3616. warn('Unimplemented operator ' + fn);
  3617. break;
  3618. }
  3619. }
  3620. },
  3621. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3622. this.current.wordSpacing = wordSpacing;
  3623. },
  3624. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3625. this.current.charSpacing = charSpacing;
  3626. },
  3627. nextLine: function SVGGraphics_nextLine() {
  3628. this.moveText(0, this.current.leading);
  3629. },
  3630. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3631. var current = this.current;
  3632. this.current.textMatrix = this.current.lineMatrix = [
  3633. a,
  3634. b,
  3635. c,
  3636. d,
  3637. e,
  3638. f
  3639. ];
  3640. this.current.x = this.current.lineX = 0;
  3641. this.current.y = this.current.lineY = 0;
  3642. current.xcoords = [];
  3643. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3644. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3645. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3646. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3647. current.txtElement = document.createElementNS(NS, 'svg:text');
  3648. current.txtElement.appendChild(current.tspan);
  3649. },
  3650. beginText: function SVGGraphics_beginText() {
  3651. this.current.x = this.current.lineX = 0;
  3652. this.current.y = this.current.lineY = 0;
  3653. this.current.textMatrix = IDENTITY_MATRIX;
  3654. this.current.lineMatrix = IDENTITY_MATRIX;
  3655. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3656. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3657. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3658. this.current.xcoords = [];
  3659. },
  3660. moveText: function SVGGraphics_moveText(x, y) {
  3661. var current = this.current;
  3662. this.current.x = this.current.lineX += x;
  3663. this.current.y = this.current.lineY += y;
  3664. current.xcoords = [];
  3665. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3666. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3667. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3668. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3669. },
  3670. showText: function SVGGraphics_showText(glyphs) {
  3671. var current = this.current;
  3672. var font = current.font;
  3673. var fontSize = current.fontSize;
  3674. if (fontSize === 0) {
  3675. return;
  3676. }
  3677. var charSpacing = current.charSpacing;
  3678. var wordSpacing = current.wordSpacing;
  3679. var fontDirection = current.fontDirection;
  3680. var textHScale = current.textHScale * fontDirection;
  3681. var glyphsLength = glyphs.length;
  3682. var vertical = font.vertical;
  3683. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3684. var x = 0, i;
  3685. for (i = 0; i < glyphsLength; ++i) {
  3686. var glyph = glyphs[i];
  3687. if (glyph === null) {
  3688. // word break
  3689. x += fontDirection * wordSpacing;
  3690. continue;
  3691. } else if (isNum(glyph)) {
  3692. x += -glyph * fontSize * 0.001;
  3693. continue;
  3694. }
  3695. current.xcoords.push(current.x + x * textHScale);
  3696. var width = glyph.width;
  3697. var character = glyph.fontChar;
  3698. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3699. x += charWidth;
  3700. current.tspan.textContent += character;
  3701. }
  3702. if (vertical) {
  3703. current.y -= x * textHScale;
  3704. } else {
  3705. current.x += x * textHScale;
  3706. }
  3707. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3708. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3709. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3710. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3711. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3712. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3713. }
  3714. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3715. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3716. }
  3717. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3718. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3719. }
  3720. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3721. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3722. current.txtElement.appendChild(current.tspan);
  3723. current.txtgrp.appendChild(current.txtElement);
  3724. this._ensureTransformGroup().appendChild(current.txtElement);
  3725. },
  3726. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3727. this.setLeading(-y);
  3728. this.moveText(x, y);
  3729. },
  3730. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3731. if (!this.cssStyle) {
  3732. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3733. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3734. this.defs.appendChild(this.cssStyle);
  3735. }
  3736. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3737. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3738. },
  3739. setFont: function SVGGraphics_setFont(details) {
  3740. var current = this.current;
  3741. var fontObj = this.commonObjs.get(details[0]);
  3742. var size = details[1];
  3743. this.current.font = fontObj;
  3744. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3745. this.addFontStyle(fontObj);
  3746. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3747. }
  3748. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3749. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3750. var italic = fontObj.italic ? 'italic' : 'normal';
  3751. if (size < 0) {
  3752. size = -size;
  3753. current.fontDirection = -1;
  3754. } else {
  3755. current.fontDirection = 1;
  3756. }
  3757. current.fontSize = size;
  3758. current.fontFamily = fontObj.loadedName;
  3759. current.fontWeight = bold;
  3760. current.fontStyle = italic;
  3761. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3762. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3763. current.xcoords = [];
  3764. },
  3765. endText: function SVGGraphics_endText() {
  3766. },
  3767. // Path properties
  3768. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3769. this.current.lineWidth = width;
  3770. },
  3771. setLineCap: function SVGGraphics_setLineCap(style) {
  3772. this.current.lineCap = LINE_CAP_STYLES[style];
  3773. },
  3774. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3775. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3776. },
  3777. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3778. this.current.miterLimit = limit;
  3779. },
  3780. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3781. var color = Util.makeCssRgb(r, g, b);
  3782. this.current.strokeColor = color;
  3783. },
  3784. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3785. var color = Util.makeCssRgb(r, g, b);
  3786. this.current.fillColor = color;
  3787. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3788. this.current.xcoords = [];
  3789. },
  3790. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3791. this.current.dashArray = dashArray;
  3792. this.current.dashPhase = dashPhase;
  3793. },
  3794. constructPath: function SVGGraphics_constructPath(ops, args) {
  3795. var current = this.current;
  3796. var x = current.x, y = current.y;
  3797. current.path = document.createElementNS(NS, 'svg:path');
  3798. var d = [];
  3799. var opLength = ops.length;
  3800. for (var i = 0, j = 0; i < opLength; i++) {
  3801. switch (ops[i] | 0) {
  3802. case OPS.rectangle:
  3803. x = args[j++];
  3804. y = args[j++];
  3805. var width = args[j++];
  3806. var height = args[j++];
  3807. var xw = x + width;
  3808. var yh = y + height;
  3809. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3810. break;
  3811. case OPS.moveTo:
  3812. x = args[j++];
  3813. y = args[j++];
  3814. d.push('M', pf(x), pf(y));
  3815. break;
  3816. case OPS.lineTo:
  3817. x = args[j++];
  3818. y = args[j++];
  3819. d.push('L', pf(x), pf(y));
  3820. break;
  3821. case OPS.curveTo:
  3822. x = args[j + 4];
  3823. y = args[j + 5];
  3824. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3825. j += 6;
  3826. break;
  3827. case OPS.curveTo2:
  3828. x = args[j + 2];
  3829. y = args[j + 3];
  3830. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3831. j += 4;
  3832. break;
  3833. case OPS.curveTo3:
  3834. x = args[j + 2];
  3835. y = args[j + 3];
  3836. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3837. j += 4;
  3838. break;
  3839. case OPS.closePath:
  3840. d.push('Z');
  3841. break;
  3842. }
  3843. }
  3844. current.path.setAttributeNS(null, 'd', d.join(' '));
  3845. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3846. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3847. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3848. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3849. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3850. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3851. current.path.setAttributeNS(null, 'fill', 'none');
  3852. this._ensureTransformGroup().appendChild(current.path);
  3853. // Saving a reference in current.element so that it can be addressed
  3854. // in 'fill' and 'stroke'
  3855. current.element = current.path;
  3856. current.setCurrentPoint(x, y);
  3857. },
  3858. endPath: function SVGGraphics_endPath() {
  3859. },
  3860. clip: function SVGGraphics_clip(type) {
  3861. var current = this.current;
  3862. // Add current path to clipping path
  3863. var clipId = 'clippath' + clipCount;
  3864. clipCount++;
  3865. var clipPath = document.createElementNS(NS, 'svg:clipPath');
  3866. clipPath.setAttributeNS(null, 'id', clipId);
  3867. clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3868. var clipElement = current.element.cloneNode();
  3869. if (type === 'evenodd') {
  3870. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3871. } else {
  3872. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3873. }
  3874. clipPath.appendChild(clipElement);
  3875. this.defs.appendChild(clipPath);
  3876. if (current.activeClipUrl) {
  3877. // The previous clipping group content can go out of order -- resetting
  3878. // cached clipGroup's.
  3879. current.clipGroup = null;
  3880. this.extraStack.forEach(function (prev) {
  3881. prev.clipGroup = null;
  3882. });
  3883. }
  3884. current.activeClipUrl = 'url(#' + clipId + ')';
  3885. this.tgrp = null;
  3886. },
  3887. closePath: function SVGGraphics_closePath() {
  3888. var current = this.current;
  3889. var d = current.path.getAttributeNS(null, 'd');
  3890. d += 'Z';
  3891. current.path.setAttributeNS(null, 'd', d);
  3892. },
  3893. setLeading: function SVGGraphics_setLeading(leading) {
  3894. this.current.leading = -leading;
  3895. },
  3896. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3897. this.current.textRise = textRise;
  3898. },
  3899. setHScale: function SVGGraphics_setHScale(scale) {
  3900. this.current.textHScale = scale / 100;
  3901. },
  3902. setGState: function SVGGraphics_setGState(states) {
  3903. for (var i = 0, ii = states.length; i < ii; i++) {
  3904. var state = states[i];
  3905. var key = state[0];
  3906. var value = state[1];
  3907. switch (key) {
  3908. case 'LW':
  3909. this.setLineWidth(value);
  3910. break;
  3911. case 'LC':
  3912. this.setLineCap(value);
  3913. break;
  3914. case 'LJ':
  3915. this.setLineJoin(value);
  3916. break;
  3917. case 'ML':
  3918. this.setMiterLimit(value);
  3919. break;
  3920. case 'D':
  3921. this.setDash(value[0], value[1]);
  3922. break;
  3923. case 'Font':
  3924. this.setFont(value);
  3925. break;
  3926. default:
  3927. warn('Unimplemented graphic state ' + key);
  3928. break;
  3929. }
  3930. }
  3931. },
  3932. fill: function SVGGraphics_fill() {
  3933. var current = this.current;
  3934. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3935. },
  3936. stroke: function SVGGraphics_stroke() {
  3937. var current = this.current;
  3938. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3939. current.element.setAttributeNS(null, 'fill', 'none');
  3940. },
  3941. eoFill: function SVGGraphics_eoFill() {
  3942. var current = this.current;
  3943. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3944. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3945. },
  3946. fillStroke: function SVGGraphics_fillStroke() {
  3947. // Order is important since stroke wants fill to be none.
  3948. // First stroke, then if fill needed, it will be overwritten.
  3949. this.stroke();
  3950. this.fill();
  3951. },
  3952. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3953. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3954. this.fillStroke();
  3955. },
  3956. closeStroke: function SVGGraphics_closeStroke() {
  3957. this.closePath();
  3958. this.stroke();
  3959. },
  3960. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3961. this.closePath();
  3962. this.fillStroke();
  3963. },
  3964. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  3965. var current = this.current;
  3966. var rect = document.createElementNS(NS, 'svg:rect');
  3967. rect.setAttributeNS(null, 'x', '0');
  3968. rect.setAttributeNS(null, 'y', '0');
  3969. rect.setAttributeNS(null, 'width', '1px');
  3970. rect.setAttributeNS(null, 'height', '1px');
  3971. rect.setAttributeNS(null, 'fill', current.fillColor);
  3972. this._ensureTransformGroup().appendChild(rect);
  3973. },
  3974. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3975. var imgObj = this.objs.get(objId);
  3976. var imgEl = document.createElementNS(NS, 'svg:image');
  3977. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3978. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3979. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3980. imgEl.setAttributeNS(null, 'x', '0');
  3981. imgEl.setAttributeNS(null, 'y', pf(-h));
  3982. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3983. this._ensureTransformGroup().appendChild(imgEl);
  3984. },
  3985. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3986. var imgData = this.objs.get(objId);
  3987. if (!imgData) {
  3988. warn('Dependent image isn\'t ready yet');
  3989. return;
  3990. }
  3991. this.paintInlineImageXObject(imgData);
  3992. },
  3993. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3994. var width = imgData.width;
  3995. var height = imgData.height;
  3996. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3997. var cliprect = document.createElementNS(NS, 'svg:rect');
  3998. cliprect.setAttributeNS(null, 'x', '0');
  3999. cliprect.setAttributeNS(null, 'y', '0');
  4000. cliprect.setAttributeNS(null, 'width', pf(width));
  4001. cliprect.setAttributeNS(null, 'height', pf(height));
  4002. this.current.element = cliprect;
  4003. this.clip('nonzero');
  4004. var imgEl = document.createElementNS(NS, 'svg:image');
  4005. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4006. imgEl.setAttributeNS(null, 'x', '0');
  4007. imgEl.setAttributeNS(null, 'y', pf(-height));
  4008. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4009. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4010. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  4011. if (mask) {
  4012. mask.appendChild(imgEl);
  4013. } else {
  4014. this._ensureTransformGroup().appendChild(imgEl);
  4015. }
  4016. },
  4017. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  4018. var current = this.current;
  4019. var width = imgData.width;
  4020. var height = imgData.height;
  4021. var fillColor = current.fillColor;
  4022. current.maskId = 'mask' + maskCount++;
  4023. var mask = document.createElementNS(NS, 'svg:mask');
  4024. mask.setAttributeNS(null, 'id', current.maskId);
  4025. var rect = document.createElementNS(NS, 'svg:rect');
  4026. rect.setAttributeNS(null, 'x', '0');
  4027. rect.setAttributeNS(null, 'y', '0');
  4028. rect.setAttributeNS(null, 'width', pf(width));
  4029. rect.setAttributeNS(null, 'height', pf(height));
  4030. rect.setAttributeNS(null, 'fill', fillColor);
  4031. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  4032. this.defs.appendChild(mask);
  4033. this._ensureTransformGroup().appendChild(rect);
  4034. this.paintInlineImageXObject(imgData, mask);
  4035. },
  4036. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4037. if (isArray(matrix) && matrix.length === 6) {
  4038. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  4039. }
  4040. if (isArray(bbox) && bbox.length === 4) {
  4041. var width = bbox[2] - bbox[0];
  4042. var height = bbox[3] - bbox[1];
  4043. var cliprect = document.createElementNS(NS, 'svg:rect');
  4044. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4045. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4046. cliprect.setAttributeNS(null, 'width', pf(width));
  4047. cliprect.setAttributeNS(null, 'height', pf(height));
  4048. this.current.element = cliprect;
  4049. this.clip('nonzero');
  4050. this.endPath();
  4051. }
  4052. },
  4053. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  4054. },
  4055. /**
  4056. * @private
  4057. */
  4058. _initialize: function SVGGraphics_initialize(viewport) {
  4059. // Create the SVG element.
  4060. var svg = document.createElementNS(NS, 'svg:svg');
  4061. svg.setAttributeNS(null, 'version', '1.1');
  4062. svg.setAttributeNS(null, 'width', viewport.width + 'px');
  4063. svg.setAttributeNS(null, 'height', viewport.height + 'px');
  4064. svg.setAttributeNS(null, 'viewBox', '0 0 ' + viewport.width + ' ' + viewport.height);
  4065. // Create the definitions element.
  4066. var definitions = document.createElementNS(NS, 'svg:defs');
  4067. svg.appendChild(definitions);
  4068. this.defs = definitions;
  4069. // Create the root group element, which acts a container for all other
  4070. // groups and applies the viewport transform.
  4071. var rootGroup = document.createElementNS(NS, 'svg:g');
  4072. rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform));
  4073. svg.appendChild(rootGroup);
  4074. // For the construction of the SVG image we are only interested in the
  4075. // root group, so we expose it as the entry point of the SVG image for
  4076. // the other code in this class.
  4077. this.svg = rootGroup;
  4078. return svg;
  4079. },
  4080. /**
  4081. * @private
  4082. */
  4083. _ensureClipGroup: function SVGGraphics_ensureClipGroup() {
  4084. if (!this.current.clipGroup) {
  4085. var clipGroup = document.createElementNS(NS, 'svg:g');
  4086. clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl);
  4087. this.svg.appendChild(clipGroup);
  4088. this.current.clipGroup = clipGroup;
  4089. }
  4090. return this.current.clipGroup;
  4091. },
  4092. /**
  4093. * @private
  4094. */
  4095. _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() {
  4096. if (!this.tgrp) {
  4097. this.tgrp = document.createElementNS(NS, 'svg:g');
  4098. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4099. if (this.current.activeClipUrl) {
  4100. this._ensureClipGroup().appendChild(this.tgrp);
  4101. } else {
  4102. this.svg.appendChild(this.tgrp);
  4103. }
  4104. }
  4105. return this.tgrp;
  4106. }
  4107. };
  4108. return SVGGraphics;
  4109. }();
  4110. exports.SVGGraphics = SVGGraphics;
  4111. }));
  4112. (function (root, factory) {
  4113. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4114. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4115. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  4116. var AnnotationType = sharedUtil.AnnotationType;
  4117. var Util = sharedUtil.Util;
  4118. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  4119. var LinkTarget = displayDOMUtils.LinkTarget;
  4120. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  4121. var warn = sharedUtil.warn;
  4122. var CustomStyle = displayDOMUtils.CustomStyle;
  4123. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4124. /**
  4125. * @typedef {Object} AnnotationElementParameters
  4126. * @property {Object} data
  4127. * @property {HTMLDivElement} layer
  4128. * @property {PDFPage} page
  4129. * @property {PageViewport} viewport
  4130. * @property {IPDFLinkService} linkService
  4131. * @property {DownloadManager} downloadManager
  4132. * @property {string} imageResourcesPath
  4133. * @property {boolean} renderInteractiveForms
  4134. */
  4135. /**
  4136. * @class
  4137. * @alias AnnotationElementFactory
  4138. */
  4139. function AnnotationElementFactory() {
  4140. }
  4141. AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */
  4142. {
  4143. /**
  4144. * @param {AnnotationElementParameters} parameters
  4145. * @returns {AnnotationElement}
  4146. */
  4147. create: function AnnotationElementFactory_create(parameters) {
  4148. var subtype = parameters.data.annotationType;
  4149. switch (subtype) {
  4150. case AnnotationType.LINK:
  4151. return new LinkAnnotationElement(parameters);
  4152. case AnnotationType.TEXT:
  4153. return new TextAnnotationElement(parameters);
  4154. case AnnotationType.WIDGET:
  4155. var fieldType = parameters.data.fieldType;
  4156. switch (fieldType) {
  4157. case 'Tx':
  4158. return new TextWidgetAnnotationElement(parameters);
  4159. case 'Ch':
  4160. return new ChoiceWidgetAnnotationElement(parameters);
  4161. }
  4162. return new WidgetAnnotationElement(parameters);
  4163. case AnnotationType.POPUP:
  4164. return new PopupAnnotationElement(parameters);
  4165. case AnnotationType.HIGHLIGHT:
  4166. return new HighlightAnnotationElement(parameters);
  4167. case AnnotationType.UNDERLINE:
  4168. return new UnderlineAnnotationElement(parameters);
  4169. case AnnotationType.SQUIGGLY:
  4170. return new SquigglyAnnotationElement(parameters);
  4171. case AnnotationType.STRIKEOUT:
  4172. return new StrikeOutAnnotationElement(parameters);
  4173. case AnnotationType.FILEATTACHMENT:
  4174. return new FileAttachmentAnnotationElement(parameters);
  4175. default:
  4176. return new AnnotationElement(parameters);
  4177. }
  4178. }
  4179. };
  4180. /**
  4181. * @class
  4182. * @alias AnnotationElement
  4183. */
  4184. var AnnotationElement = function AnnotationElementClosure() {
  4185. function AnnotationElement(parameters, isRenderable) {
  4186. this.isRenderable = isRenderable || false;
  4187. this.data = parameters.data;
  4188. this.layer = parameters.layer;
  4189. this.page = parameters.page;
  4190. this.viewport = parameters.viewport;
  4191. this.linkService = parameters.linkService;
  4192. this.downloadManager = parameters.downloadManager;
  4193. this.imageResourcesPath = parameters.imageResourcesPath;
  4194. this.renderInteractiveForms = parameters.renderInteractiveForms;
  4195. if (isRenderable) {
  4196. this.container = this._createContainer();
  4197. }
  4198. }
  4199. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */
  4200. {
  4201. /**
  4202. * Create an empty container for the annotation's HTML element.
  4203. *
  4204. * @private
  4205. * @memberof AnnotationElement
  4206. * @returns {HTMLSectionElement}
  4207. */
  4208. _createContainer: function AnnotationElement_createContainer() {
  4209. var data = this.data, page = this.page, viewport = this.viewport;
  4210. var container = document.createElement('section');
  4211. var width = data.rect[2] - data.rect[0];
  4212. var height = data.rect[3] - data.rect[1];
  4213. container.setAttribute('data-annotation-id', data.id);
  4214. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4215. // position on subsequent calls to `_createContainer` (see issue 6804).
  4216. var rect = Util.normalizeRect([
  4217. data.rect[0],
  4218. page.view[3] - data.rect[1] + page.view[1],
  4219. data.rect[2],
  4220. page.view[3] - data.rect[3] + page.view[1]
  4221. ]);
  4222. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  4223. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  4224. if (data.borderStyle.width > 0) {
  4225. container.style.borderWidth = data.borderStyle.width + 'px';
  4226. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4227. // Underline styles only have a bottom border, so we do not need
  4228. // to adjust for all borders. This yields a similar result as
  4229. // Adobe Acrobat/Reader.
  4230. width = width - 2 * data.borderStyle.width;
  4231. height = height - 2 * data.borderStyle.width;
  4232. }
  4233. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4234. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4235. if (horizontalRadius > 0 || verticalRadius > 0) {
  4236. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4237. CustomStyle.setProp('borderRadius', container, radius);
  4238. }
  4239. switch (data.borderStyle.style) {
  4240. case AnnotationBorderStyleType.SOLID:
  4241. container.style.borderStyle = 'solid';
  4242. break;
  4243. case AnnotationBorderStyleType.DASHED:
  4244. container.style.borderStyle = 'dashed';
  4245. break;
  4246. case AnnotationBorderStyleType.BEVELED:
  4247. warn('Unimplemented border style: beveled');
  4248. break;
  4249. case AnnotationBorderStyleType.INSET:
  4250. warn('Unimplemented border style: inset');
  4251. break;
  4252. case AnnotationBorderStyleType.UNDERLINE:
  4253. container.style.borderBottomStyle = 'solid';
  4254. break;
  4255. default:
  4256. break;
  4257. }
  4258. if (data.color) {
  4259. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  4260. } else {
  4261. // Transparent (invisible) border, so do not draw it at all.
  4262. container.style.borderWidth = 0;
  4263. }
  4264. }
  4265. container.style.left = rect[0] + 'px';
  4266. container.style.top = rect[1] + 'px';
  4267. container.style.width = width + 'px';
  4268. container.style.height = height + 'px';
  4269. return container;
  4270. },
  4271. /**
  4272. * Create a popup for the annotation's HTML element. This is used for
  4273. * annotations that do not have a Popup entry in the dictionary, but
  4274. * are of a type that works with popups (such as Highlight annotations).
  4275. *
  4276. * @private
  4277. * @param {HTMLSectionElement} container
  4278. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4279. * @param {Object} data
  4280. * @memberof AnnotationElement
  4281. */
  4282. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  4283. // If no trigger element is specified, create it.
  4284. if (!trigger) {
  4285. trigger = document.createElement('div');
  4286. trigger.style.height = container.style.height;
  4287. trigger.style.width = container.style.width;
  4288. container.appendChild(trigger);
  4289. }
  4290. var popupElement = new PopupElement({
  4291. container: container,
  4292. trigger: trigger,
  4293. color: data.color,
  4294. title: data.title,
  4295. contents: data.contents,
  4296. hideWrapper: true
  4297. });
  4298. var popup = popupElement.render();
  4299. // Position the popup next to the annotation's container.
  4300. popup.style.left = container.style.width;
  4301. container.appendChild(popup);
  4302. },
  4303. /**
  4304. * Render the annotation's HTML element in the empty container.
  4305. *
  4306. * @public
  4307. * @memberof AnnotationElement
  4308. */
  4309. render: function AnnotationElement_render() {
  4310. throw new Error('Abstract method AnnotationElement.render called');
  4311. }
  4312. };
  4313. return AnnotationElement;
  4314. }();
  4315. /**
  4316. * @class
  4317. * @alias LinkAnnotationElement
  4318. */
  4319. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  4320. function LinkAnnotationElement(parameters) {
  4321. AnnotationElement.call(this, parameters, true);
  4322. }
  4323. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4324. /**
  4325. * Render the link annotation's HTML element in the empty container.
  4326. *
  4327. * @public
  4328. * @memberof LinkAnnotationElement
  4329. * @returns {HTMLSectionElement}
  4330. */
  4331. render: function LinkAnnotationElement_render() {
  4332. this.container.className = 'linkAnnotation';
  4333. var link = document.createElement('a');
  4334. addLinkAttributes(link, {
  4335. url: this.data.url,
  4336. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  4337. });
  4338. if (!this.data.url) {
  4339. if (this.data.action) {
  4340. this._bindNamedAction(link, this.data.action);
  4341. } else {
  4342. this._bindLink(link, this.data.dest || null);
  4343. }
  4344. }
  4345. this.container.appendChild(link);
  4346. return this.container;
  4347. },
  4348. /**
  4349. * Bind internal links to the link element.
  4350. *
  4351. * @private
  4352. * @param {Object} link
  4353. * @param {Object} destination
  4354. * @memberof LinkAnnotationElement
  4355. */
  4356. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4357. var self = this;
  4358. link.href = this.linkService.getDestinationHash(destination);
  4359. link.onclick = function () {
  4360. if (destination) {
  4361. self.linkService.navigateTo(destination);
  4362. }
  4363. return false;
  4364. };
  4365. if (destination) {
  4366. link.className = 'internalLink';
  4367. }
  4368. },
  4369. /**
  4370. * Bind named actions to the link element.
  4371. *
  4372. * @private
  4373. * @param {Object} link
  4374. * @param {Object} action
  4375. * @memberof LinkAnnotationElement
  4376. */
  4377. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  4378. var self = this;
  4379. link.href = this.linkService.getAnchorUrl('');
  4380. link.onclick = function () {
  4381. self.linkService.executeNamedAction(action);
  4382. return false;
  4383. };
  4384. link.className = 'internalLink';
  4385. }
  4386. });
  4387. return LinkAnnotationElement;
  4388. }();
  4389. /**
  4390. * @class
  4391. * @alias TextAnnotationElement
  4392. */
  4393. var TextAnnotationElement = function TextAnnotationElementClosure() {
  4394. function TextAnnotationElement(parameters) {
  4395. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4396. AnnotationElement.call(this, parameters, isRenderable);
  4397. }
  4398. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4399. /**
  4400. * Render the text annotation's HTML element in the empty container.
  4401. *
  4402. * @public
  4403. * @memberof TextAnnotationElement
  4404. * @returns {HTMLSectionElement}
  4405. */
  4406. render: function TextAnnotationElement_render() {
  4407. this.container.className = 'textAnnotation';
  4408. var image = document.createElement('img');
  4409. image.style.height = this.container.style.height;
  4410. image.style.width = this.container.style.width;
  4411. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  4412. image.alt = '[{{type}} Annotation]';
  4413. image.dataset.l10nId = 'text_annotation_type';
  4414. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  4415. if (!this.data.hasPopup) {
  4416. this._createPopup(this.container, image, this.data);
  4417. }
  4418. this.container.appendChild(image);
  4419. return this.container;
  4420. }
  4421. });
  4422. return TextAnnotationElement;
  4423. }();
  4424. /**
  4425. * @class
  4426. * @alias WidgetAnnotationElement
  4427. */
  4428. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4429. function WidgetAnnotationElement(parameters, isRenderable) {
  4430. AnnotationElement.call(this, parameters, isRenderable);
  4431. }
  4432. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4433. /**
  4434. * Render the widget annotation's HTML element in the empty container.
  4435. *
  4436. * @public
  4437. * @memberof WidgetAnnotationElement
  4438. * @returns {HTMLSectionElement}
  4439. */
  4440. render: function WidgetAnnotationElement_render() {
  4441. // Show only the container for unsupported field types.
  4442. return this.container;
  4443. }
  4444. });
  4445. return WidgetAnnotationElement;
  4446. }();
  4447. /**
  4448. * @class
  4449. * @alias TextWidgetAnnotationElement
  4450. */
  4451. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4452. var TEXT_ALIGNMENT = [
  4453. 'left',
  4454. 'center',
  4455. 'right'
  4456. ];
  4457. function TextWidgetAnnotationElement(parameters) {
  4458. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4459. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4460. }
  4461. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4462. /**
  4463. * Render the text widget annotation's HTML element in the empty container.
  4464. *
  4465. * @public
  4466. * @memberof TextWidgetAnnotationElement
  4467. * @returns {HTMLSectionElement}
  4468. */
  4469. render: function TextWidgetAnnotationElement_render() {
  4470. this.container.className = 'textWidgetAnnotation';
  4471. var element = null;
  4472. if (this.renderInteractiveForms) {
  4473. // NOTE: We cannot set the values using `element.value` below, since it
  4474. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4475. // from parsing the elements correctly for the reference tests.
  4476. if (this.data.multiLine) {
  4477. element = document.createElement('textarea');
  4478. element.textContent = this.data.fieldValue;
  4479. } else {
  4480. element = document.createElement('input');
  4481. element.type = 'text';
  4482. element.setAttribute('value', this.data.fieldValue);
  4483. }
  4484. element.disabled = this.data.readOnly;
  4485. if (this.data.maxLen !== null) {
  4486. element.maxLength = this.data.maxLen;
  4487. }
  4488. if (this.data.comb) {
  4489. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4490. var combWidth = fieldWidth / this.data.maxLen;
  4491. element.classList.add('comb');
  4492. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4493. }
  4494. } else {
  4495. element = document.createElement('div');
  4496. element.textContent = this.data.fieldValue;
  4497. element.style.verticalAlign = 'middle';
  4498. element.style.display = 'table-cell';
  4499. var font = null;
  4500. if (this.data.fontRefName) {
  4501. font = this.page.commonObjs.getData(this.data.fontRefName);
  4502. }
  4503. this._setTextStyle(element, font);
  4504. }
  4505. if (this.data.textAlignment !== null) {
  4506. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4507. }
  4508. this.container.appendChild(element);
  4509. return this.container;
  4510. },
  4511. /**
  4512. * Apply text styles to the text in the element.
  4513. *
  4514. * @private
  4515. * @param {HTMLDivElement} element
  4516. * @param {Object} font
  4517. * @memberof TextWidgetAnnotationElement
  4518. */
  4519. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4520. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4521. var style = element.style;
  4522. style.fontSize = this.data.fontSize + 'px';
  4523. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4524. if (!font) {
  4525. return;
  4526. }
  4527. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4528. style.fontStyle = font.italic ? 'italic' : 'normal';
  4529. // Use a reasonable default font if the font doesn't specify a fallback.
  4530. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4531. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4532. style.fontFamily = fontFamily + fallbackName;
  4533. }
  4534. });
  4535. return TextWidgetAnnotationElement;
  4536. }();
  4537. /**
  4538. * @class
  4539. * @alias ChoiceWidgetAnnotationElement
  4540. */
  4541. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4542. function ChoiceWidgetAnnotationElement(parameters) {
  4543. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4544. }
  4545. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4546. /**
  4547. * Render the choice widget annotation's HTML element in the empty
  4548. * container.
  4549. *
  4550. * @public
  4551. * @memberof ChoiceWidgetAnnotationElement
  4552. * @returns {HTMLSectionElement}
  4553. */
  4554. render: function ChoiceWidgetAnnotationElement_render() {
  4555. this.container.className = 'choiceWidgetAnnotation';
  4556. var selectElement = document.createElement('select');
  4557. selectElement.disabled = this.data.readOnly;
  4558. if (!this.data.combo) {
  4559. // List boxes have a size and (optionally) multiple selection.
  4560. selectElement.size = this.data.options.length;
  4561. if (this.data.multiSelect) {
  4562. selectElement.multiple = true;
  4563. }
  4564. }
  4565. // Insert the options into the choice field.
  4566. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4567. var option = this.data.options[i];
  4568. var optionElement = document.createElement('option');
  4569. optionElement.textContent = option.displayValue;
  4570. optionElement.value = option.exportValue;
  4571. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4572. optionElement.setAttribute('selected', true);
  4573. }
  4574. selectElement.appendChild(optionElement);
  4575. }
  4576. this.container.appendChild(selectElement);
  4577. return this.container;
  4578. }
  4579. });
  4580. return ChoiceWidgetAnnotationElement;
  4581. }();
  4582. /**
  4583. * @class
  4584. * @alias PopupAnnotationElement
  4585. */
  4586. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4587. function PopupAnnotationElement(parameters) {
  4588. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4589. AnnotationElement.call(this, parameters, isRenderable);
  4590. }
  4591. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4592. /**
  4593. * Render the popup annotation's HTML element in the empty container.
  4594. *
  4595. * @public
  4596. * @memberof PopupAnnotationElement
  4597. * @returns {HTMLSectionElement}
  4598. */
  4599. render: function PopupAnnotationElement_render() {
  4600. this.container.className = 'popupAnnotation';
  4601. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4602. var parentElement = this.layer.querySelector(selector);
  4603. if (!parentElement) {
  4604. return this.container;
  4605. }
  4606. var popup = new PopupElement({
  4607. container: this.container,
  4608. trigger: parentElement,
  4609. color: this.data.color,
  4610. title: this.data.title,
  4611. contents: this.data.contents
  4612. });
  4613. // Position the popup next to the parent annotation's container.
  4614. // PDF viewers ignore a popup annotation's rectangle.
  4615. var parentLeft = parseFloat(parentElement.style.left);
  4616. var parentWidth = parseFloat(parentElement.style.width);
  4617. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4618. this.container.style.left = parentLeft + parentWidth + 'px';
  4619. this.container.appendChild(popup.render());
  4620. return this.container;
  4621. }
  4622. });
  4623. return PopupAnnotationElement;
  4624. }();
  4625. /**
  4626. * @class
  4627. * @alias PopupElement
  4628. */
  4629. var PopupElement = function PopupElementClosure() {
  4630. var BACKGROUND_ENLIGHT = 0.7;
  4631. function PopupElement(parameters) {
  4632. this.container = parameters.container;
  4633. this.trigger = parameters.trigger;
  4634. this.color = parameters.color;
  4635. this.title = parameters.title;
  4636. this.contents = parameters.contents;
  4637. this.hideWrapper = parameters.hideWrapper || false;
  4638. this.pinned = false;
  4639. }
  4640. PopupElement.prototype = /** @lends PopupElement.prototype */
  4641. {
  4642. /**
  4643. * Render the popup's HTML element.
  4644. *
  4645. * @public
  4646. * @memberof PopupElement
  4647. * @returns {HTMLSectionElement}
  4648. */
  4649. render: function PopupElement_render() {
  4650. var wrapper = document.createElement('div');
  4651. wrapper.className = 'popupWrapper';
  4652. // For Popup annotations we hide the entire section because it contains
  4653. // only the popup. However, for Text annotations without a separate Popup
  4654. // annotation, we cannot hide the entire container as the image would
  4655. // disappear too. In that special case, hiding the wrapper suffices.
  4656. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4657. this.hideElement.setAttribute('hidden', true);
  4658. var popup = document.createElement('div');
  4659. popup.className = 'popup';
  4660. var color = this.color;
  4661. if (color) {
  4662. // Enlighten the color.
  4663. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4664. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4665. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4666. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4667. }
  4668. var contents = this._formatContents(this.contents);
  4669. var title = document.createElement('h1');
  4670. title.textContent = this.title;
  4671. // Attach the event listeners to the trigger element.
  4672. this.trigger.addEventListener('click', this._toggle.bind(this));
  4673. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4674. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4675. popup.addEventListener('click', this._hide.bind(this, true));
  4676. popup.appendChild(title);
  4677. popup.appendChild(contents);
  4678. wrapper.appendChild(popup);
  4679. return wrapper;
  4680. },
  4681. /**
  4682. * Format the contents of the popup by adding newlines where necessary.
  4683. *
  4684. * @private
  4685. * @param {string} contents
  4686. * @memberof PopupElement
  4687. * @returns {HTMLParagraphElement}
  4688. */
  4689. _formatContents: function PopupElement_formatContents(contents) {
  4690. var p = document.createElement('p');
  4691. var lines = contents.split(/(?:\r\n?|\n)/);
  4692. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4693. var line = lines[i];
  4694. p.appendChild(document.createTextNode(line));
  4695. if (i < ii - 1) {
  4696. p.appendChild(document.createElement('br'));
  4697. }
  4698. }
  4699. return p;
  4700. },
  4701. /**
  4702. * Toggle the visibility of the popup.
  4703. *
  4704. * @private
  4705. * @memberof PopupElement
  4706. */
  4707. _toggle: function PopupElement_toggle() {
  4708. if (this.pinned) {
  4709. this._hide(true);
  4710. } else {
  4711. this._show(true);
  4712. }
  4713. },
  4714. /**
  4715. * Show the popup.
  4716. *
  4717. * @private
  4718. * @param {boolean} pin
  4719. * @memberof PopupElement
  4720. */
  4721. _show: function PopupElement_show(pin) {
  4722. if (pin) {
  4723. this.pinned = true;
  4724. }
  4725. if (this.hideElement.hasAttribute('hidden')) {
  4726. this.hideElement.removeAttribute('hidden');
  4727. this.container.style.zIndex += 1;
  4728. }
  4729. },
  4730. /**
  4731. * Hide the popup.
  4732. *
  4733. * @private
  4734. * @param {boolean} unpin
  4735. * @memberof PopupElement
  4736. */
  4737. _hide: function PopupElement_hide(unpin) {
  4738. if (unpin) {
  4739. this.pinned = false;
  4740. }
  4741. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4742. this.hideElement.setAttribute('hidden', true);
  4743. this.container.style.zIndex -= 1;
  4744. }
  4745. }
  4746. };
  4747. return PopupElement;
  4748. }();
  4749. /**
  4750. * @class
  4751. * @alias HighlightAnnotationElement
  4752. */
  4753. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4754. function HighlightAnnotationElement(parameters) {
  4755. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4756. AnnotationElement.call(this, parameters, isRenderable);
  4757. }
  4758. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4759. /**
  4760. * Render the highlight annotation's HTML element in the empty container.
  4761. *
  4762. * @public
  4763. * @memberof HighlightAnnotationElement
  4764. * @returns {HTMLSectionElement}
  4765. */
  4766. render: function HighlightAnnotationElement_render() {
  4767. this.container.className = 'highlightAnnotation';
  4768. if (!this.data.hasPopup) {
  4769. this._createPopup(this.container, null, this.data);
  4770. }
  4771. return this.container;
  4772. }
  4773. });
  4774. return HighlightAnnotationElement;
  4775. }();
  4776. /**
  4777. * @class
  4778. * @alias UnderlineAnnotationElement
  4779. */
  4780. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4781. function UnderlineAnnotationElement(parameters) {
  4782. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4783. AnnotationElement.call(this, parameters, isRenderable);
  4784. }
  4785. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4786. /**
  4787. * Render the underline annotation's HTML element in the empty container.
  4788. *
  4789. * @public
  4790. * @memberof UnderlineAnnotationElement
  4791. * @returns {HTMLSectionElement}
  4792. */
  4793. render: function UnderlineAnnotationElement_render() {
  4794. this.container.className = 'underlineAnnotation';
  4795. if (!this.data.hasPopup) {
  4796. this._createPopup(this.container, null, this.data);
  4797. }
  4798. return this.container;
  4799. }
  4800. });
  4801. return UnderlineAnnotationElement;
  4802. }();
  4803. /**
  4804. * @class
  4805. * @alias SquigglyAnnotationElement
  4806. */
  4807. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4808. function SquigglyAnnotationElement(parameters) {
  4809. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4810. AnnotationElement.call(this, parameters, isRenderable);
  4811. }
  4812. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4813. /**
  4814. * Render the squiggly annotation's HTML element in the empty container.
  4815. *
  4816. * @public
  4817. * @memberof SquigglyAnnotationElement
  4818. * @returns {HTMLSectionElement}
  4819. */
  4820. render: function SquigglyAnnotationElement_render() {
  4821. this.container.className = 'squigglyAnnotation';
  4822. if (!this.data.hasPopup) {
  4823. this._createPopup(this.container, null, this.data);
  4824. }
  4825. return this.container;
  4826. }
  4827. });
  4828. return SquigglyAnnotationElement;
  4829. }();
  4830. /**
  4831. * @class
  4832. * @alias StrikeOutAnnotationElement
  4833. */
  4834. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4835. function StrikeOutAnnotationElement(parameters) {
  4836. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4837. AnnotationElement.call(this, parameters, isRenderable);
  4838. }
  4839. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4840. /**
  4841. * Render the strikeout annotation's HTML element in the empty container.
  4842. *
  4843. * @public
  4844. * @memberof StrikeOutAnnotationElement
  4845. * @returns {HTMLSectionElement}
  4846. */
  4847. render: function StrikeOutAnnotationElement_render() {
  4848. this.container.className = 'strikeoutAnnotation';
  4849. if (!this.data.hasPopup) {
  4850. this._createPopup(this.container, null, this.data);
  4851. }
  4852. return this.container;
  4853. }
  4854. });
  4855. return StrikeOutAnnotationElement;
  4856. }();
  4857. /**
  4858. * @class
  4859. * @alias FileAttachmentAnnotationElement
  4860. */
  4861. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4862. function FileAttachmentAnnotationElement(parameters) {
  4863. AnnotationElement.call(this, parameters, true);
  4864. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4865. this.content = parameters.data.file.content;
  4866. }
  4867. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4868. /**
  4869. * Render the file attachment annotation's HTML element in the empty
  4870. * container.
  4871. *
  4872. * @public
  4873. * @memberof FileAttachmentAnnotationElement
  4874. * @returns {HTMLSectionElement}
  4875. */
  4876. render: function FileAttachmentAnnotationElement_render() {
  4877. this.container.className = 'fileAttachmentAnnotation';
  4878. var trigger = document.createElement('div');
  4879. trigger.style.height = this.container.style.height;
  4880. trigger.style.width = this.container.style.width;
  4881. trigger.addEventListener('dblclick', this._download.bind(this));
  4882. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4883. this._createPopup(this.container, trigger, this.data);
  4884. }
  4885. this.container.appendChild(trigger);
  4886. return this.container;
  4887. },
  4888. /**
  4889. * Download the file attachment associated with this annotation.
  4890. *
  4891. * @private
  4892. * @memberof FileAttachmentAnnotationElement
  4893. */
  4894. _download: function FileAttachmentAnnotationElement_download() {
  4895. if (!this.downloadManager) {
  4896. warn('Download cannot be started due to unavailable download manager');
  4897. return;
  4898. }
  4899. this.downloadManager.downloadData(this.content, this.filename, '');
  4900. }
  4901. });
  4902. return FileAttachmentAnnotationElement;
  4903. }();
  4904. /**
  4905. * @typedef {Object} AnnotationLayerParameters
  4906. * @property {PageViewport} viewport
  4907. * @property {HTMLDivElement} div
  4908. * @property {Array} annotations
  4909. * @property {PDFPage} page
  4910. * @property {IPDFLinkService} linkService
  4911. * @property {string} imageResourcesPath
  4912. * @property {boolean} renderInteractiveForms
  4913. */
  4914. /**
  4915. * @class
  4916. * @alias AnnotationLayer
  4917. */
  4918. var AnnotationLayer = function AnnotationLayerClosure() {
  4919. return {
  4920. /**
  4921. * Render a new annotation layer with all annotation elements.
  4922. *
  4923. * @public
  4924. * @param {AnnotationLayerParameters} parameters
  4925. * @memberof AnnotationLayer
  4926. */
  4927. render: function AnnotationLayer_render(parameters) {
  4928. var annotationElementFactory = new AnnotationElementFactory();
  4929. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4930. var data = parameters.annotations[i];
  4931. if (!data) {
  4932. continue;
  4933. }
  4934. var properties = {
  4935. data: data,
  4936. layer: parameters.div,
  4937. page: parameters.page,
  4938. viewport: parameters.viewport,
  4939. linkService: parameters.linkService,
  4940. downloadManager: parameters.downloadManager,
  4941. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4942. renderInteractiveForms: parameters.renderInteractiveForms || false
  4943. };
  4944. var element = annotationElementFactory.create(properties);
  4945. if (element.isRenderable) {
  4946. parameters.div.appendChild(element.render());
  4947. }
  4948. }
  4949. },
  4950. /**
  4951. * Update the annotation elements on existing annotation layer.
  4952. *
  4953. * @public
  4954. * @param {AnnotationLayerParameters} parameters
  4955. * @memberof AnnotationLayer
  4956. */
  4957. update: function AnnotationLayer_update(parameters) {
  4958. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4959. var data = parameters.annotations[i];
  4960. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4961. if (element) {
  4962. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4963. }
  4964. }
  4965. parameters.div.removeAttribute('hidden');
  4966. }
  4967. };
  4968. }();
  4969. exports.AnnotationLayer = AnnotationLayer;
  4970. }));
  4971. (function (root, factory) {
  4972. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4973. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4974. var Util = sharedUtil.Util;
  4975. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4976. var CustomStyle = displayDOMUtils.CustomStyle;
  4977. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4978. /**
  4979. * Text layer render parameters.
  4980. *
  4981. * @typedef {Object} TextLayerRenderParameters
  4982. * @property {TextContent} textContent - Text content to render (the object is
  4983. * returned by the page's getTextContent() method).
  4984. * @property {HTMLElement} container - HTML element that will contain text runs.
  4985. * @property {PageViewport} viewport - The target viewport to properly
  4986. * layout the text runs.
  4987. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4988. * the text items of the textContent input. This is output and shall be
  4989. * initially be set to empty array.
  4990. * @property {number} timeout - (optional) Delay in milliseconds before
  4991. * rendering of the text runs occurs.
  4992. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4993. * text selection enhancement.
  4994. */
  4995. var renderTextLayer = function renderTextLayerClosure() {
  4996. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4997. var NonWhitespaceRegexp = /\S/;
  4998. function isAllWhitespace(str) {
  4999. return !NonWhitespaceRegexp.test(str);
  5000. }
  5001. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  5002. // creating many intermediate strings when building their 'style' properties.
  5003. var styleBuf = [
  5004. 'left: ',
  5005. 0,
  5006. 'px; top: ',
  5007. 0,
  5008. 'px; font-size: ',
  5009. 0,
  5010. 'px; font-family: ',
  5011. '',
  5012. ';'
  5013. ];
  5014. function appendText(task, geom, styles) {
  5015. // Initialize all used properties to keep the caches monomorphic.
  5016. var textDiv = document.createElement('div');
  5017. var textDivProperties = {
  5018. style: null,
  5019. angle: 0,
  5020. canvasWidth: 0,
  5021. isWhitespace: false,
  5022. originalTransform: null,
  5023. paddingBottom: 0,
  5024. paddingLeft: 0,
  5025. paddingRight: 0,
  5026. paddingTop: 0,
  5027. scale: 1
  5028. };
  5029. task._textDivs.push(textDiv);
  5030. if (isAllWhitespace(geom.str)) {
  5031. textDivProperties.isWhitespace = true;
  5032. task._textDivProperties.set(textDiv, textDivProperties);
  5033. return;
  5034. }
  5035. var tx = Util.transform(task._viewport.transform, geom.transform);
  5036. var angle = Math.atan2(tx[1], tx[0]);
  5037. var style = styles[geom.fontName];
  5038. if (style.vertical) {
  5039. angle += Math.PI / 2;
  5040. }
  5041. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  5042. var fontAscent = fontHeight;
  5043. if (style.ascent) {
  5044. fontAscent = style.ascent * fontAscent;
  5045. } else if (style.descent) {
  5046. fontAscent = (1 + style.descent) * fontAscent;
  5047. }
  5048. var left;
  5049. var top;
  5050. if (angle === 0) {
  5051. left = tx[4];
  5052. top = tx[5] - fontAscent;
  5053. } else {
  5054. left = tx[4] + fontAscent * Math.sin(angle);
  5055. top = tx[5] - fontAscent * Math.cos(angle);
  5056. }
  5057. styleBuf[1] = left;
  5058. styleBuf[3] = top;
  5059. styleBuf[5] = fontHeight;
  5060. styleBuf[7] = style.fontFamily;
  5061. textDivProperties.style = styleBuf.join('');
  5062. textDiv.setAttribute('style', textDivProperties.style);
  5063. textDiv.textContent = geom.str;
  5064. // |fontName| is only used by the Font Inspector. This test will succeed
  5065. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  5066. // not worth the effort to do a more accurate test. We only use `dataset`
  5067. // here to make the font name available for the debugger.
  5068. if (getDefaultSetting('pdfBug')) {
  5069. textDiv.dataset.fontName = geom.fontName;
  5070. }
  5071. if (angle !== 0) {
  5072. textDivProperties.angle = angle * (180 / Math.PI);
  5073. }
  5074. // We don't bother scaling single-char text divs, because it has very
  5075. // little effect on text highlighting. This makes scrolling on docs with
  5076. // lots of such divs a lot faster.
  5077. if (geom.str.length > 1) {
  5078. if (style.vertical) {
  5079. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  5080. } else {
  5081. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  5082. }
  5083. }
  5084. task._textDivProperties.set(textDiv, textDivProperties);
  5085. if (task._enhanceTextSelection) {
  5086. var angleCos = 1, angleSin = 0;
  5087. if (angle !== 0) {
  5088. angleCos = Math.cos(angle);
  5089. angleSin = Math.sin(angle);
  5090. }
  5091. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  5092. var divHeight = fontHeight;
  5093. var m, b;
  5094. if (angle !== 0) {
  5095. m = [
  5096. angleCos,
  5097. angleSin,
  5098. -angleSin,
  5099. angleCos,
  5100. left,
  5101. top
  5102. ];
  5103. b = Util.getAxialAlignedBoundingBox([
  5104. 0,
  5105. 0,
  5106. divWidth,
  5107. divHeight
  5108. ], m);
  5109. } else {
  5110. b = [
  5111. left,
  5112. top,
  5113. left + divWidth,
  5114. top + divHeight
  5115. ];
  5116. }
  5117. task._bounds.push({
  5118. left: b[0],
  5119. top: b[1],
  5120. right: b[2],
  5121. bottom: b[3],
  5122. div: textDiv,
  5123. size: [
  5124. divWidth,
  5125. divHeight
  5126. ],
  5127. m: m
  5128. });
  5129. }
  5130. }
  5131. function render(task) {
  5132. if (task._canceled) {
  5133. return;
  5134. }
  5135. var textLayerFrag = task._container;
  5136. var textDivs = task._textDivs;
  5137. var capability = task._capability;
  5138. var textDivsLength = textDivs.length;
  5139. // No point in rendering many divs as it would make the browser
  5140. // unusable even after the divs are rendered.
  5141. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  5142. task._renderingDone = true;
  5143. capability.resolve();
  5144. return;
  5145. }
  5146. var canvas = document.createElement('canvas');
  5147. canvas.mozOpaque = true;
  5148. var ctx = canvas.getContext('2d', { alpha: false });
  5149. var lastFontSize;
  5150. var lastFontFamily;
  5151. for (var i = 0; i < textDivsLength; i++) {
  5152. var textDiv = textDivs[i];
  5153. var textDivProperties = task._textDivProperties.get(textDiv);
  5154. if (textDivProperties.isWhitespace) {
  5155. continue;
  5156. }
  5157. var fontSize = textDiv.style.fontSize;
  5158. var fontFamily = textDiv.style.fontFamily;
  5159. // Only build font string and set to context if different from last.
  5160. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  5161. ctx.font = fontSize + ' ' + fontFamily;
  5162. lastFontSize = fontSize;
  5163. lastFontFamily = fontFamily;
  5164. }
  5165. var width = ctx.measureText(textDiv.textContent).width;
  5166. textLayerFrag.appendChild(textDiv);
  5167. var transform = '';
  5168. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  5169. textDivProperties.scale = textDivProperties.canvasWidth / width;
  5170. transform = 'scaleX(' + textDivProperties.scale + ')';
  5171. }
  5172. if (textDivProperties.angle !== 0) {
  5173. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  5174. }
  5175. if (transform !== '') {
  5176. textDivProperties.originalTransform = transform;
  5177. CustomStyle.setProp('transform', textDiv, transform);
  5178. }
  5179. task._textDivProperties.set(textDiv, textDivProperties);
  5180. }
  5181. task._renderingDone = true;
  5182. capability.resolve();
  5183. }
  5184. function expand(task) {
  5185. var bounds = task._bounds;
  5186. var viewport = task._viewport;
  5187. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  5188. for (var i = 0; i < expanded.length; i++) {
  5189. var div = bounds[i].div;
  5190. var divProperties = task._textDivProperties.get(div);
  5191. if (divProperties.angle === 0) {
  5192. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  5193. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  5194. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  5195. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  5196. task._textDivProperties.set(div, divProperties);
  5197. continue;
  5198. }
  5199. // Box is rotated -- trying to find padding so rotated div will not
  5200. // exceed its expanded bounds.
  5201. var e = expanded[i], b = bounds[i];
  5202. var m = b.m, c = m[0], s = m[1];
  5203. // Finding intersections with expanded box.
  5204. var points = [
  5205. [
  5206. 0,
  5207. 0
  5208. ],
  5209. [
  5210. 0,
  5211. b.size[1]
  5212. ],
  5213. [
  5214. b.size[0],
  5215. 0
  5216. ],
  5217. b.size
  5218. ];
  5219. var ts = new Float64Array(64);
  5220. points.forEach(function (p, i) {
  5221. var t = Util.applyTransform(p, m);
  5222. ts[i + 0] = c && (e.left - t[0]) / c;
  5223. ts[i + 4] = s && (e.top - t[1]) / s;
  5224. ts[i + 8] = c && (e.right - t[0]) / c;
  5225. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5226. ts[i + 16] = s && (e.left - t[0]) / -s;
  5227. ts[i + 20] = c && (e.top - t[1]) / c;
  5228. ts[i + 24] = s && (e.right - t[0]) / -s;
  5229. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5230. ts[i + 32] = c && (e.left - t[0]) / -c;
  5231. ts[i + 36] = s && (e.top - t[1]) / -s;
  5232. ts[i + 40] = c && (e.right - t[0]) / -c;
  5233. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5234. ts[i + 48] = s && (e.left - t[0]) / s;
  5235. ts[i + 52] = c && (e.top - t[1]) / -c;
  5236. ts[i + 56] = s && (e.right - t[0]) / s;
  5237. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5238. });
  5239. var findPositiveMin = function (ts, offset, count) {
  5240. var result = 0;
  5241. for (var i = 0; i < count; i++) {
  5242. var t = ts[offset++];
  5243. if (t > 0) {
  5244. result = result ? Math.min(t, result) : t;
  5245. }
  5246. }
  5247. return result;
  5248. };
  5249. // Not based on math, but to simplify calculations, using cos and sin
  5250. // absolute values to not exceed the box (it can but insignificantly).
  5251. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5252. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5253. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5254. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5255. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5256. task._textDivProperties.set(div, divProperties);
  5257. }
  5258. }
  5259. function expandBounds(width, height, boxes) {
  5260. var bounds = boxes.map(function (box, i) {
  5261. return {
  5262. x1: box.left,
  5263. y1: box.top,
  5264. x2: box.right,
  5265. y2: box.bottom,
  5266. index: i,
  5267. x1New: undefined,
  5268. x2New: undefined
  5269. };
  5270. });
  5271. expandBoundsLTR(width, bounds);
  5272. var expanded = new Array(boxes.length);
  5273. bounds.forEach(function (b) {
  5274. var i = b.index;
  5275. expanded[i] = {
  5276. left: b.x1New,
  5277. top: 0,
  5278. right: b.x2New,
  5279. bottom: 0
  5280. };
  5281. });
  5282. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5283. // array and objects.
  5284. boxes.map(function (box, i) {
  5285. var e = expanded[i], b = bounds[i];
  5286. b.x1 = box.top;
  5287. b.y1 = width - e.right;
  5288. b.x2 = box.bottom;
  5289. b.y2 = width - e.left;
  5290. b.index = i;
  5291. b.x1New = undefined;
  5292. b.x2New = undefined;
  5293. });
  5294. expandBoundsLTR(height, bounds);
  5295. bounds.forEach(function (b) {
  5296. var i = b.index;
  5297. expanded[i].top = b.x1New;
  5298. expanded[i].bottom = b.x2New;
  5299. });
  5300. return expanded;
  5301. }
  5302. function expandBoundsLTR(width, bounds) {
  5303. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5304. bounds.sort(function (a, b) {
  5305. return a.x1 - b.x1 || a.index - b.index;
  5306. });
  5307. // First we see on the horizon is a fake boundary.
  5308. var fakeBoundary = {
  5309. x1: -Infinity,
  5310. y1: -Infinity,
  5311. x2: 0,
  5312. y2: Infinity,
  5313. index: -1,
  5314. x1New: 0,
  5315. x2New: 0
  5316. };
  5317. var horizon = [{
  5318. start: -Infinity,
  5319. end: Infinity,
  5320. boundary: fakeBoundary
  5321. }];
  5322. bounds.forEach(function (boundary) {
  5323. // Searching for the affected part of horizon.
  5324. // TODO red-black tree or simple binary search
  5325. var i = 0;
  5326. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5327. i++;
  5328. }
  5329. var j = horizon.length - 1;
  5330. while (j >= 0 && horizon[j].start >= boundary.y2) {
  5331. j--;
  5332. }
  5333. var horizonPart, affectedBoundary;
  5334. var q, k, maxXNew = -Infinity;
  5335. for (q = i; q <= j; q++) {
  5336. horizonPart = horizon[q];
  5337. affectedBoundary = horizonPart.boundary;
  5338. var xNew;
  5339. if (affectedBoundary.x2 > boundary.x1) {
  5340. // In the middle of the previous element, new x shall be at the
  5341. // boundary start. Extending if further if the affected bondary
  5342. // placed on top of the current one.
  5343. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  5344. } else if (affectedBoundary.x2New === undefined) {
  5345. // We have some space in between, new x in middle will be a fair
  5346. // choice.
  5347. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5348. } else {
  5349. // Affected boundary has x2new set, using it as new x.
  5350. xNew = affectedBoundary.x2New;
  5351. }
  5352. if (xNew > maxXNew) {
  5353. maxXNew = xNew;
  5354. }
  5355. }
  5356. // Set new x1 for current boundary.
  5357. boundary.x1New = maxXNew;
  5358. // Adjusts new x2 for the affected boundaries.
  5359. for (q = i; q <= j; q++) {
  5360. horizonPart = horizon[q];
  5361. affectedBoundary = horizonPart.boundary;
  5362. if (affectedBoundary.x2New === undefined) {
  5363. // Was not set yet, choosing new x if possible.
  5364. if (affectedBoundary.x2 > boundary.x1) {
  5365. // Current and affected boundaries intersect. If affected boundary
  5366. // is placed on top of the current, shrinking the affected.
  5367. if (affectedBoundary.index > boundary.index) {
  5368. affectedBoundary.x2New = affectedBoundary.x2;
  5369. }
  5370. } else {
  5371. affectedBoundary.x2New = maxXNew;
  5372. }
  5373. } else if (affectedBoundary.x2New > maxXNew) {
  5374. // Affected boundary is touching new x, pushing it back.
  5375. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5376. }
  5377. }
  5378. // Fixing the horizon.
  5379. var changedHorizon = [], lastBoundary = null;
  5380. for (q = i; q <= j; q++) {
  5381. horizonPart = horizon[q];
  5382. affectedBoundary = horizonPart.boundary;
  5383. // Checking which boundary will be visible.
  5384. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  5385. if (lastBoundary === useBoundary) {
  5386. // Merging with previous.
  5387. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5388. } else {
  5389. changedHorizon.push({
  5390. start: horizonPart.start,
  5391. end: horizonPart.end,
  5392. boundary: useBoundary
  5393. });
  5394. lastBoundary = useBoundary;
  5395. }
  5396. }
  5397. if (horizon[i].start < boundary.y1) {
  5398. changedHorizon[0].start = boundary.y1;
  5399. changedHorizon.unshift({
  5400. start: horizon[i].start,
  5401. end: boundary.y1,
  5402. boundary: horizon[i].boundary
  5403. });
  5404. }
  5405. if (boundary.y2 < horizon[j].end) {
  5406. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5407. changedHorizon.push({
  5408. start: boundary.y2,
  5409. end: horizon[j].end,
  5410. boundary: horizon[j].boundary
  5411. });
  5412. }
  5413. // Set x2 new of boundary that is no longer visible (see overlapping case
  5414. // above).
  5415. // TODO more efficient, e.g. via reference counting.
  5416. for (q = i; q <= j; q++) {
  5417. horizonPart = horizon[q];
  5418. affectedBoundary = horizonPart.boundary;
  5419. if (affectedBoundary.x2New !== undefined) {
  5420. continue;
  5421. }
  5422. var used = false;
  5423. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  5424. used = horizon[k].boundary === affectedBoundary;
  5425. }
  5426. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  5427. used = horizon[k].boundary === affectedBoundary;
  5428. }
  5429. for (k = 0; !used && k < changedHorizon.length; k++) {
  5430. used = changedHorizon[k].boundary === affectedBoundary;
  5431. }
  5432. if (!used) {
  5433. affectedBoundary.x2New = maxXNew;
  5434. }
  5435. }
  5436. Array.prototype.splice.apply(horizon, [
  5437. i,
  5438. j - i + 1
  5439. ].concat(changedHorizon));
  5440. });
  5441. // Set new x2 for all unset boundaries.
  5442. horizon.forEach(function (horizonPart) {
  5443. var affectedBoundary = horizonPart.boundary;
  5444. if (affectedBoundary.x2New === undefined) {
  5445. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5446. }
  5447. });
  5448. }
  5449. /**
  5450. * Text layer rendering task.
  5451. *
  5452. * @param {TextContent} textContent
  5453. * @param {HTMLElement} container
  5454. * @param {PageViewport} viewport
  5455. * @param {Array} textDivs
  5456. * @param {boolean} enhanceTextSelection
  5457. * @private
  5458. */
  5459. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  5460. this._textContent = textContent;
  5461. this._container = container;
  5462. this._viewport = viewport;
  5463. this._textDivs = textDivs || [];
  5464. this._textDivProperties = new WeakMap();
  5465. this._renderingDone = false;
  5466. this._canceled = false;
  5467. this._capability = createPromiseCapability();
  5468. this._renderTimer = null;
  5469. this._bounds = [];
  5470. this._enhanceTextSelection = !!enhanceTextSelection;
  5471. }
  5472. TextLayerRenderTask.prototype = {
  5473. get promise() {
  5474. return this._capability.promise;
  5475. },
  5476. cancel: function TextLayer_cancel() {
  5477. this._canceled = true;
  5478. if (this._renderTimer !== null) {
  5479. clearTimeout(this._renderTimer);
  5480. this._renderTimer = null;
  5481. }
  5482. this._capability.reject('canceled');
  5483. },
  5484. _render: function TextLayer_render(timeout) {
  5485. var textItems = this._textContent.items;
  5486. var textStyles = this._textContent.styles;
  5487. for (var i = 0, len = textItems.length; i < len; i++) {
  5488. appendText(this, textItems[i], textStyles);
  5489. }
  5490. if (!timeout) {
  5491. // Render right away
  5492. render(this);
  5493. } else {
  5494. // Schedule
  5495. var self = this;
  5496. this._renderTimer = setTimeout(function () {
  5497. render(self);
  5498. self._renderTimer = null;
  5499. }, timeout);
  5500. }
  5501. },
  5502. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5503. if (!this._enhanceTextSelection || !this._renderingDone) {
  5504. return;
  5505. }
  5506. if (this._bounds !== null) {
  5507. expand(this);
  5508. this._bounds = null;
  5509. }
  5510. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5511. var div = this._textDivs[i];
  5512. var divProperties = this._textDivProperties.get(div);
  5513. if (divProperties.isWhitespace) {
  5514. continue;
  5515. }
  5516. if (expandDivs) {
  5517. var transform = '', padding = '';
  5518. if (divProperties.scale !== 1) {
  5519. transform = 'scaleX(' + divProperties.scale + ')';
  5520. }
  5521. if (divProperties.angle !== 0) {
  5522. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5523. }
  5524. if (divProperties.paddingLeft !== 0) {
  5525. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  5526. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  5527. }
  5528. if (divProperties.paddingTop !== 0) {
  5529. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5530. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  5531. }
  5532. if (divProperties.paddingRight !== 0) {
  5533. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  5534. }
  5535. if (divProperties.paddingBottom !== 0) {
  5536. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  5537. }
  5538. if (padding !== '') {
  5539. div.setAttribute('style', divProperties.style + padding);
  5540. }
  5541. if (transform !== '') {
  5542. CustomStyle.setProp('transform', div, transform);
  5543. }
  5544. } else {
  5545. div.style.padding = 0;
  5546. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  5547. }
  5548. }
  5549. }
  5550. };
  5551. /**
  5552. * Starts rendering of the text layer.
  5553. *
  5554. * @param {TextLayerRenderParameters} renderParameters
  5555. * @returns {TextLayerRenderTask}
  5556. */
  5557. function renderTextLayer(renderParameters) {
  5558. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  5559. task._render(renderParameters.timeout);
  5560. return task;
  5561. }
  5562. return renderTextLayer;
  5563. }();
  5564. exports.renderTextLayer = renderTextLayer;
  5565. }));
  5566. (function (root, factory) {
  5567. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  5568. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5569. var shadow = sharedUtil.shadow;
  5570. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5571. var WebGLUtils = function WebGLUtilsClosure() {
  5572. function loadShader(gl, code, shaderType) {
  5573. var shader = gl.createShader(shaderType);
  5574. gl.shaderSource(shader, code);
  5575. gl.compileShader(shader);
  5576. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5577. if (!compiled) {
  5578. var errorMsg = gl.getShaderInfoLog(shader);
  5579. throw new Error('Error during shader compilation: ' + errorMsg);
  5580. }
  5581. return shader;
  5582. }
  5583. function createVertexShader(gl, code) {
  5584. return loadShader(gl, code, gl.VERTEX_SHADER);
  5585. }
  5586. function createFragmentShader(gl, code) {
  5587. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5588. }
  5589. function createProgram(gl, shaders) {
  5590. var program = gl.createProgram();
  5591. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5592. gl.attachShader(program, shaders[i]);
  5593. }
  5594. gl.linkProgram(program);
  5595. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5596. if (!linked) {
  5597. var errorMsg = gl.getProgramInfoLog(program);
  5598. throw new Error('Error during program linking: ' + errorMsg);
  5599. }
  5600. return program;
  5601. }
  5602. function createTexture(gl, image, textureId) {
  5603. gl.activeTexture(textureId);
  5604. var texture = gl.createTexture();
  5605. gl.bindTexture(gl.TEXTURE_2D, texture);
  5606. // Set the parameters so we can render any size image.
  5607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5611. // Upload the image into the texture.
  5612. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5613. return texture;
  5614. }
  5615. var currentGL, currentCanvas;
  5616. function generateGL() {
  5617. if (currentGL) {
  5618. return;
  5619. }
  5620. currentCanvas = document.createElement('canvas');
  5621. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  5622. }
  5623. var smaskVertexShaderCode = '\
  5624. attribute vec2 a_position; \
  5625. attribute vec2 a_texCoord; \
  5626. \
  5627. uniform vec2 u_resolution; \
  5628. \
  5629. varying vec2 v_texCoord; \
  5630. \
  5631. void main() { \
  5632. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5633. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5634. \
  5635. v_texCoord = a_texCoord; \
  5636. } ';
  5637. var smaskFragmentShaderCode = '\
  5638. precision mediump float; \
  5639. \
  5640. uniform vec4 u_backdrop; \
  5641. uniform int u_subtype; \
  5642. uniform sampler2D u_image; \
  5643. uniform sampler2D u_mask; \
  5644. \
  5645. varying vec2 v_texCoord; \
  5646. \
  5647. void main() { \
  5648. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5649. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5650. if (u_backdrop.a > 0.0) { \
  5651. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5652. u_backdrop.rgb * (1.0 - maskColor.a); \
  5653. } \
  5654. float lum; \
  5655. if (u_subtype == 0) { \
  5656. lum = maskColor.a; \
  5657. } else { \
  5658. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5659. maskColor.b * 0.11; \
  5660. } \
  5661. imageColor.a *= lum; \
  5662. imageColor.rgb *= imageColor.a; \
  5663. gl_FragColor = imageColor; \
  5664. } ';
  5665. var smaskCache = null;
  5666. function initSmaskGL() {
  5667. var canvas, gl;
  5668. generateGL();
  5669. canvas = currentCanvas;
  5670. currentCanvas = null;
  5671. gl = currentGL;
  5672. currentGL = null;
  5673. // setup a GLSL program
  5674. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5675. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5676. var program = createProgram(gl, [
  5677. vertexShader,
  5678. fragmentShader
  5679. ]);
  5680. gl.useProgram(program);
  5681. var cache = {};
  5682. cache.gl = gl;
  5683. cache.canvas = canvas;
  5684. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5685. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5686. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5687. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5688. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5689. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5690. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5691. // provide texture coordinates for the rectangle.
  5692. var texCoordBuffer = gl.createBuffer();
  5693. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5694. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5695. 0.0,
  5696. 0.0,
  5697. 1.0,
  5698. 0.0,
  5699. 0.0,
  5700. 1.0,
  5701. 0.0,
  5702. 1.0,
  5703. 1.0,
  5704. 0.0,
  5705. 1.0,
  5706. 1.0
  5707. ]), gl.STATIC_DRAW);
  5708. gl.enableVertexAttribArray(texCoordLocation);
  5709. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5710. gl.uniform1i(texLayerLocation, 0);
  5711. gl.uniform1i(texMaskLocation, 1);
  5712. smaskCache = cache;
  5713. }
  5714. function composeSMask(layer, mask, properties) {
  5715. var width = layer.width, height = layer.height;
  5716. if (!smaskCache) {
  5717. initSmaskGL();
  5718. }
  5719. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5720. canvas.width = width;
  5721. canvas.height = height;
  5722. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5723. gl.uniform2f(cache.resolutionLocation, width, height);
  5724. if (properties.backdrop) {
  5725. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5726. } else {
  5727. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5728. }
  5729. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5730. // Create a textures
  5731. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5732. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5733. // Create a buffer and put a single clipspace rectangle in
  5734. // it (2 triangles)
  5735. var buffer = gl.createBuffer();
  5736. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5737. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5738. 0,
  5739. 0,
  5740. width,
  5741. 0,
  5742. 0,
  5743. height,
  5744. 0,
  5745. height,
  5746. width,
  5747. 0,
  5748. width,
  5749. height
  5750. ]), gl.STATIC_DRAW);
  5751. gl.enableVertexAttribArray(cache.positionLocation);
  5752. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5753. // draw
  5754. gl.clearColor(0, 0, 0, 0);
  5755. gl.enable(gl.BLEND);
  5756. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5757. gl.clear(gl.COLOR_BUFFER_BIT);
  5758. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5759. gl.flush();
  5760. gl.deleteTexture(texture);
  5761. gl.deleteTexture(maskTexture);
  5762. gl.deleteBuffer(buffer);
  5763. return canvas;
  5764. }
  5765. var figuresVertexShaderCode = '\
  5766. attribute vec2 a_position; \
  5767. attribute vec3 a_color; \
  5768. \
  5769. uniform vec2 u_resolution; \
  5770. uniform vec2 u_scale; \
  5771. uniform vec2 u_offset; \
  5772. \
  5773. varying vec4 v_color; \
  5774. \
  5775. void main() { \
  5776. vec2 position = (a_position + u_offset) * u_scale; \
  5777. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5778. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5779. \
  5780. v_color = vec4(a_color / 255.0, 1.0); \
  5781. } ';
  5782. var figuresFragmentShaderCode = '\
  5783. precision mediump float; \
  5784. \
  5785. varying vec4 v_color; \
  5786. \
  5787. void main() { \
  5788. gl_FragColor = v_color; \
  5789. } ';
  5790. var figuresCache = null;
  5791. function initFiguresGL() {
  5792. var canvas, gl;
  5793. generateGL();
  5794. canvas = currentCanvas;
  5795. currentCanvas = null;
  5796. gl = currentGL;
  5797. currentGL = null;
  5798. // setup a GLSL program
  5799. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5800. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5801. var program = createProgram(gl, [
  5802. vertexShader,
  5803. fragmentShader
  5804. ]);
  5805. gl.useProgram(program);
  5806. var cache = {};
  5807. cache.gl = gl;
  5808. cache.canvas = canvas;
  5809. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5810. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5811. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5812. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5813. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5814. figuresCache = cache;
  5815. }
  5816. function drawFigures(width, height, backgroundColor, figures, context) {
  5817. if (!figuresCache) {
  5818. initFiguresGL();
  5819. }
  5820. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5821. canvas.width = width;
  5822. canvas.height = height;
  5823. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5824. gl.uniform2f(cache.resolutionLocation, width, height);
  5825. // count triangle points
  5826. var count = 0;
  5827. var i, ii, rows;
  5828. for (i = 0, ii = figures.length; i < ii; i++) {
  5829. switch (figures[i].type) {
  5830. case 'lattice':
  5831. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5832. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5833. break;
  5834. case 'triangles':
  5835. count += figures[i].coords.length;
  5836. break;
  5837. }
  5838. }
  5839. // transfer data
  5840. var coords = new Float32Array(count * 2);
  5841. var colors = new Uint8Array(count * 3);
  5842. var coordsMap = context.coords, colorsMap = context.colors;
  5843. var pIndex = 0, cIndex = 0;
  5844. for (i = 0, ii = figures.length; i < ii; i++) {
  5845. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5846. switch (figure.type) {
  5847. case 'lattice':
  5848. var cols = figure.verticesPerRow;
  5849. rows = ps.length / cols | 0;
  5850. for (var row = 1; row < rows; row++) {
  5851. var offset = row * cols + 1;
  5852. for (var col = 1; col < cols; col++, offset++) {
  5853. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5854. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5855. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5856. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5857. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5858. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5859. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5860. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5861. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5862. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5863. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5864. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5865. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5866. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5867. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5868. coords[pIndex + 6] = coords[pIndex + 2];
  5869. coords[pIndex + 7] = coords[pIndex + 3];
  5870. coords[pIndex + 8] = coords[pIndex + 4];
  5871. coords[pIndex + 9] = coords[pIndex + 5];
  5872. coords[pIndex + 10] = coordsMap[ps[offset]];
  5873. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5874. colors[cIndex + 9] = colors[cIndex + 3];
  5875. colors[cIndex + 10] = colors[cIndex + 4];
  5876. colors[cIndex + 11] = colors[cIndex + 5];
  5877. colors[cIndex + 12] = colors[cIndex + 6];
  5878. colors[cIndex + 13] = colors[cIndex + 7];
  5879. colors[cIndex + 14] = colors[cIndex + 8];
  5880. colors[cIndex + 15] = colorsMap[cs[offset]];
  5881. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5882. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5883. pIndex += 12;
  5884. cIndex += 18;
  5885. }
  5886. }
  5887. break;
  5888. case 'triangles':
  5889. for (var j = 0, jj = ps.length; j < jj; j++) {
  5890. coords[pIndex] = coordsMap[ps[j]];
  5891. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5892. colors[cIndex] = colorsMap[cs[j]];
  5893. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5894. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5895. pIndex += 2;
  5896. cIndex += 3;
  5897. }
  5898. break;
  5899. }
  5900. }
  5901. // draw
  5902. if (backgroundColor) {
  5903. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5904. } else {
  5905. gl.clearColor(0, 0, 0, 0);
  5906. }
  5907. gl.clear(gl.COLOR_BUFFER_BIT);
  5908. var coordsBuffer = gl.createBuffer();
  5909. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5910. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5911. gl.enableVertexAttribArray(cache.positionLocation);
  5912. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5913. var colorsBuffer = gl.createBuffer();
  5914. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5915. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5916. gl.enableVertexAttribArray(cache.colorLocation);
  5917. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5918. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5919. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5920. gl.drawArrays(gl.TRIANGLES, 0, count);
  5921. gl.flush();
  5922. gl.deleteBuffer(coordsBuffer);
  5923. gl.deleteBuffer(colorsBuffer);
  5924. return canvas;
  5925. }
  5926. function cleanup() {
  5927. if (smaskCache && smaskCache.canvas) {
  5928. smaskCache.canvas.width = 0;
  5929. smaskCache.canvas.height = 0;
  5930. }
  5931. if (figuresCache && figuresCache.canvas) {
  5932. figuresCache.canvas.width = 0;
  5933. figuresCache.canvas.height = 0;
  5934. }
  5935. smaskCache = null;
  5936. figuresCache = null;
  5937. }
  5938. return {
  5939. get isEnabled() {
  5940. if (getDefaultSetting('disableWebGL')) {
  5941. return false;
  5942. }
  5943. var enabled = false;
  5944. try {
  5945. generateGL();
  5946. enabled = !!currentGL;
  5947. } catch (e) {
  5948. }
  5949. return shadow(this, 'isEnabled', enabled);
  5950. },
  5951. composeSMask: composeSMask,
  5952. drawFigures: drawFigures,
  5953. clear: cleanup
  5954. };
  5955. }();
  5956. exports.WebGLUtils = WebGLUtils;
  5957. }));
  5958. (function (root, factory) {
  5959. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5960. }(this, function (exports, sharedUtil, displayWebGL) {
  5961. var Util = sharedUtil.Util;
  5962. var info = sharedUtil.info;
  5963. var isArray = sharedUtil.isArray;
  5964. var error = sharedUtil.error;
  5965. var WebGLUtils = displayWebGL.WebGLUtils;
  5966. var ShadingIRs = {};
  5967. ShadingIRs.RadialAxial = {
  5968. fromIR: function RadialAxial_fromIR(raw) {
  5969. var type = raw[1];
  5970. var colorStops = raw[2];
  5971. var p0 = raw[3];
  5972. var p1 = raw[4];
  5973. var r0 = raw[5];
  5974. var r1 = raw[6];
  5975. return {
  5976. type: 'Pattern',
  5977. getPattern: function RadialAxial_getPattern(ctx) {
  5978. var grad;
  5979. if (type === 'axial') {
  5980. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5981. } else if (type === 'radial') {
  5982. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5983. }
  5984. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5985. var c = colorStops[i];
  5986. grad.addColorStop(c[0], c[1]);
  5987. }
  5988. return grad;
  5989. }
  5990. };
  5991. }
  5992. };
  5993. var createMeshCanvas = function createMeshCanvasClosure() {
  5994. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5995. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5996. var coords = context.coords, colors = context.colors;
  5997. var bytes = data.data, rowSize = data.width * 4;
  5998. var tmp;
  5999. if (coords[p1 + 1] > coords[p2 + 1]) {
  6000. tmp = p1;
  6001. p1 = p2;
  6002. p2 = tmp;
  6003. tmp = c1;
  6004. c1 = c2;
  6005. c2 = tmp;
  6006. }
  6007. if (coords[p2 + 1] > coords[p3 + 1]) {
  6008. tmp = p2;
  6009. p2 = p3;
  6010. p3 = tmp;
  6011. tmp = c2;
  6012. c2 = c3;
  6013. c3 = tmp;
  6014. }
  6015. if (coords[p1 + 1] > coords[p2 + 1]) {
  6016. tmp = p1;
  6017. p1 = p2;
  6018. p2 = tmp;
  6019. tmp = c1;
  6020. c1 = c2;
  6021. c2 = tmp;
  6022. }
  6023. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6024. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6025. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6026. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6027. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6028. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6029. if (y1 >= y3) {
  6030. return;
  6031. }
  6032. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  6033. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  6034. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  6035. var minY = Math.round(y1), maxY = Math.round(y3);
  6036. var xa, car, cag, cab;
  6037. var xb, cbr, cbg, cbb;
  6038. var k;
  6039. for (var y = minY; y <= maxY; y++) {
  6040. if (y < y2) {
  6041. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  6042. xa = x1 - (x1 - x2) * k;
  6043. car = c1r - (c1r - c2r) * k;
  6044. cag = c1g - (c1g - c2g) * k;
  6045. cab = c1b - (c1b - c2b) * k;
  6046. } else {
  6047. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  6048. xa = x2 - (x2 - x3) * k;
  6049. car = c2r - (c2r - c3r) * k;
  6050. cag = c2g - (c2g - c3g) * k;
  6051. cab = c2b - (c2b - c3b) * k;
  6052. }
  6053. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  6054. xb = x1 - (x1 - x3) * k;
  6055. cbr = c1r - (c1r - c3r) * k;
  6056. cbg = c1g - (c1g - c3g) * k;
  6057. cbb = c1b - (c1b - c3b) * k;
  6058. var x1_ = Math.round(Math.min(xa, xb));
  6059. var x2_ = Math.round(Math.max(xa, xb));
  6060. var j = rowSize * y + x1_ * 4;
  6061. for (var x = x1_; x <= x2_; x++) {
  6062. k = (xa - x) / (xa - xb);
  6063. k = k < 0 ? 0 : k > 1 ? 1 : k;
  6064. bytes[j++] = car - (car - cbr) * k | 0;
  6065. bytes[j++] = cag - (cag - cbg) * k | 0;
  6066. bytes[j++] = cab - (cab - cbb) * k | 0;
  6067. bytes[j++] = 255;
  6068. }
  6069. }
  6070. }
  6071. function drawFigure(data, figure, context) {
  6072. var ps = figure.coords;
  6073. var cs = figure.colors;
  6074. var i, ii;
  6075. switch (figure.type) {
  6076. case 'lattice':
  6077. var verticesPerRow = figure.verticesPerRow;
  6078. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  6079. var cols = verticesPerRow - 1;
  6080. for (i = 0; i < rows; i++) {
  6081. var q = i * verticesPerRow;
  6082. for (var j = 0; j < cols; j++, q++) {
  6083. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6084. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6085. }
  6086. }
  6087. break;
  6088. case 'triangles':
  6089. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6090. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6091. }
  6092. break;
  6093. default:
  6094. error('illigal figure');
  6095. break;
  6096. }
  6097. }
  6098. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  6099. // we will increase scale on some weird factor to let antialiasing take
  6100. // care of "rough" edges
  6101. var EXPECTED_SCALE = 1.1;
  6102. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6103. var MAX_PATTERN_SIZE = 3000;
  6104. // 10in @ 300dpi shall be enough
  6105. // We need to keep transparent border around our pattern for fill():
  6106. // createPattern with 'no-repeat' will bleed edges across entire area.
  6107. var BORDER_SIZE = 2;
  6108. var offsetX = Math.floor(bounds[0]);
  6109. var offsetY = Math.floor(bounds[1]);
  6110. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  6111. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  6112. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6113. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6114. var scaleX = boundsWidth / width;
  6115. var scaleY = boundsHeight / height;
  6116. var context = {
  6117. coords: coords,
  6118. colors: colors,
  6119. offsetX: -offsetX,
  6120. offsetY: -offsetY,
  6121. scaleX: 1 / scaleX,
  6122. scaleY: 1 / scaleY
  6123. };
  6124. var paddedWidth = width + BORDER_SIZE * 2;
  6125. var paddedHeight = height + BORDER_SIZE * 2;
  6126. var canvas, tmpCanvas, i, ii;
  6127. if (WebGLUtils.isEnabled) {
  6128. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  6129. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  6130. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6131. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  6132. canvas = tmpCanvas.canvas;
  6133. } else {
  6134. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6135. var tmpCtx = tmpCanvas.context;
  6136. var data = tmpCtx.createImageData(width, height);
  6137. if (backgroundColor) {
  6138. var bytes = data.data;
  6139. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  6140. bytes[i] = backgroundColor[0];
  6141. bytes[i + 1] = backgroundColor[1];
  6142. bytes[i + 2] = backgroundColor[2];
  6143. bytes[i + 3] = 255;
  6144. }
  6145. }
  6146. for (i = 0; i < figures.length; i++) {
  6147. drawFigure(data, figures[i], context);
  6148. }
  6149. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6150. canvas = tmpCanvas.canvas;
  6151. }
  6152. return {
  6153. canvas: canvas,
  6154. offsetX: offsetX - BORDER_SIZE * scaleX,
  6155. offsetY: offsetY - BORDER_SIZE * scaleY,
  6156. scaleX: scaleX,
  6157. scaleY: scaleY
  6158. };
  6159. }
  6160. return createMeshCanvas;
  6161. }();
  6162. ShadingIRs.Mesh = {
  6163. fromIR: function Mesh_fromIR(raw) {
  6164. //var type = raw[1];
  6165. var coords = raw[2];
  6166. var colors = raw[3];
  6167. var figures = raw[4];
  6168. var bounds = raw[5];
  6169. var matrix = raw[6];
  6170. //var bbox = raw[7];
  6171. var background = raw[8];
  6172. return {
  6173. type: 'Pattern',
  6174. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  6175. var scale;
  6176. if (shadingFill) {
  6177. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6178. } else {
  6179. // Obtain scale from matrix and current transformation matrix.
  6180. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6181. if (matrix) {
  6182. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  6183. scale = [
  6184. scale[0] * matrixScale[0],
  6185. scale[1] * matrixScale[1]
  6186. ];
  6187. }
  6188. }
  6189. // Rasterizing on the main thread since sending/queue large canvases
  6190. // might cause OOM.
  6191. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  6192. if (!shadingFill) {
  6193. ctx.setTransform.apply(ctx, owner.baseTransform);
  6194. if (matrix) {
  6195. ctx.transform.apply(ctx, matrix);
  6196. }
  6197. }
  6198. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6199. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6200. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  6201. }
  6202. };
  6203. }
  6204. };
  6205. ShadingIRs.Dummy = {
  6206. fromIR: function Dummy_fromIR() {
  6207. return {
  6208. type: 'Pattern',
  6209. getPattern: function Dummy_fromIR_getPattern() {
  6210. return 'hotpink';
  6211. }
  6212. };
  6213. }
  6214. };
  6215. function getShadingPatternFromIR(raw) {
  6216. var shadingIR = ShadingIRs[raw[0]];
  6217. if (!shadingIR) {
  6218. error('Unknown IR type: ' + raw[0]);
  6219. }
  6220. return shadingIR.fromIR(raw);
  6221. }
  6222. var TilingPattern = function TilingPatternClosure() {
  6223. var PaintType = {
  6224. COLORED: 1,
  6225. UNCOLORED: 2
  6226. };
  6227. var MAX_PATTERN_SIZE = 3000;
  6228. // 10in @ 300dpi shall be enough
  6229. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6230. this.operatorList = IR[2];
  6231. this.matrix = IR[3] || [
  6232. 1,
  6233. 0,
  6234. 0,
  6235. 1,
  6236. 0,
  6237. 0
  6238. ];
  6239. this.bbox = IR[4];
  6240. this.xstep = IR[5];
  6241. this.ystep = IR[6];
  6242. this.paintType = IR[7];
  6243. this.tilingType = IR[8];
  6244. this.color = color;
  6245. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6246. this.baseTransform = baseTransform;
  6247. this.type = 'Pattern';
  6248. this.ctx = ctx;
  6249. }
  6250. TilingPattern.prototype = {
  6251. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6252. var operatorList = this.operatorList;
  6253. var bbox = this.bbox;
  6254. var xstep = this.xstep;
  6255. var ystep = this.ystep;
  6256. var paintType = this.paintType;
  6257. var tilingType = this.tilingType;
  6258. var color = this.color;
  6259. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6260. info('TilingType: ' + tilingType);
  6261. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6262. var topLeft = [
  6263. x0,
  6264. y0
  6265. ];
  6266. // we want the canvas to be as large as the step size
  6267. var botRight = [
  6268. x0 + xstep,
  6269. y0 + ystep
  6270. ];
  6271. var width = botRight[0] - topLeft[0];
  6272. var height = botRight[1] - topLeft[1];
  6273. // Obtain scale from matrix and current transformation matrix.
  6274. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6275. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6276. var combinedScale = [
  6277. matrixScale[0] * curMatrixScale[0],
  6278. matrixScale[1] * curMatrixScale[1]
  6279. ];
  6280. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6281. // Use width and height values that are as close as possible to the end
  6282. // result when the pattern is used. Too low value makes the pattern look
  6283. // blurry. Too large value makes it look too crispy.
  6284. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  6285. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  6286. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  6287. var tmpCtx = tmpCanvas.context;
  6288. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6289. graphics.groupLevel = owner.groupLevel;
  6290. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6291. this.setScale(width, height, xstep, ystep);
  6292. this.transformToScale(graphics);
  6293. // transform coordinates to pattern space
  6294. var tmpTranslate = [
  6295. 1,
  6296. 0,
  6297. 0,
  6298. 1,
  6299. -topLeft[0],
  6300. -topLeft[1]
  6301. ];
  6302. graphics.transform.apply(graphics, tmpTranslate);
  6303. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6304. graphics.executeOperatorList(operatorList);
  6305. return tmpCanvas.canvas;
  6306. },
  6307. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6308. this.scale = [
  6309. width / xstep,
  6310. height / ystep
  6311. ];
  6312. },
  6313. transformToScale: function TilingPattern_transformToScale(graphics) {
  6314. var scale = this.scale;
  6315. var tmpScale = [
  6316. scale[0],
  6317. 0,
  6318. 0,
  6319. scale[1],
  6320. 0,
  6321. 0
  6322. ];
  6323. graphics.transform.apply(graphics, tmpScale);
  6324. },
  6325. scaleToContext: function TilingPattern_scaleToContext() {
  6326. var scale = this.scale;
  6327. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6328. },
  6329. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6330. if (bbox && isArray(bbox) && bbox.length === 4) {
  6331. var bboxWidth = x1 - x0;
  6332. var bboxHeight = y1 - y0;
  6333. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6334. graphics.clip();
  6335. graphics.endPath();
  6336. }
  6337. },
  6338. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  6339. switch (paintType) {
  6340. case PaintType.COLORED:
  6341. var ctx = this.ctx;
  6342. context.fillStyle = ctx.fillStyle;
  6343. context.strokeStyle = ctx.strokeStyle;
  6344. break;
  6345. case PaintType.UNCOLORED:
  6346. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6347. context.fillStyle = cssColor;
  6348. context.strokeStyle = cssColor;
  6349. break;
  6350. default:
  6351. error('Unsupported paint type: ' + paintType);
  6352. }
  6353. },
  6354. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6355. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6356. ctx = this.ctx;
  6357. ctx.setTransform.apply(ctx, this.baseTransform);
  6358. ctx.transform.apply(ctx, this.matrix);
  6359. this.scaleToContext();
  6360. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6361. }
  6362. };
  6363. return TilingPattern;
  6364. }();
  6365. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6366. exports.TilingPattern = TilingPattern;
  6367. }));
  6368. (function (root, factory) {
  6369. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  6370. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  6371. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6372. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6373. var ImageKind = sharedUtil.ImageKind;
  6374. var OPS = sharedUtil.OPS;
  6375. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6376. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6377. var Util = sharedUtil.Util;
  6378. var assert = sharedUtil.assert;
  6379. var info = sharedUtil.info;
  6380. var isNum = sharedUtil.isNum;
  6381. var isArray = sharedUtil.isArray;
  6382. var isLittleEndian = sharedUtil.isLittleEndian;
  6383. var error = sharedUtil.error;
  6384. var shadow = sharedUtil.shadow;
  6385. var warn = sharedUtil.warn;
  6386. var TilingPattern = displayPatternHelper.TilingPattern;
  6387. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6388. var WebGLUtils = displayWebGL.WebGLUtils;
  6389. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6390. // <canvas> contexts store most of the state we need natively.
  6391. // However, PDF needs a bit more state, which we store here.
  6392. // Minimal font size that would be used during canvas fillText operations.
  6393. var MIN_FONT_SIZE = 16;
  6394. // Maximum font size that would be used during canvas fillText operations.
  6395. var MAX_FONT_SIZE = 100;
  6396. var MAX_GROUP_SIZE = 4096;
  6397. // Heuristic value used when enforcing minimum line widths.
  6398. var MIN_WIDTH_FACTOR = 0.65;
  6399. var COMPILE_TYPE3_GLYPHS = true;
  6400. var MAX_SIZE_TO_COMPILE = 1000;
  6401. var FULL_CHUNK_HEIGHT = 16;
  6402. var HasCanvasTypedArraysCached = {
  6403. get value() {
  6404. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6405. }
  6406. };
  6407. var IsLittleEndianCached = {
  6408. get value() {
  6409. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6410. }
  6411. };
  6412. function createScratchCanvas(width, height) {
  6413. var canvas = document.createElement('canvas');
  6414. canvas.width = width;
  6415. canvas.height = height;
  6416. return canvas;
  6417. }
  6418. function addContextCurrentTransform(ctx) {
  6419. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6420. if (!ctx.mozCurrentTransform) {
  6421. ctx._originalSave = ctx.save;
  6422. ctx._originalRestore = ctx.restore;
  6423. ctx._originalRotate = ctx.rotate;
  6424. ctx._originalScale = ctx.scale;
  6425. ctx._originalTranslate = ctx.translate;
  6426. ctx._originalTransform = ctx.transform;
  6427. ctx._originalSetTransform = ctx.setTransform;
  6428. ctx._transformMatrix = ctx._transformMatrix || [
  6429. 1,
  6430. 0,
  6431. 0,
  6432. 1,
  6433. 0,
  6434. 0
  6435. ];
  6436. ctx._transformStack = [];
  6437. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6438. get: function getCurrentTransform() {
  6439. return this._transformMatrix;
  6440. }
  6441. });
  6442. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6443. get: function getCurrentTransformInverse() {
  6444. // Calculation done using WolframAlpha:
  6445. // http://www.wolframalpha.com/input/?
  6446. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6447. var m = this._transformMatrix;
  6448. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6449. var ad_bc = a * d - b * c;
  6450. var bc_ad = b * c - a * d;
  6451. return [
  6452. d / ad_bc,
  6453. b / bc_ad,
  6454. c / bc_ad,
  6455. a / ad_bc,
  6456. (d * e - c * f) / bc_ad,
  6457. (b * e - a * f) / ad_bc
  6458. ];
  6459. }
  6460. });
  6461. ctx.save = function ctxSave() {
  6462. var old = this._transformMatrix;
  6463. this._transformStack.push(old);
  6464. this._transformMatrix = old.slice(0, 6);
  6465. this._originalSave();
  6466. };
  6467. ctx.restore = function ctxRestore() {
  6468. var prev = this._transformStack.pop();
  6469. if (prev) {
  6470. this._transformMatrix = prev;
  6471. this._originalRestore();
  6472. }
  6473. };
  6474. ctx.translate = function ctxTranslate(x, y) {
  6475. var m = this._transformMatrix;
  6476. m[4] = m[0] * x + m[2] * y + m[4];
  6477. m[5] = m[1] * x + m[3] * y + m[5];
  6478. this._originalTranslate(x, y);
  6479. };
  6480. ctx.scale = function ctxScale(x, y) {
  6481. var m = this._transformMatrix;
  6482. m[0] = m[0] * x;
  6483. m[1] = m[1] * x;
  6484. m[2] = m[2] * y;
  6485. m[3] = m[3] * y;
  6486. this._originalScale(x, y);
  6487. };
  6488. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6489. var m = this._transformMatrix;
  6490. this._transformMatrix = [
  6491. m[0] * a + m[2] * b,
  6492. m[1] * a + m[3] * b,
  6493. m[0] * c + m[2] * d,
  6494. m[1] * c + m[3] * d,
  6495. m[0] * e + m[2] * f + m[4],
  6496. m[1] * e + m[3] * f + m[5]
  6497. ];
  6498. ctx._originalTransform(a, b, c, d, e, f);
  6499. };
  6500. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6501. this._transformMatrix = [
  6502. a,
  6503. b,
  6504. c,
  6505. d,
  6506. e,
  6507. f
  6508. ];
  6509. ctx._originalSetTransform(a, b, c, d, e, f);
  6510. };
  6511. ctx.rotate = function ctxRotate(angle) {
  6512. var cosValue = Math.cos(angle);
  6513. var sinValue = Math.sin(angle);
  6514. var m = this._transformMatrix;
  6515. this._transformMatrix = [
  6516. m[0] * cosValue + m[2] * sinValue,
  6517. m[1] * cosValue + m[3] * sinValue,
  6518. m[0] * -sinValue + m[2] * cosValue,
  6519. m[1] * -sinValue + m[3] * cosValue,
  6520. m[4],
  6521. m[5]
  6522. ];
  6523. this._originalRotate(angle);
  6524. };
  6525. }
  6526. }
  6527. var CachedCanvases = function CachedCanvasesClosure() {
  6528. function CachedCanvases() {
  6529. this.cache = Object.create(null);
  6530. }
  6531. CachedCanvases.prototype = {
  6532. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  6533. var canvasEntry;
  6534. if (this.cache[id] !== undefined) {
  6535. canvasEntry = this.cache[id];
  6536. canvasEntry.canvas.width = width;
  6537. canvasEntry.canvas.height = height;
  6538. // reset canvas transform for emulated mozCurrentTransform, if needed
  6539. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6540. } else {
  6541. var canvas = createScratchCanvas(width, height);
  6542. var ctx = canvas.getContext('2d');
  6543. if (trackTransform) {
  6544. addContextCurrentTransform(ctx);
  6545. }
  6546. this.cache[id] = canvasEntry = {
  6547. canvas: canvas,
  6548. context: ctx
  6549. };
  6550. }
  6551. return canvasEntry;
  6552. },
  6553. clear: function () {
  6554. for (var id in this.cache) {
  6555. var canvasEntry = this.cache[id];
  6556. // Zeroing the width and height causes Firefox to release graphics
  6557. // resources immediately, which can greatly reduce memory consumption.
  6558. canvasEntry.canvas.width = 0;
  6559. canvasEntry.canvas.height = 0;
  6560. delete this.cache[id];
  6561. }
  6562. }
  6563. };
  6564. return CachedCanvases;
  6565. }();
  6566. function compileType3Glyph(imgData) {
  6567. var POINT_TO_PROCESS_LIMIT = 1000;
  6568. var width = imgData.width, height = imgData.height;
  6569. var i, j, j0, width1 = width + 1;
  6570. var points = new Uint8Array(width1 * (height + 1));
  6571. var POINT_TYPES = new Uint8Array([
  6572. 0,
  6573. 2,
  6574. 4,
  6575. 0,
  6576. 1,
  6577. 0,
  6578. 5,
  6579. 4,
  6580. 8,
  6581. 10,
  6582. 0,
  6583. 8,
  6584. 0,
  6585. 2,
  6586. 1,
  6587. 0
  6588. ]);
  6589. // decodes bit-packed mask data
  6590. var lineSize = width + 7 & ~7, data0 = imgData.data;
  6591. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6592. for (i = 0, ii = data0.length; i < ii; i++) {
  6593. var mask = 128, elem = data0[i];
  6594. while (mask > 0) {
  6595. data[pos++] = elem & mask ? 0 : 255;
  6596. mask >>= 1;
  6597. }
  6598. }
  6599. // finding iteresting points: every point is located between mask pixels,
  6600. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6601. // will have flags assigned based on neighboring mask pixels:
  6602. // 4 | 8
  6603. // --P--
  6604. // 2 | 1
  6605. // We are interested only in points with the flags:
  6606. // - outside corners: 1, 2, 4, 8;
  6607. // - inside corners: 7, 11, 13, 14;
  6608. // - and, intersections: 5, 10.
  6609. var count = 0;
  6610. pos = 0;
  6611. if (data[pos] !== 0) {
  6612. points[0] = 1;
  6613. ++count;
  6614. }
  6615. for (j = 1; j < width; j++) {
  6616. if (data[pos] !== data[pos + 1]) {
  6617. points[j] = data[pos] ? 2 : 1;
  6618. ++count;
  6619. }
  6620. pos++;
  6621. }
  6622. if (data[pos] !== 0) {
  6623. points[j] = 2;
  6624. ++count;
  6625. }
  6626. for (i = 1; i < height; i++) {
  6627. pos = i * lineSize;
  6628. j0 = i * width1;
  6629. if (data[pos - lineSize] !== data[pos]) {
  6630. points[j0] = data[pos] ? 1 : 8;
  6631. ++count;
  6632. }
  6633. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6634. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6635. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6636. for (j = 1; j < width; j++) {
  6637. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6638. if (POINT_TYPES[sum]) {
  6639. points[j0 + j] = POINT_TYPES[sum];
  6640. ++count;
  6641. }
  6642. pos++;
  6643. }
  6644. if (data[pos - lineSize] !== data[pos]) {
  6645. points[j0 + j] = data[pos] ? 2 : 4;
  6646. ++count;
  6647. }
  6648. if (count > POINT_TO_PROCESS_LIMIT) {
  6649. return null;
  6650. }
  6651. }
  6652. pos = lineSize * (height - 1);
  6653. j0 = i * width1;
  6654. if (data[pos] !== 0) {
  6655. points[j0] = 8;
  6656. ++count;
  6657. }
  6658. for (j = 1; j < width; j++) {
  6659. if (data[pos] !== data[pos + 1]) {
  6660. points[j0 + j] = data[pos] ? 4 : 8;
  6661. ++count;
  6662. }
  6663. pos++;
  6664. }
  6665. if (data[pos] !== 0) {
  6666. points[j0 + j] = 4;
  6667. ++count;
  6668. }
  6669. if (count > POINT_TO_PROCESS_LIMIT) {
  6670. return null;
  6671. }
  6672. // building outlines
  6673. var steps = new Int32Array([
  6674. 0,
  6675. width1,
  6676. -1,
  6677. 0,
  6678. -width1,
  6679. 0,
  6680. 0,
  6681. 0,
  6682. 1
  6683. ]);
  6684. var outlines = [];
  6685. for (i = 0; count && i <= height; i++) {
  6686. var p = i * width1;
  6687. var end = p + width;
  6688. while (p < end && !points[p]) {
  6689. p++;
  6690. }
  6691. if (p === end) {
  6692. continue;
  6693. }
  6694. var coords = [
  6695. p % width1,
  6696. i
  6697. ];
  6698. var type = points[p], p0 = p, pp;
  6699. do {
  6700. var step = steps[type];
  6701. do {
  6702. p += step;
  6703. } while (!points[p]);
  6704. pp = points[p];
  6705. if (pp !== 5 && pp !== 10) {
  6706. // set new direction
  6707. type = pp;
  6708. // delete mark
  6709. points[p] = 0;
  6710. } else {
  6711. // type is 5 or 10, ie, a crossing
  6712. // set new direction
  6713. type = pp & 0x33 * type >> 4;
  6714. // set new type for "future hit"
  6715. points[p] &= type >> 2 | type << 2;
  6716. }
  6717. coords.push(p % width1);
  6718. coords.push(p / width1 | 0);
  6719. --count;
  6720. } while (p0 !== p);
  6721. outlines.push(coords);
  6722. --i;
  6723. }
  6724. var drawOutline = function (c) {
  6725. c.save();
  6726. // the path shall be painted in [0..1]x[0..1] space
  6727. c.scale(1 / width, -1 / height);
  6728. c.translate(0, -height);
  6729. c.beginPath();
  6730. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6731. var o = outlines[i];
  6732. c.moveTo(o[0], o[1]);
  6733. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6734. c.lineTo(o[j], o[j + 1]);
  6735. }
  6736. }
  6737. c.fill();
  6738. c.beginPath();
  6739. c.restore();
  6740. };
  6741. return drawOutline;
  6742. }
  6743. var CanvasExtraState = function CanvasExtraStateClosure() {
  6744. function CanvasExtraState(old) {
  6745. // Are soft masks and alpha values shapes or opacities?
  6746. this.alphaIsShape = false;
  6747. this.fontSize = 0;
  6748. this.fontSizeScale = 1;
  6749. this.textMatrix = IDENTITY_MATRIX;
  6750. this.textMatrixScale = 1;
  6751. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6752. this.leading = 0;
  6753. // Current point (in user coordinates)
  6754. this.x = 0;
  6755. this.y = 0;
  6756. // Start of text line (in text coordinates)
  6757. this.lineX = 0;
  6758. this.lineY = 0;
  6759. // Character and word spacing
  6760. this.charSpacing = 0;
  6761. this.wordSpacing = 0;
  6762. this.textHScale = 1;
  6763. this.textRenderingMode = TextRenderingMode.FILL;
  6764. this.textRise = 0;
  6765. // Default fore and background colors
  6766. this.fillColor = '#000000';
  6767. this.strokeColor = '#000000';
  6768. this.patternFill = false;
  6769. // Note: fill alpha applies to all non-stroking operations
  6770. this.fillAlpha = 1;
  6771. this.strokeAlpha = 1;
  6772. this.lineWidth = 1;
  6773. this.activeSMask = null;
  6774. this.resumeSMaskCtx = null;
  6775. // nonclonable field (see the save method below)
  6776. this.old = old;
  6777. }
  6778. CanvasExtraState.prototype = {
  6779. clone: function CanvasExtraState_clone() {
  6780. return Object.create(this);
  6781. },
  6782. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6783. this.x = x;
  6784. this.y = y;
  6785. }
  6786. };
  6787. return CanvasExtraState;
  6788. }();
  6789. var CanvasGraphics = function CanvasGraphicsClosure() {
  6790. // Defines the time the executeOperatorList is going to be executing
  6791. // before it stops and shedules a continue of execution.
  6792. var EXECUTION_TIME = 15;
  6793. // Defines the number of steps before checking the execution time
  6794. var EXECUTION_STEPS = 10;
  6795. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6796. this.ctx = canvasCtx;
  6797. this.current = new CanvasExtraState();
  6798. this.stateStack = [];
  6799. this.pendingClip = null;
  6800. this.pendingEOFill = false;
  6801. this.res = null;
  6802. this.xobjs = null;
  6803. this.commonObjs = commonObjs;
  6804. this.objs = objs;
  6805. this.imageLayer = imageLayer;
  6806. this.groupStack = [];
  6807. this.processingType3 = null;
  6808. // Patterns are painted relative to the initial page/form transform, see pdf
  6809. // spec 8.7.2 NOTE 1.
  6810. this.baseTransform = null;
  6811. this.baseTransformStack = [];
  6812. this.groupLevel = 0;
  6813. this.smaskStack = [];
  6814. this.smaskCounter = 0;
  6815. this.tempSMask = null;
  6816. this.cachedCanvases = new CachedCanvases();
  6817. if (canvasCtx) {
  6818. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6819. // the transformation must already be set in canvasCtx._transformMatrix.
  6820. addContextCurrentTransform(canvasCtx);
  6821. }
  6822. this.cachedGetSinglePixelWidth = null;
  6823. }
  6824. function putBinaryImageData(ctx, imgData) {
  6825. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6826. ctx.putImageData(imgData, 0, 0);
  6827. return;
  6828. }
  6829. // Put the image data to the canvas in chunks, rather than putting the
  6830. // whole image at once. This saves JS memory, because the ImageData object
  6831. // is smaller. It also possibly saves C++ memory within the implementation
  6832. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6833. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6834. // because too many putImageData() calls will slow things down.
  6835. //
  6836. // Note: as written, if the last chunk is partial, the putImageData() call
  6837. // will (conceptually) put pixels past the bounds of the canvas. But
  6838. // that's ok; any such pixels are ignored.
  6839. var height = imgData.height, width = imgData.width;
  6840. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6841. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6842. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6843. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6844. var srcPos = 0, destPos;
  6845. var src = imgData.data;
  6846. var dest = chunkImgData.data;
  6847. var i, j, thisChunkHeight, elemsInThisChunk;
  6848. // There are multiple forms in which the pixel data can be passed, and
  6849. // imgData.kind tells us which one this is.
  6850. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6851. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6852. var srcLength = src.byteLength;
  6853. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6854. var dest32DataLength = dest32.length;
  6855. var fullSrcDiff = width + 7 >> 3;
  6856. var white = 0xFFFFFFFF;
  6857. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6858. for (i = 0; i < totalChunks; i++) {
  6859. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6860. destPos = 0;
  6861. for (j = 0; j < thisChunkHeight; j++) {
  6862. var srcDiff = srcLength - srcPos;
  6863. var k = 0;
  6864. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6865. var kEndUnrolled = kEnd & ~7;
  6866. var mask = 0;
  6867. var srcByte = 0;
  6868. for (; k < kEndUnrolled; k += 8) {
  6869. srcByte = src[srcPos++];
  6870. dest32[destPos++] = srcByte & 128 ? white : black;
  6871. dest32[destPos++] = srcByte & 64 ? white : black;
  6872. dest32[destPos++] = srcByte & 32 ? white : black;
  6873. dest32[destPos++] = srcByte & 16 ? white : black;
  6874. dest32[destPos++] = srcByte & 8 ? white : black;
  6875. dest32[destPos++] = srcByte & 4 ? white : black;
  6876. dest32[destPos++] = srcByte & 2 ? white : black;
  6877. dest32[destPos++] = srcByte & 1 ? white : black;
  6878. }
  6879. for (; k < kEnd; k++) {
  6880. if (mask === 0) {
  6881. srcByte = src[srcPos++];
  6882. mask = 128;
  6883. }
  6884. dest32[destPos++] = srcByte & mask ? white : black;
  6885. mask >>= 1;
  6886. }
  6887. }
  6888. // We ran out of input. Make all remaining pixels transparent.
  6889. while (destPos < dest32DataLength) {
  6890. dest32[destPos++] = 0;
  6891. }
  6892. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6893. }
  6894. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6895. // RGBA, 32-bits per pixel.
  6896. j = 0;
  6897. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6898. for (i = 0; i < fullChunks; i++) {
  6899. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6900. srcPos += elemsInThisChunk;
  6901. ctx.putImageData(chunkImgData, 0, j);
  6902. j += FULL_CHUNK_HEIGHT;
  6903. }
  6904. if (i < totalChunks) {
  6905. elemsInThisChunk = width * partialChunkHeight * 4;
  6906. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6907. ctx.putImageData(chunkImgData, 0, j);
  6908. }
  6909. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6910. // RGB, 24-bits per pixel.
  6911. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6912. elemsInThisChunk = width * thisChunkHeight;
  6913. for (i = 0; i < totalChunks; i++) {
  6914. if (i >= fullChunks) {
  6915. thisChunkHeight = partialChunkHeight;
  6916. elemsInThisChunk = width * thisChunkHeight;
  6917. }
  6918. destPos = 0;
  6919. for (j = elemsInThisChunk; j--;) {
  6920. dest[destPos++] = src[srcPos++];
  6921. dest[destPos++] = src[srcPos++];
  6922. dest[destPos++] = src[srcPos++];
  6923. dest[destPos++] = 255;
  6924. }
  6925. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6926. }
  6927. } else {
  6928. error('bad image kind: ' + imgData.kind);
  6929. }
  6930. }
  6931. function putBinaryImageMask(ctx, imgData) {
  6932. var height = imgData.height, width = imgData.width;
  6933. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6934. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6935. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6936. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6937. var srcPos = 0;
  6938. var src = imgData.data;
  6939. var dest = chunkImgData.data;
  6940. for (var i = 0; i < totalChunks; i++) {
  6941. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6942. // Expand the mask so it can be used by the canvas. Any required
  6943. // inversion has already been handled.
  6944. var destPos = 3;
  6945. // alpha component offset
  6946. for (var j = 0; j < thisChunkHeight; j++) {
  6947. var mask = 0;
  6948. for (var k = 0; k < width; k++) {
  6949. if (!mask) {
  6950. var elem = src[srcPos++];
  6951. mask = 128;
  6952. }
  6953. dest[destPos] = elem & mask ? 0 : 255;
  6954. destPos += 4;
  6955. mask >>= 1;
  6956. }
  6957. }
  6958. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6959. }
  6960. }
  6961. function copyCtxState(sourceCtx, destCtx) {
  6962. var properties = [
  6963. 'strokeStyle',
  6964. 'fillStyle',
  6965. 'fillRule',
  6966. 'globalAlpha',
  6967. 'lineWidth',
  6968. 'lineCap',
  6969. 'lineJoin',
  6970. 'miterLimit',
  6971. 'globalCompositeOperation',
  6972. 'font'
  6973. ];
  6974. for (var i = 0, ii = properties.length; i < ii; i++) {
  6975. var property = properties[i];
  6976. if (sourceCtx[property] !== undefined) {
  6977. destCtx[property] = sourceCtx[property];
  6978. }
  6979. }
  6980. if (sourceCtx.setLineDash !== undefined) {
  6981. destCtx.setLineDash(sourceCtx.getLineDash());
  6982. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6983. }
  6984. }
  6985. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6986. var length = bytes.length;
  6987. for (var i = 3; i < length; i += 4) {
  6988. var alpha = bytes[i];
  6989. if (alpha === 0) {
  6990. bytes[i - 3] = r0;
  6991. bytes[i - 2] = g0;
  6992. bytes[i - 1] = b0;
  6993. } else if (alpha < 255) {
  6994. var alpha_ = 255 - alpha;
  6995. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  6996. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  6997. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  6998. }
  6999. }
  7000. }
  7001. function composeSMaskAlpha(maskData, layerData, transferMap) {
  7002. var length = maskData.length;
  7003. var scale = 1 / 255;
  7004. for (var i = 3; i < length; i += 4) {
  7005. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  7006. layerData[i] = layerData[i] * alpha * scale | 0;
  7007. }
  7008. }
  7009. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  7010. var length = maskData.length;
  7011. for (var i = 3; i < length; i += 4) {
  7012. var y = maskData[i - 3] * 77 + // * 0.3 / 255 * 0x10000
  7013. maskData[i - 2] * 152 + // * 0.59 ....
  7014. maskData[i - 1] * 28;
  7015. // * 0.11 ....
  7016. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  7017. }
  7018. }
  7019. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  7020. var hasBackdrop = !!backdrop;
  7021. var r0 = hasBackdrop ? backdrop[0] : 0;
  7022. var g0 = hasBackdrop ? backdrop[1] : 0;
  7023. var b0 = hasBackdrop ? backdrop[2] : 0;
  7024. var composeFn;
  7025. if (subtype === 'Luminosity') {
  7026. composeFn = composeSMaskLuminosity;
  7027. } else {
  7028. composeFn = composeSMaskAlpha;
  7029. }
  7030. // processing image in chunks to save memory
  7031. var PIXELS_TO_PROCESS = 1048576;
  7032. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  7033. for (var row = 0; row < height; row += chunkSize) {
  7034. var chunkHeight = Math.min(chunkSize, height - row);
  7035. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  7036. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  7037. if (hasBackdrop) {
  7038. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  7039. }
  7040. composeFn(maskData.data, layerData.data, transferMap);
  7041. maskCtx.putImageData(layerData, 0, row);
  7042. }
  7043. }
  7044. function composeSMask(ctx, smask, layerCtx) {
  7045. var mask = smask.canvas;
  7046. var maskCtx = smask.context;
  7047. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  7048. var backdrop = smask.backdrop || null;
  7049. if (!smask.transferMap && WebGLUtils.isEnabled) {
  7050. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  7051. subtype: smask.subtype,
  7052. backdrop: backdrop
  7053. });
  7054. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7055. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  7056. return;
  7057. }
  7058. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  7059. ctx.drawImage(mask, 0, 0);
  7060. }
  7061. var LINE_CAP_STYLES = [
  7062. 'butt',
  7063. 'round',
  7064. 'square'
  7065. ];
  7066. var LINE_JOIN_STYLES = [
  7067. 'miter',
  7068. 'round',
  7069. 'bevel'
  7070. ];
  7071. var NORMAL_CLIP = {};
  7072. var EO_CLIP = {};
  7073. CanvasGraphics.prototype = {
  7074. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  7075. // For pdfs that use blend modes we have to clear the canvas else certain
  7076. // blend modes can look wrong since we'd be blending with a white
  7077. // backdrop. The problem with a transparent backdrop though is we then
  7078. // don't get sub pixel anti aliasing on text, creating temporary
  7079. // transparent canvas when we have blend modes.
  7080. var width = this.ctx.canvas.width;
  7081. var height = this.ctx.canvas.height;
  7082. this.ctx.save();
  7083. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  7084. this.ctx.fillRect(0, 0, width, height);
  7085. this.ctx.restore();
  7086. if (transparency) {
  7087. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  7088. this.compositeCtx = this.ctx;
  7089. this.transparentCanvas = transparentCanvas.canvas;
  7090. this.ctx = transparentCanvas.context;
  7091. this.ctx.save();
  7092. // The transform can be applied before rendering, transferring it to
  7093. // the new canvas.
  7094. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  7095. }
  7096. this.ctx.save();
  7097. if (transform) {
  7098. this.ctx.transform.apply(this.ctx, transform);
  7099. }
  7100. this.ctx.transform.apply(this.ctx, viewport.transform);
  7101. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  7102. if (this.imageLayer) {
  7103. this.imageLayer.beginLayout();
  7104. }
  7105. },
  7106. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7107. var argsArray = operatorList.argsArray;
  7108. var fnArray = operatorList.fnArray;
  7109. var i = executionStartIdx || 0;
  7110. var argsArrayLen = argsArray.length;
  7111. // Sometimes the OperatorList to execute is empty.
  7112. if (argsArrayLen === i) {
  7113. return i;
  7114. }
  7115. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  7116. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7117. var steps = 0;
  7118. var commonObjs = this.commonObjs;
  7119. var objs = this.objs;
  7120. var fnId;
  7121. while (true) {
  7122. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7123. stepper.breakIt(i, continueCallback);
  7124. return i;
  7125. }
  7126. fnId = fnArray[i];
  7127. if (fnId !== OPS.dependency) {
  7128. this[fnId].apply(this, argsArray[i]);
  7129. } else {
  7130. var deps = argsArray[i];
  7131. for (var n = 0, nn = deps.length; n < nn; n++) {
  7132. var depObjId = deps[n];
  7133. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  7134. var objsPool = common ? commonObjs : objs;
  7135. // If the promise isn't resolved yet, add the continueCallback
  7136. // to the promise and bail out.
  7137. if (!objsPool.isResolved(depObjId)) {
  7138. objsPool.get(depObjId, continueCallback);
  7139. return i;
  7140. }
  7141. }
  7142. }
  7143. i++;
  7144. // If the entire operatorList was executed, stop as were done.
  7145. if (i === argsArrayLen) {
  7146. return i;
  7147. }
  7148. // If the execution took longer then a certain amount of time and
  7149. // `continueCallback` is specified, interrupt the execution.
  7150. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7151. if (Date.now() > endTime) {
  7152. continueCallback();
  7153. return i;
  7154. }
  7155. steps = 0;
  7156. }
  7157. }
  7158. },
  7159. // If the operatorList isn't executed completely yet OR the execution
  7160. // time was short enough, do another execution round.
  7161. endDrawing: function CanvasGraphics_endDrawing() {
  7162. // Finishing all opened operations such as SMask group painting.
  7163. if (this.current.activeSMask !== null) {
  7164. this.endSMaskGroup();
  7165. }
  7166. this.ctx.restore();
  7167. if (this.transparentCanvas) {
  7168. this.ctx = this.compositeCtx;
  7169. this.ctx.save();
  7170. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7171. // Avoid apply transform twice
  7172. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7173. this.ctx.restore();
  7174. this.transparentCanvas = null;
  7175. }
  7176. this.cachedCanvases.clear();
  7177. WebGLUtils.clear();
  7178. if (this.imageLayer) {
  7179. this.imageLayer.endLayout();
  7180. }
  7181. },
  7182. // Graphics state
  7183. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  7184. this.current.lineWidth = width;
  7185. this.ctx.lineWidth = width;
  7186. },
  7187. setLineCap: function CanvasGraphics_setLineCap(style) {
  7188. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7189. },
  7190. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  7191. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7192. },
  7193. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  7194. this.ctx.miterLimit = limit;
  7195. },
  7196. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  7197. var ctx = this.ctx;
  7198. if (ctx.setLineDash !== undefined) {
  7199. ctx.setLineDash(dashArray);
  7200. ctx.lineDashOffset = dashPhase;
  7201. }
  7202. },
  7203. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  7204. },
  7205. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  7206. },
  7207. setGState: function CanvasGraphics_setGState(states) {
  7208. for (var i = 0, ii = states.length; i < ii; i++) {
  7209. var state = states[i];
  7210. var key = state[0];
  7211. var value = state[1];
  7212. switch (key) {
  7213. case 'LW':
  7214. this.setLineWidth(value);
  7215. break;
  7216. case 'LC':
  7217. this.setLineCap(value);
  7218. break;
  7219. case 'LJ':
  7220. this.setLineJoin(value);
  7221. break;
  7222. case 'ML':
  7223. this.setMiterLimit(value);
  7224. break;
  7225. case 'D':
  7226. this.setDash(value[0], value[1]);
  7227. break;
  7228. case 'RI':
  7229. this.setRenderingIntent(value);
  7230. break;
  7231. case 'FL':
  7232. this.setFlatness(value);
  7233. break;
  7234. case 'Font':
  7235. this.setFont(value[0], value[1]);
  7236. break;
  7237. case 'CA':
  7238. this.current.strokeAlpha = state[1];
  7239. break;
  7240. case 'ca':
  7241. this.current.fillAlpha = state[1];
  7242. this.ctx.globalAlpha = state[1];
  7243. break;
  7244. case 'BM':
  7245. if (value && value.name && value.name !== 'Normal') {
  7246. var mode = value.name.replace(/([A-Z])/g, function (c) {
  7247. return '-' + c.toLowerCase();
  7248. }).substring(1);
  7249. this.ctx.globalCompositeOperation = mode;
  7250. if (this.ctx.globalCompositeOperation !== mode) {
  7251. warn('globalCompositeOperation "' + mode + '" is not supported');
  7252. }
  7253. } else {
  7254. this.ctx.globalCompositeOperation = 'source-over';
  7255. }
  7256. break;
  7257. case 'SMask':
  7258. if (this.current.activeSMask) {
  7259. // If SMask is currrenly used, it needs to be suspended or
  7260. // finished. Suspend only makes sense when at least one save()
  7261. // was performed and state needs to be reverted on restore().
  7262. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  7263. this.suspendSMaskGroup();
  7264. } else {
  7265. this.endSMaskGroup();
  7266. }
  7267. }
  7268. this.current.activeSMask = value ? this.tempSMask : null;
  7269. if (this.current.activeSMask) {
  7270. this.beginSMaskGroup();
  7271. }
  7272. this.tempSMask = null;
  7273. break;
  7274. }
  7275. }
  7276. },
  7277. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  7278. var activeSMask = this.current.activeSMask;
  7279. var drawnWidth = activeSMask.canvas.width;
  7280. var drawnHeight = activeSMask.canvas.height;
  7281. var cacheId = 'smaskGroupAt' + this.groupLevel;
  7282. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7283. var currentCtx = this.ctx;
  7284. var currentTransform = currentCtx.mozCurrentTransform;
  7285. this.ctx.save();
  7286. var groupCtx = scratchCanvas.context;
  7287. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  7288. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  7289. groupCtx.transform.apply(groupCtx, currentTransform);
  7290. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  7291. copyCtxState(currentCtx, groupCtx);
  7292. this.ctx = groupCtx;
  7293. this.setGState([
  7294. [
  7295. 'BM',
  7296. 'Normal'
  7297. ],
  7298. [
  7299. 'ca',
  7300. 1
  7301. ],
  7302. [
  7303. 'CA',
  7304. 1
  7305. ]
  7306. ]);
  7307. this.groupStack.push(currentCtx);
  7308. this.groupLevel++;
  7309. },
  7310. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7311. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7312. // and future ctx state restored.
  7313. var groupCtx = this.ctx;
  7314. this.groupLevel--;
  7315. this.ctx = this.groupStack.pop();
  7316. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7317. this.ctx.restore();
  7318. this.ctx.save();
  7319. // save is needed since SMask will be resumed.
  7320. copyCtxState(groupCtx, this.ctx);
  7321. // Saving state for resuming.
  7322. this.current.resumeSMaskCtx = groupCtx;
  7323. // Transform was changed in the SMask canvas, reflecting this change on
  7324. // this.ctx.
  7325. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7326. this.ctx.transform.apply(this.ctx, deltaTransform);
  7327. // SMask was composed, the results at the groupCtx can be cleared.
  7328. groupCtx.save();
  7329. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7330. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7331. groupCtx.restore();
  7332. },
  7333. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7334. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7335. // any groupCtx state since restore() command (the only caller) will do
  7336. // that for us. See also beginSMaskGroup.
  7337. var groupCtx = this.current.resumeSMaskCtx;
  7338. var currentCtx = this.ctx;
  7339. this.ctx = groupCtx;
  7340. this.groupStack.push(currentCtx);
  7341. this.groupLevel++;
  7342. },
  7343. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7344. var groupCtx = this.ctx;
  7345. this.groupLevel--;
  7346. this.ctx = this.groupStack.pop();
  7347. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7348. this.ctx.restore();
  7349. copyCtxState(groupCtx, this.ctx);
  7350. // Transform was changed in the SMask canvas, reflecting this change on
  7351. // this.ctx.
  7352. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7353. this.ctx.transform.apply(this.ctx, deltaTransform);
  7354. },
  7355. save: function CanvasGraphics_save() {
  7356. this.ctx.save();
  7357. var old = this.current;
  7358. this.stateStack.push(old);
  7359. this.current = old.clone();
  7360. this.current.resumeSMaskCtx = null;
  7361. },
  7362. restore: function CanvasGraphics_restore() {
  7363. // SMask was suspended, we just need to resume it.
  7364. if (this.current.resumeSMaskCtx) {
  7365. this.resumeSMaskGroup();
  7366. }
  7367. // SMask has to be finished once there is no states that are using the
  7368. // same SMask.
  7369. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  7370. this.endSMaskGroup();
  7371. }
  7372. if (this.stateStack.length !== 0) {
  7373. this.current = this.stateStack.pop();
  7374. this.ctx.restore();
  7375. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7376. this.pendingClip = null;
  7377. this.cachedGetSinglePixelWidth = null;
  7378. }
  7379. },
  7380. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7381. this.ctx.transform(a, b, c, d, e, f);
  7382. this.cachedGetSinglePixelWidth = null;
  7383. },
  7384. // Path
  7385. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7386. var ctx = this.ctx;
  7387. var current = this.current;
  7388. var x = current.x, y = current.y;
  7389. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7390. switch (ops[i] | 0) {
  7391. case OPS.rectangle:
  7392. x = args[j++];
  7393. y = args[j++];
  7394. var width = args[j++];
  7395. var height = args[j++];
  7396. if (width === 0) {
  7397. width = this.getSinglePixelWidth();
  7398. }
  7399. if (height === 0) {
  7400. height = this.getSinglePixelWidth();
  7401. }
  7402. var xw = x + width;
  7403. var yh = y + height;
  7404. this.ctx.moveTo(x, y);
  7405. this.ctx.lineTo(xw, y);
  7406. this.ctx.lineTo(xw, yh);
  7407. this.ctx.lineTo(x, yh);
  7408. this.ctx.lineTo(x, y);
  7409. this.ctx.closePath();
  7410. break;
  7411. case OPS.moveTo:
  7412. x = args[j++];
  7413. y = args[j++];
  7414. ctx.moveTo(x, y);
  7415. break;
  7416. case OPS.lineTo:
  7417. x = args[j++];
  7418. y = args[j++];
  7419. ctx.lineTo(x, y);
  7420. break;
  7421. case OPS.curveTo:
  7422. x = args[j + 4];
  7423. y = args[j + 5];
  7424. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7425. j += 6;
  7426. break;
  7427. case OPS.curveTo2:
  7428. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7429. x = args[j + 2];
  7430. y = args[j + 3];
  7431. j += 4;
  7432. break;
  7433. case OPS.curveTo3:
  7434. x = args[j + 2];
  7435. y = args[j + 3];
  7436. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7437. j += 4;
  7438. break;
  7439. case OPS.closePath:
  7440. ctx.closePath();
  7441. break;
  7442. }
  7443. }
  7444. current.setCurrentPoint(x, y);
  7445. },
  7446. closePath: function CanvasGraphics_closePath() {
  7447. this.ctx.closePath();
  7448. },
  7449. stroke: function CanvasGraphics_stroke(consumePath) {
  7450. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7451. var ctx = this.ctx;
  7452. var strokeColor = this.current.strokeColor;
  7453. // Prevent drawing too thin lines by enforcing a minimum line width.
  7454. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  7455. // For stroke we want to temporarily change the global alpha to the
  7456. // stroking alpha.
  7457. ctx.globalAlpha = this.current.strokeAlpha;
  7458. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  7459. // for patterns, we transform to pattern space, calculate
  7460. // the pattern, call stroke, and restore to user space
  7461. ctx.save();
  7462. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7463. ctx.stroke();
  7464. ctx.restore();
  7465. } else {
  7466. ctx.stroke();
  7467. }
  7468. if (consumePath) {
  7469. this.consumePath();
  7470. }
  7471. // Restore the global alpha to the fill alpha
  7472. ctx.globalAlpha = this.current.fillAlpha;
  7473. },
  7474. closeStroke: function CanvasGraphics_closeStroke() {
  7475. this.closePath();
  7476. this.stroke();
  7477. },
  7478. fill: function CanvasGraphics_fill(consumePath) {
  7479. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7480. var ctx = this.ctx;
  7481. var fillColor = this.current.fillColor;
  7482. var isPatternFill = this.current.patternFill;
  7483. var needRestore = false;
  7484. if (isPatternFill) {
  7485. ctx.save();
  7486. if (this.baseTransform) {
  7487. ctx.setTransform.apply(ctx, this.baseTransform);
  7488. }
  7489. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7490. needRestore = true;
  7491. }
  7492. if (this.pendingEOFill) {
  7493. if (ctx.mozFillRule !== undefined) {
  7494. ctx.mozFillRule = 'evenodd';
  7495. ctx.fill();
  7496. ctx.mozFillRule = 'nonzero';
  7497. } else {
  7498. ctx.fill('evenodd');
  7499. }
  7500. this.pendingEOFill = false;
  7501. } else {
  7502. ctx.fill();
  7503. }
  7504. if (needRestore) {
  7505. ctx.restore();
  7506. }
  7507. if (consumePath) {
  7508. this.consumePath();
  7509. }
  7510. },
  7511. eoFill: function CanvasGraphics_eoFill() {
  7512. this.pendingEOFill = true;
  7513. this.fill();
  7514. },
  7515. fillStroke: function CanvasGraphics_fillStroke() {
  7516. this.fill(false);
  7517. this.stroke(false);
  7518. this.consumePath();
  7519. },
  7520. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7521. this.pendingEOFill = true;
  7522. this.fillStroke();
  7523. },
  7524. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7525. this.closePath();
  7526. this.fillStroke();
  7527. },
  7528. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7529. this.pendingEOFill = true;
  7530. this.closePath();
  7531. this.fillStroke();
  7532. },
  7533. endPath: function CanvasGraphics_endPath() {
  7534. this.consumePath();
  7535. },
  7536. // Clipping
  7537. clip: function CanvasGraphics_clip() {
  7538. this.pendingClip = NORMAL_CLIP;
  7539. },
  7540. eoClip: function CanvasGraphics_eoClip() {
  7541. this.pendingClip = EO_CLIP;
  7542. },
  7543. // Text
  7544. beginText: function CanvasGraphics_beginText() {
  7545. this.current.textMatrix = IDENTITY_MATRIX;
  7546. this.current.textMatrixScale = 1;
  7547. this.current.x = this.current.lineX = 0;
  7548. this.current.y = this.current.lineY = 0;
  7549. },
  7550. endText: function CanvasGraphics_endText() {
  7551. var paths = this.pendingTextPaths;
  7552. var ctx = this.ctx;
  7553. if (paths === undefined) {
  7554. ctx.beginPath();
  7555. return;
  7556. }
  7557. ctx.save();
  7558. ctx.beginPath();
  7559. for (var i = 0; i < paths.length; i++) {
  7560. var path = paths[i];
  7561. ctx.setTransform.apply(ctx, path.transform);
  7562. ctx.translate(path.x, path.y);
  7563. path.addToPath(ctx, path.fontSize);
  7564. }
  7565. ctx.restore();
  7566. ctx.clip();
  7567. ctx.beginPath();
  7568. delete this.pendingTextPaths;
  7569. },
  7570. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7571. this.current.charSpacing = spacing;
  7572. },
  7573. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7574. this.current.wordSpacing = spacing;
  7575. },
  7576. setHScale: function CanvasGraphics_setHScale(scale) {
  7577. this.current.textHScale = scale / 100;
  7578. },
  7579. setLeading: function CanvasGraphics_setLeading(leading) {
  7580. this.current.leading = -leading;
  7581. },
  7582. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7583. var fontObj = this.commonObjs.get(fontRefName);
  7584. var current = this.current;
  7585. if (!fontObj) {
  7586. error('Can\'t find font for ' + fontRefName);
  7587. }
  7588. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  7589. // A valid matrix needs all main diagonal elements to be non-zero
  7590. // This also ensures we bypass FF bugzilla bug #719844.
  7591. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7592. warn('Invalid font matrix for font ' + fontRefName);
  7593. }
  7594. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7595. // and in some docs this can be negative (inverted x-y axes).
  7596. if (size < 0) {
  7597. size = -size;
  7598. current.fontDirection = -1;
  7599. } else {
  7600. current.fontDirection = 1;
  7601. }
  7602. this.current.font = fontObj;
  7603. this.current.fontSize = size;
  7604. if (fontObj.isType3Font) {
  7605. return;
  7606. }
  7607. // we don't need ctx.font for Type3 fonts
  7608. var name = fontObj.loadedName || 'sans-serif';
  7609. var bold = fontObj.black ? fontObj.bold ? '900' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  7610. var italic = fontObj.italic ? 'italic' : 'normal';
  7611. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7612. // Some font backends cannot handle fonts below certain size.
  7613. // Keeping the font at minimal size and using the fontSizeScale to change
  7614. // the current transformation matrix before the fillText/strokeText.
  7615. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7616. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7617. this.current.fontSizeScale = size / browserFontSize;
  7618. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7619. this.ctx.font = rule;
  7620. },
  7621. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7622. this.current.textRenderingMode = mode;
  7623. },
  7624. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7625. this.current.textRise = rise;
  7626. },
  7627. moveText: function CanvasGraphics_moveText(x, y) {
  7628. this.current.x = this.current.lineX += x;
  7629. this.current.y = this.current.lineY += y;
  7630. },
  7631. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7632. this.setLeading(-y);
  7633. this.moveText(x, y);
  7634. },
  7635. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7636. this.current.textMatrix = [
  7637. a,
  7638. b,
  7639. c,
  7640. d,
  7641. e,
  7642. f
  7643. ];
  7644. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7645. this.current.x = this.current.lineX = 0;
  7646. this.current.y = this.current.lineY = 0;
  7647. },
  7648. nextLine: function CanvasGraphics_nextLine() {
  7649. this.moveText(0, this.current.leading);
  7650. },
  7651. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7652. var ctx = this.ctx;
  7653. var current = this.current;
  7654. var font = current.font;
  7655. var textRenderingMode = current.textRenderingMode;
  7656. var fontSize = current.fontSize / current.fontSizeScale;
  7657. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7658. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7659. var addToPath;
  7660. if (font.disableFontFace || isAddToPathSet) {
  7661. addToPath = font.getPathGenerator(this.commonObjs, character);
  7662. }
  7663. if (font.disableFontFace) {
  7664. ctx.save();
  7665. ctx.translate(x, y);
  7666. ctx.beginPath();
  7667. addToPath(ctx, fontSize);
  7668. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7669. ctx.fill();
  7670. }
  7671. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7672. ctx.stroke();
  7673. }
  7674. ctx.restore();
  7675. } else {
  7676. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7677. ctx.fillText(character, x, y);
  7678. }
  7679. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7680. ctx.strokeText(character, x, y);
  7681. }
  7682. }
  7683. if (isAddToPathSet) {
  7684. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7685. paths.push({
  7686. transform: ctx.mozCurrentTransform,
  7687. x: x,
  7688. y: y,
  7689. fontSize: fontSize,
  7690. addToPath: addToPath
  7691. });
  7692. }
  7693. },
  7694. get isFontSubpixelAAEnabled() {
  7695. // Checks if anti-aliasing is enabled when scaled text is painted.
  7696. // On Windows GDI scaled fonts looks bad.
  7697. var ctx = document.createElement('canvas').getContext('2d');
  7698. ctx.scale(1.5, 1);
  7699. ctx.fillText('I', 0, 10);
  7700. var data = ctx.getImageData(0, 0, 10, 10).data;
  7701. var enabled = false;
  7702. for (var i = 3; i < data.length; i += 4) {
  7703. if (data[i] > 0 && data[i] < 255) {
  7704. enabled = true;
  7705. break;
  7706. }
  7707. }
  7708. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7709. },
  7710. showText: function CanvasGraphics_showText(glyphs) {
  7711. var current = this.current;
  7712. var font = current.font;
  7713. if (font.isType3Font) {
  7714. return this.showType3Text(glyphs);
  7715. }
  7716. var fontSize = current.fontSize;
  7717. if (fontSize === 0) {
  7718. return;
  7719. }
  7720. var ctx = this.ctx;
  7721. var fontSizeScale = current.fontSizeScale;
  7722. var charSpacing = current.charSpacing;
  7723. var wordSpacing = current.wordSpacing;
  7724. var fontDirection = current.fontDirection;
  7725. var textHScale = current.textHScale * fontDirection;
  7726. var glyphsLength = glyphs.length;
  7727. var vertical = font.vertical;
  7728. var spacingDir = vertical ? 1 : -1;
  7729. var defaultVMetrics = font.defaultVMetrics;
  7730. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7731. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  7732. ctx.save();
  7733. ctx.transform.apply(ctx, current.textMatrix);
  7734. ctx.translate(current.x, current.y + current.textRise);
  7735. if (current.patternFill) {
  7736. // TODO: Some shading patterns are not applied correctly to text,
  7737. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7738. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7739. }
  7740. if (fontDirection > 0) {
  7741. ctx.scale(textHScale, -1);
  7742. } else {
  7743. ctx.scale(textHScale, 1);
  7744. }
  7745. var lineWidth = current.lineWidth;
  7746. var scale = current.textMatrixScale;
  7747. if (scale === 0 || lineWidth === 0) {
  7748. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7749. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7750. this.cachedGetSinglePixelWidth = null;
  7751. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7752. }
  7753. } else {
  7754. lineWidth /= scale;
  7755. }
  7756. if (fontSizeScale !== 1.0) {
  7757. ctx.scale(fontSizeScale, fontSizeScale);
  7758. lineWidth /= fontSizeScale;
  7759. }
  7760. ctx.lineWidth = lineWidth;
  7761. var x = 0, i;
  7762. for (i = 0; i < glyphsLength; ++i) {
  7763. var glyph = glyphs[i];
  7764. if (isNum(glyph)) {
  7765. x += spacingDir * glyph * fontSize / 1000;
  7766. continue;
  7767. }
  7768. var restoreNeeded = false;
  7769. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7770. var character = glyph.fontChar;
  7771. var accent = glyph.accent;
  7772. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7773. var width = glyph.width;
  7774. if (vertical) {
  7775. var vmetric, vx, vy;
  7776. vmetric = glyph.vmetric || defaultVMetrics;
  7777. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7778. vx = -vx * widthAdvanceScale;
  7779. vy = vmetric[2] * widthAdvanceScale;
  7780. width = vmetric ? -vmetric[0] : width;
  7781. scaledX = vx / fontSizeScale;
  7782. scaledY = (x + vy) / fontSizeScale;
  7783. } else {
  7784. scaledX = x / fontSizeScale;
  7785. scaledY = 0;
  7786. }
  7787. if (font.remeasure && width > 0) {
  7788. // Some standard fonts may not have the exact width: rescale per
  7789. // character if measured width is greater than expected glyph width
  7790. // and subpixel-aa is enabled, otherwise just center the glyph.
  7791. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7792. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7793. var characterScaleX = width / measuredWidth;
  7794. restoreNeeded = true;
  7795. ctx.save();
  7796. ctx.scale(characterScaleX, 1);
  7797. scaledX /= characterScaleX;
  7798. } else if (width !== measuredWidth) {
  7799. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7800. }
  7801. }
  7802. // Only attempt to draw the glyph if it is actually in the embedded font
  7803. // file or if there isn't a font file so the fallback font is shown.
  7804. if (glyph.isInFont || font.missingFile) {
  7805. if (simpleFillText && !accent) {
  7806. // common case
  7807. ctx.fillText(character, scaledX, scaledY);
  7808. } else {
  7809. this.paintChar(character, scaledX, scaledY);
  7810. if (accent) {
  7811. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7812. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7813. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7814. }
  7815. }
  7816. }
  7817. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7818. x += charWidth;
  7819. if (restoreNeeded) {
  7820. ctx.restore();
  7821. }
  7822. }
  7823. if (vertical) {
  7824. current.y -= x * textHScale;
  7825. } else {
  7826. current.x += x * textHScale;
  7827. }
  7828. ctx.restore();
  7829. },
  7830. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7831. // Type3 fonts - each glyph is a "mini-PDF"
  7832. var ctx = this.ctx;
  7833. var current = this.current;
  7834. var font = current.font;
  7835. var fontSize = current.fontSize;
  7836. var fontDirection = current.fontDirection;
  7837. var spacingDir = font.vertical ? 1 : -1;
  7838. var charSpacing = current.charSpacing;
  7839. var wordSpacing = current.wordSpacing;
  7840. var textHScale = current.textHScale * fontDirection;
  7841. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7842. var glyphsLength = glyphs.length;
  7843. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7844. var i, glyph, width, spacingLength;
  7845. if (isTextInvisible || fontSize === 0) {
  7846. return;
  7847. }
  7848. this.cachedGetSinglePixelWidth = null;
  7849. ctx.save();
  7850. ctx.transform.apply(ctx, current.textMatrix);
  7851. ctx.translate(current.x, current.y);
  7852. ctx.scale(textHScale, fontDirection);
  7853. for (i = 0; i < glyphsLength; ++i) {
  7854. glyph = glyphs[i];
  7855. if (isNum(glyph)) {
  7856. spacingLength = spacingDir * glyph * fontSize / 1000;
  7857. this.ctx.translate(spacingLength, 0);
  7858. current.x += spacingLength * textHScale;
  7859. continue;
  7860. }
  7861. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7862. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7863. if (!operatorList) {
  7864. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7865. continue;
  7866. }
  7867. this.processingType3 = glyph;
  7868. this.save();
  7869. ctx.scale(fontSize, fontSize);
  7870. ctx.transform.apply(ctx, fontMatrix);
  7871. this.executeOperatorList(operatorList);
  7872. this.restore();
  7873. var transformed = Util.applyTransform([
  7874. glyph.width,
  7875. 0
  7876. ], fontMatrix);
  7877. width = transformed[0] * fontSize + spacing;
  7878. ctx.translate(width, 0);
  7879. current.x += width * textHScale;
  7880. }
  7881. ctx.restore();
  7882. this.processingType3 = null;
  7883. },
  7884. // Type3 fonts
  7885. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7886. },
  7887. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7888. // TODO According to the spec we're also suppose to ignore any operators
  7889. // that set color or include images while processing this type3 font.
  7890. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7891. this.clip();
  7892. this.endPath();
  7893. },
  7894. // Color
  7895. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7896. var pattern;
  7897. if (IR[0] === 'TilingPattern') {
  7898. var color = IR[1];
  7899. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7900. var self = this;
  7901. var canvasGraphicsFactory = {
  7902. createCanvasGraphics: function (ctx) {
  7903. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7904. }
  7905. };
  7906. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7907. } else {
  7908. pattern = getShadingPatternFromIR(IR);
  7909. }
  7910. return pattern;
  7911. },
  7912. setStrokeColorN: function CanvasGraphics_setStrokeColorN()
  7913. /*...*/
  7914. {
  7915. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7916. },
  7917. setFillColorN: function CanvasGraphics_setFillColorN()
  7918. /*...*/
  7919. {
  7920. this.current.fillColor = this.getColorN_Pattern(arguments);
  7921. this.current.patternFill = true;
  7922. },
  7923. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7924. var color = Util.makeCssRgb(r, g, b);
  7925. this.ctx.strokeStyle = color;
  7926. this.current.strokeColor = color;
  7927. },
  7928. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7929. var color = Util.makeCssRgb(r, g, b);
  7930. this.ctx.fillStyle = color;
  7931. this.current.fillColor = color;
  7932. this.current.patternFill = false;
  7933. },
  7934. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7935. var ctx = this.ctx;
  7936. this.save();
  7937. var pattern = getShadingPatternFromIR(patternIR);
  7938. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7939. var inv = ctx.mozCurrentTransformInverse;
  7940. if (inv) {
  7941. var canvas = ctx.canvas;
  7942. var width = canvas.width;
  7943. var height = canvas.height;
  7944. var bl = Util.applyTransform([
  7945. 0,
  7946. 0
  7947. ], inv);
  7948. var br = Util.applyTransform([
  7949. 0,
  7950. height
  7951. ], inv);
  7952. var ul = Util.applyTransform([
  7953. width,
  7954. 0
  7955. ], inv);
  7956. var ur = Util.applyTransform([
  7957. width,
  7958. height
  7959. ], inv);
  7960. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7961. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7962. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7963. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7964. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7965. } else {
  7966. // HACK to draw the gradient onto an infinite rectangle.
  7967. // PDF gradients are drawn across the entire image while
  7968. // Canvas only allows gradients to be drawn in a rectangle
  7969. // The following bug should allow us to remove this.
  7970. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7971. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7972. }
  7973. this.restore();
  7974. },
  7975. // Images
  7976. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7977. error('Should not call beginInlineImage');
  7978. },
  7979. beginImageData: function CanvasGraphics_beginImageData() {
  7980. error('Should not call beginImageData');
  7981. },
  7982. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  7983. this.save();
  7984. this.baseTransformStack.push(this.baseTransform);
  7985. if (isArray(matrix) && 6 === matrix.length) {
  7986. this.transform.apply(this, matrix);
  7987. }
  7988. this.baseTransform = this.ctx.mozCurrentTransform;
  7989. if (isArray(bbox) && 4 === bbox.length) {
  7990. var width = bbox[2] - bbox[0];
  7991. var height = bbox[3] - bbox[1];
  7992. this.ctx.rect(bbox[0], bbox[1], width, height);
  7993. this.clip();
  7994. this.endPath();
  7995. }
  7996. },
  7997. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7998. this.restore();
  7999. this.baseTransform = this.baseTransformStack.pop();
  8000. },
  8001. beginGroup: function CanvasGraphics_beginGroup(group) {
  8002. this.save();
  8003. var currentCtx = this.ctx;
  8004. // TODO non-isolated groups - according to Rik at adobe non-isolated
  8005. // group results aren't usually that different and they even have tools
  8006. // that ignore this setting. Notes from Rik on implementing:
  8007. // - When you encounter an transparency group, create a new canvas with
  8008. // the dimensions of the bbox
  8009. // - copy the content from the previous canvas to the new canvas
  8010. // - draw as usual
  8011. // - remove the backdrop alpha:
  8012. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  8013. // value of your transparency group and 'alphaBackdrop' the alpha of the
  8014. // backdrop
  8015. // - remove background color:
  8016. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  8017. if (!group.isolated) {
  8018. info('TODO: Support non-isolated groups.');
  8019. }
  8020. // TODO knockout - supposedly possible with the clever use of compositing
  8021. // modes.
  8022. if (group.knockout) {
  8023. warn('Knockout groups not supported.');
  8024. }
  8025. var currentTransform = currentCtx.mozCurrentTransform;
  8026. if (group.matrix) {
  8027. currentCtx.transform.apply(currentCtx, group.matrix);
  8028. }
  8029. assert(group.bbox, 'Bounding box is required.');
  8030. // Based on the current transform figure out how big the bounding box
  8031. // will actually be.
  8032. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  8033. // Clip the bounding box to the current canvas.
  8034. var canvasBounds = [
  8035. 0,
  8036. 0,
  8037. currentCtx.canvas.width,
  8038. currentCtx.canvas.height
  8039. ];
  8040. bounds = Util.intersect(bounds, canvasBounds) || [
  8041. 0,
  8042. 0,
  8043. 0,
  8044. 0
  8045. ];
  8046. // Use ceil in case we're between sizes so we don't create canvas that is
  8047. // too small and make the canvas at least 1x1 pixels.
  8048. var offsetX = Math.floor(bounds[0]);
  8049. var offsetY = Math.floor(bounds[1]);
  8050. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8051. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8052. var scaleX = 1, scaleY = 1;
  8053. if (drawnWidth > MAX_GROUP_SIZE) {
  8054. scaleX = drawnWidth / MAX_GROUP_SIZE;
  8055. drawnWidth = MAX_GROUP_SIZE;
  8056. }
  8057. if (drawnHeight > MAX_GROUP_SIZE) {
  8058. scaleY = drawnHeight / MAX_GROUP_SIZE;
  8059. drawnHeight = MAX_GROUP_SIZE;
  8060. }
  8061. var cacheId = 'groupAt' + this.groupLevel;
  8062. if (group.smask) {
  8063. // Using two cache entries is case if masks are used one after another.
  8064. cacheId += '_smask_' + this.smaskCounter++ % 2;
  8065. }
  8066. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  8067. var groupCtx = scratchCanvas.context;
  8068. // Since we created a new canvas that is just the size of the bounding box
  8069. // we have to translate the group ctx.
  8070. groupCtx.scale(1 / scaleX, 1 / scaleY);
  8071. groupCtx.translate(-offsetX, -offsetY);
  8072. groupCtx.transform.apply(groupCtx, currentTransform);
  8073. if (group.smask) {
  8074. // Saving state and cached mask to be used in setGState.
  8075. this.smaskStack.push({
  8076. canvas: scratchCanvas.canvas,
  8077. context: groupCtx,
  8078. offsetX: offsetX,
  8079. offsetY: offsetY,
  8080. scaleX: scaleX,
  8081. scaleY: scaleY,
  8082. subtype: group.smask.subtype,
  8083. backdrop: group.smask.backdrop,
  8084. transferMap: group.smask.transferMap || null,
  8085. startTransformInverse: null
  8086. });
  8087. } else
  8088. // used during suspend operation
  8089. {
  8090. // Setup the current ctx so when the group is popped we draw it at the
  8091. // right location.
  8092. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8093. currentCtx.translate(offsetX, offsetY);
  8094. currentCtx.scale(scaleX, scaleY);
  8095. }
  8096. // The transparency group inherits all off the current graphics state
  8097. // except the blend mode, soft mask, and alpha constants.
  8098. copyCtxState(currentCtx, groupCtx);
  8099. this.ctx = groupCtx;
  8100. this.setGState([
  8101. [
  8102. 'BM',
  8103. 'Normal'
  8104. ],
  8105. [
  8106. 'ca',
  8107. 1
  8108. ],
  8109. [
  8110. 'CA',
  8111. 1
  8112. ]
  8113. ]);
  8114. this.groupStack.push(currentCtx);
  8115. this.groupLevel++;
  8116. // Reseting mask state, masks will be applied on restore of the group.
  8117. this.current.activeSMask = null;
  8118. },
  8119. endGroup: function CanvasGraphics_endGroup(group) {
  8120. this.groupLevel--;
  8121. var groupCtx = this.ctx;
  8122. this.ctx = this.groupStack.pop();
  8123. // Turn off image smoothing to avoid sub pixel interpolation which can
  8124. // look kind of blurry for some pdfs.
  8125. if (this.ctx.imageSmoothingEnabled !== undefined) {
  8126. this.ctx.imageSmoothingEnabled = false;
  8127. } else {
  8128. this.ctx.mozImageSmoothingEnabled = false;
  8129. }
  8130. if (group.smask) {
  8131. this.tempSMask = this.smaskStack.pop();
  8132. } else {
  8133. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8134. }
  8135. this.restore();
  8136. },
  8137. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  8138. this.save();
  8139. this.current = new CanvasExtraState();
  8140. if (this.baseTransform) {
  8141. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  8142. }
  8143. },
  8144. endAnnotations: function CanvasGraphics_endAnnotations() {
  8145. this.restore();
  8146. },
  8147. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  8148. this.save();
  8149. if (isArray(rect) && 4 === rect.length) {
  8150. var width = rect[2] - rect[0];
  8151. var height = rect[3] - rect[1];
  8152. this.ctx.rect(rect[0], rect[1], width, height);
  8153. this.clip();
  8154. this.endPath();
  8155. }
  8156. this.transform.apply(this, transform);
  8157. this.transform.apply(this, matrix);
  8158. },
  8159. endAnnotation: function CanvasGraphics_endAnnotation() {
  8160. this.restore();
  8161. },
  8162. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  8163. var domImage = this.objs.get(objId);
  8164. if (!domImage) {
  8165. warn('Dependent image isn\'t ready yet');
  8166. return;
  8167. }
  8168. this.save();
  8169. var ctx = this.ctx;
  8170. // scale the image to the unit square
  8171. ctx.scale(1 / w, -1 / h);
  8172. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  8173. if (this.imageLayer) {
  8174. var currentTransform = ctx.mozCurrentTransformInverse;
  8175. var position = this.getCanvasPosition(0, 0);
  8176. this.imageLayer.appendImage({
  8177. objId: objId,
  8178. left: position[0],
  8179. top: position[1],
  8180. width: w / currentTransform[0],
  8181. height: h / currentTransform[3]
  8182. });
  8183. }
  8184. this.restore();
  8185. },
  8186. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  8187. var ctx = this.ctx;
  8188. var width = img.width, height = img.height;
  8189. var fillColor = this.current.fillColor;
  8190. var isPatternFill = this.current.patternFill;
  8191. var glyph = this.processingType3;
  8192. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  8193. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  8194. glyph.compiled = compileType3Glyph({
  8195. data: img.data,
  8196. width: width,
  8197. height: height
  8198. });
  8199. } else {
  8200. glyph.compiled = null;
  8201. }
  8202. }
  8203. if (glyph && glyph.compiled) {
  8204. glyph.compiled(ctx);
  8205. return;
  8206. }
  8207. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8208. var maskCtx = maskCanvas.context;
  8209. maskCtx.save();
  8210. putBinaryImageMask(maskCtx, img);
  8211. maskCtx.globalCompositeOperation = 'source-in';
  8212. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8213. maskCtx.fillRect(0, 0, width, height);
  8214. maskCtx.restore();
  8215. this.paintInlineImageXObject(maskCanvas.canvas);
  8216. },
  8217. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  8218. var width = imgData.width;
  8219. var height = imgData.height;
  8220. var fillColor = this.current.fillColor;
  8221. var isPatternFill = this.current.patternFill;
  8222. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8223. var maskCtx = maskCanvas.context;
  8224. maskCtx.save();
  8225. putBinaryImageMask(maskCtx, imgData);
  8226. maskCtx.globalCompositeOperation = 'source-in';
  8227. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8228. maskCtx.fillRect(0, 0, width, height);
  8229. maskCtx.restore();
  8230. var ctx = this.ctx;
  8231. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8232. ctx.save();
  8233. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  8234. ctx.scale(1, -1);
  8235. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8236. ctx.restore();
  8237. }
  8238. },
  8239. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  8240. var ctx = this.ctx;
  8241. var fillColor = this.current.fillColor;
  8242. var isPatternFill = this.current.patternFill;
  8243. for (var i = 0, ii = images.length; i < ii; i++) {
  8244. var image = images[i];
  8245. var width = image.width, height = image.height;
  8246. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8247. var maskCtx = maskCanvas.context;
  8248. maskCtx.save();
  8249. putBinaryImageMask(maskCtx, image);
  8250. maskCtx.globalCompositeOperation = 'source-in';
  8251. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8252. maskCtx.fillRect(0, 0, width, height);
  8253. maskCtx.restore();
  8254. ctx.save();
  8255. ctx.transform.apply(ctx, image.transform);
  8256. ctx.scale(1, -1);
  8257. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8258. ctx.restore();
  8259. }
  8260. },
  8261. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  8262. var imgData = this.objs.get(objId);
  8263. if (!imgData) {
  8264. warn('Dependent image isn\'t ready yet');
  8265. return;
  8266. }
  8267. this.paintInlineImageXObject(imgData);
  8268. },
  8269. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8270. var imgData = this.objs.get(objId);
  8271. if (!imgData) {
  8272. warn('Dependent image isn\'t ready yet');
  8273. return;
  8274. }
  8275. var width = imgData.width;
  8276. var height = imgData.height;
  8277. var map = [];
  8278. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8279. map.push({
  8280. transform: [
  8281. scaleX,
  8282. 0,
  8283. 0,
  8284. scaleY,
  8285. positions[i],
  8286. positions[i + 1]
  8287. ],
  8288. x: 0,
  8289. y: 0,
  8290. w: width,
  8291. h: height
  8292. });
  8293. }
  8294. this.paintInlineImageXObjectGroup(imgData, map);
  8295. },
  8296. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  8297. var width = imgData.width;
  8298. var height = imgData.height;
  8299. var ctx = this.ctx;
  8300. this.save();
  8301. // scale the image to the unit square
  8302. ctx.scale(1 / width, -1 / height);
  8303. var currentTransform = ctx.mozCurrentTransformInverse;
  8304. var a = currentTransform[0], b = currentTransform[1];
  8305. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8306. var c = currentTransform[2], d = currentTransform[3];
  8307. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8308. var imgToPaint, tmpCanvas;
  8309. // instanceof HTMLElement does not work in jsdom node.js module
  8310. if (imgData instanceof HTMLElement || !imgData.data) {
  8311. imgToPaint = imgData;
  8312. } else {
  8313. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  8314. var tmpCtx = tmpCanvas.context;
  8315. putBinaryImageData(tmpCtx, imgData);
  8316. imgToPaint = tmpCanvas.canvas;
  8317. }
  8318. var paintWidth = width, paintHeight = height;
  8319. var tmpCanvasId = 'prescale1';
  8320. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8321. // pixels during drawImage operation, painting on the temporary canvas(es)
  8322. // that are twice smaller in size
  8323. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  8324. var newWidth = paintWidth, newHeight = paintHeight;
  8325. if (widthScale > 2 && paintWidth > 1) {
  8326. newWidth = Math.ceil(paintWidth / 2);
  8327. widthScale /= paintWidth / newWidth;
  8328. }
  8329. if (heightScale > 2 && paintHeight > 1) {
  8330. newHeight = Math.ceil(paintHeight / 2);
  8331. heightScale /= paintHeight / newHeight;
  8332. }
  8333. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  8334. tmpCtx = tmpCanvas.context;
  8335. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8336. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  8337. imgToPaint = tmpCanvas.canvas;
  8338. paintWidth = newWidth;
  8339. paintHeight = newHeight;
  8340. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8341. }
  8342. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  8343. if (this.imageLayer) {
  8344. var position = this.getCanvasPosition(0, -height);
  8345. this.imageLayer.appendImage({
  8346. imgData: imgData,
  8347. left: position[0],
  8348. top: position[1],
  8349. width: width / currentTransform[0],
  8350. height: height / currentTransform[3]
  8351. });
  8352. }
  8353. this.restore();
  8354. },
  8355. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8356. var ctx = this.ctx;
  8357. var w = imgData.width;
  8358. var h = imgData.height;
  8359. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8360. var tmpCtx = tmpCanvas.context;
  8361. putBinaryImageData(tmpCtx, imgData);
  8362. for (var i = 0, ii = map.length; i < ii; i++) {
  8363. var entry = map[i];
  8364. ctx.save();
  8365. ctx.transform.apply(ctx, entry.transform);
  8366. ctx.scale(1, -1);
  8367. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8368. if (this.imageLayer) {
  8369. var position = this.getCanvasPosition(entry.x, entry.y);
  8370. this.imageLayer.appendImage({
  8371. imgData: imgData,
  8372. left: position[0],
  8373. top: position[1],
  8374. width: w,
  8375. height: h
  8376. });
  8377. }
  8378. ctx.restore();
  8379. }
  8380. },
  8381. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  8382. this.ctx.fillRect(0, 0, 1, 1);
  8383. },
  8384. paintXObject: function CanvasGraphics_paintXObject() {
  8385. warn('Unsupported \'paintXObject\' command.');
  8386. },
  8387. // Marked content
  8388. markPoint: function CanvasGraphics_markPoint(tag) {
  8389. },
  8390. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8391. },
  8392. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8393. },
  8394. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  8395. },
  8396. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8397. },
  8398. // Compatibility
  8399. beginCompat: function CanvasGraphics_beginCompat() {
  8400. },
  8401. endCompat: function CanvasGraphics_endCompat() {
  8402. },
  8403. // Helper functions
  8404. consumePath: function CanvasGraphics_consumePath() {
  8405. var ctx = this.ctx;
  8406. if (this.pendingClip) {
  8407. if (this.pendingClip === EO_CLIP) {
  8408. if (ctx.mozFillRule !== undefined) {
  8409. ctx.mozFillRule = 'evenodd';
  8410. ctx.clip();
  8411. ctx.mozFillRule = 'nonzero';
  8412. } else {
  8413. ctx.clip('evenodd');
  8414. }
  8415. } else {
  8416. ctx.clip();
  8417. }
  8418. this.pendingClip = null;
  8419. }
  8420. ctx.beginPath();
  8421. },
  8422. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8423. if (this.cachedGetSinglePixelWidth === null) {
  8424. // NOTE: The `save` and `restore` commands used below is a workaround
  8425. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8426. // from intermittently returning incorrect values in Firefox, see:
  8427. // https://github.com/mozilla/pdf.js/issues/7188.
  8428. this.ctx.save();
  8429. var inverse = this.ctx.mozCurrentTransformInverse;
  8430. this.ctx.restore();
  8431. // max of the current horizontal and vertical scale
  8432. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  8433. }
  8434. return this.cachedGetSinglePixelWidth;
  8435. },
  8436. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8437. var transform = this.ctx.mozCurrentTransform;
  8438. return [
  8439. transform[0] * x + transform[2] * y + transform[4],
  8440. transform[1] * x + transform[3] * y + transform[5]
  8441. ];
  8442. }
  8443. };
  8444. for (var op in OPS) {
  8445. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8446. }
  8447. return CanvasGraphics;
  8448. }();
  8449. exports.CanvasGraphics = CanvasGraphics;
  8450. exports.createScratchCanvas = createScratchCanvas;
  8451. }));
  8452. (function (root, factory) {
  8453. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8454. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  8455. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8456. var MessageHandler = sharedUtil.MessageHandler;
  8457. var MissingPDFException = sharedUtil.MissingPDFException;
  8458. var PageViewport = sharedUtil.PageViewport;
  8459. var PasswordResponses = sharedUtil.PasswordResponses;
  8460. var PasswordException = sharedUtil.PasswordException;
  8461. var StatTimer = sharedUtil.StatTimer;
  8462. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8463. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8464. var Util = sharedUtil.Util;
  8465. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8466. var error = sharedUtil.error;
  8467. var deprecated = sharedUtil.deprecated;
  8468. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8469. var info = sharedUtil.info;
  8470. var isInt = sharedUtil.isInt;
  8471. var isArray = sharedUtil.isArray;
  8472. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8473. var isSameOrigin = sharedUtil.isSameOrigin;
  8474. var loadJpegStream = sharedUtil.loadJpegStream;
  8475. var stringToBytes = sharedUtil.stringToBytes;
  8476. var globalScope = sharedUtil.globalScope;
  8477. var warn = sharedUtil.warn;
  8478. var FontFaceObject = displayFontLoader.FontFaceObject;
  8479. var FontLoader = displayFontLoader.FontLoader;
  8480. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8481. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8482. var Metadata = displayMetadata.Metadata;
  8483. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8484. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  8485. // 2^16 = 65536
  8486. var isWorkerDisabled = false;
  8487. var workerSrc;
  8488. var isPostMessageTransfersDisabled = false;
  8489. var fakeWorkerFilesLoader = null;
  8490. var useRequireEnsure = false;
  8491. // For GENERIC build we need add support of different fake file loaders
  8492. // for different frameworks.
  8493. if (typeof window === 'undefined') {
  8494. // node.js - disable worker and set require.ensure.
  8495. isWorkerDisabled = true;
  8496. if (typeof require.ensure === 'undefined') {
  8497. require.ensure = require('node-ensure');
  8498. }
  8499. useRequireEnsure = true;
  8500. }
  8501. if (typeof __webpack_require__ !== 'undefined') {
  8502. useRequireEnsure = true;
  8503. }
  8504. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8505. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8506. }
  8507. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8508. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  8509. require.ensure([], function () {
  8510. var worker = require('./pdf.worker.js');
  8511. callback(worker.WorkerMessageHandler);
  8512. });
  8513. } : dynamicLoaderSupported ? function (callback) {
  8514. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8515. callback(worker.WorkerMessageHandler);
  8516. });
  8517. } : null;
  8518. /**
  8519. * Document initialization / loading parameters object.
  8520. *
  8521. * @typedef {Object} DocumentInitParameters
  8522. * @property {string} url - The URL of the PDF.
  8523. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8524. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8525. * use atob() to convert it to a binary string first.
  8526. * @property {Object} httpHeaders - Basic authentication headers.
  8527. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8528. * Access-Control requests should be made using credentials such as cookies
  8529. * or authorization headers. The default is false.
  8530. * @property {string} password - For decrypting password-protected PDFs.
  8531. * @property {TypedArray} initialData - A typed array with the first portion or
  8532. * all of the pdf data. Used by the extension since some data is already
  8533. * loaded before the switch to range requests.
  8534. * @property {number} length - The PDF file length. It's used for progress
  8535. * reports and range requests operations.
  8536. * @property {PDFDataRangeTransport} range
  8537. * @property {number} rangeChunkSize - Optional parameter to specify
  8538. * maximum number of bytes fetched per range request. The default value is
  8539. * 2^16 = 65536.
  8540. * @property {PDFWorker} worker - The worker that will be used for the loading
  8541. * and parsing of the PDF data.
  8542. */
  8543. /**
  8544. * @typedef {Object} PDFDocumentStats
  8545. * @property {Array} streamTypes - Used stream types in the document (an item
  8546. * is set to true if specific stream ID was used in the document).
  8547. * @property {Array} fontTypes - Used font type in the document (an item is set
  8548. * to true if specific font ID was used in the document).
  8549. */
  8550. /**
  8551. * This is the main entry point for loading a PDF and interacting with it.
  8552. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8553. * is used, which means it must follow the same origin rules that any XHR does
  8554. * e.g. No cross domain requests without CORS.
  8555. *
  8556. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8557. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8558. * already populated with data or parameter object.
  8559. *
  8560. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8561. * if you want to manually serve range requests for data in the PDF.
  8562. *
  8563. * @param {function} passwordCallback (deprecated) It is used to request a
  8564. * password if wrong or no password was provided. The callback receives two
  8565. * parameters: function that needs to be called with new password and reason
  8566. * (see {PasswordResponses}).
  8567. *
  8568. * @param {function} progressCallback (deprecated) It is used to be able to
  8569. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8570. * a loading bar). The callback receives an {Object} with the properties:
  8571. * {number} loaded and {number} total.
  8572. *
  8573. * @return {PDFDocumentLoadingTask}
  8574. */
  8575. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  8576. var task = new PDFDocumentLoadingTask();
  8577. // Support of the obsolete arguments (for compatibility with API v1.0)
  8578. if (arguments.length > 1) {
  8579. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  8580. }
  8581. if (pdfDataRangeTransport) {
  8582. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8583. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8584. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8585. pdfDataRangeTransport.length = src.length;
  8586. pdfDataRangeTransport.initialData = src.initialData;
  8587. if (!pdfDataRangeTransport.abort) {
  8588. pdfDataRangeTransport.abort = function () {
  8589. };
  8590. }
  8591. }
  8592. src = Object.create(src);
  8593. src.range = pdfDataRangeTransport;
  8594. }
  8595. task.onPassword = passwordCallback || null;
  8596. task.onProgress = progressCallback || null;
  8597. var source;
  8598. if (typeof src === 'string') {
  8599. source = { url: src };
  8600. } else if (isArrayBuffer(src)) {
  8601. source = { data: src };
  8602. } else if (src instanceof PDFDataRangeTransport) {
  8603. source = { range: src };
  8604. } else {
  8605. if (typeof src !== 'object') {
  8606. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  8607. }
  8608. if (!src.url && !src.data && !src.range) {
  8609. error('Invalid parameter object: need either .data, .range or .url');
  8610. }
  8611. source = src;
  8612. }
  8613. var params = {};
  8614. var rangeTransport = null;
  8615. var worker = null;
  8616. for (var key in source) {
  8617. if (key === 'url' && typeof window !== 'undefined') {
  8618. // The full path is required in the 'url' field.
  8619. params[key] = new URL(source[key], window.location).href;
  8620. continue;
  8621. } else if (key === 'range') {
  8622. rangeTransport = source[key];
  8623. continue;
  8624. } else if (key === 'worker') {
  8625. worker = source[key];
  8626. continue;
  8627. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8628. // Converting string or array-like data to Uint8Array.
  8629. var pdfBytes = source[key];
  8630. if (typeof pdfBytes === 'string') {
  8631. params[key] = stringToBytes(pdfBytes);
  8632. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  8633. params[key] = new Uint8Array(pdfBytes);
  8634. } else if (isArrayBuffer(pdfBytes)) {
  8635. params[key] = new Uint8Array(pdfBytes);
  8636. } else {
  8637. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  8638. }
  8639. continue;
  8640. }
  8641. params[key] = source[key];
  8642. }
  8643. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8644. if (!worker) {
  8645. // Worker was not provided -- creating and owning our own.
  8646. worker = new PDFWorker();
  8647. task._worker = worker;
  8648. }
  8649. var docId = task.docId;
  8650. worker.promise.then(function () {
  8651. if (task.destroyed) {
  8652. throw new Error('Loading aborted');
  8653. }
  8654. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  8655. if (task.destroyed) {
  8656. throw new Error('Loading aborted');
  8657. }
  8658. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8659. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8660. task._transport = transport;
  8661. messageHandler.send('Ready', null);
  8662. });
  8663. }).catch(task._capability.reject);
  8664. return task;
  8665. }
  8666. /**
  8667. * Starts fetching of specified PDF document/data.
  8668. * @param {PDFWorker} worker
  8669. * @param {Object} source
  8670. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8671. * @param {string} docId Unique document id, used as MessageHandler id.
  8672. * @returns {Promise} The promise, which is resolved when worker id of
  8673. * MessageHandler is known.
  8674. * @private
  8675. */
  8676. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8677. if (worker.destroyed) {
  8678. return Promise.reject(new Error('Worker was destroyed'));
  8679. }
  8680. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8681. source.disableStream = getDefaultSetting('disableStream');
  8682. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8683. if (pdfDataRangeTransport) {
  8684. source.length = pdfDataRangeTransport.length;
  8685. source.initialData = pdfDataRangeTransport.initialData;
  8686. }
  8687. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8688. docId: docId,
  8689. source: source,
  8690. disableRange: getDefaultSetting('disableRange'),
  8691. maxImageSize: getDefaultSetting('maxImageSize'),
  8692. cMapUrl: getDefaultSetting('cMapUrl'),
  8693. cMapPacked: getDefaultSetting('cMapPacked'),
  8694. disableFontFace: getDefaultSetting('disableFontFace'),
  8695. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8696. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled
  8697. }).then(function (workerId) {
  8698. if (worker.destroyed) {
  8699. throw new Error('Worker was destroyed');
  8700. }
  8701. return workerId;
  8702. });
  8703. }
  8704. /**
  8705. * PDF document loading operation.
  8706. * @class
  8707. * @alias PDFDocumentLoadingTask
  8708. */
  8709. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  8710. var nextDocumentId = 0;
  8711. /** @constructs PDFDocumentLoadingTask */
  8712. function PDFDocumentLoadingTask() {
  8713. this._capability = createPromiseCapability();
  8714. this._transport = null;
  8715. this._worker = null;
  8716. /**
  8717. * Unique document loading task id -- used in MessageHandlers.
  8718. * @type {string}
  8719. */
  8720. this.docId = 'd' + nextDocumentId++;
  8721. /**
  8722. * Shows if loading task is destroyed.
  8723. * @type {boolean}
  8724. */
  8725. this.destroyed = false;
  8726. /**
  8727. * Callback to request a password if wrong or no password was provided.
  8728. * The callback receives two parameters: function that needs to be called
  8729. * with new password and reason (see {PasswordResponses}).
  8730. */
  8731. this.onPassword = null;
  8732. /**
  8733. * Callback to be able to monitor the loading progress of the PDF file
  8734. * (necessary to implement e.g. a loading bar). The callback receives
  8735. * an {Object} with the properties: {number} loaded and {number} total.
  8736. */
  8737. this.onProgress = null;
  8738. /**
  8739. * Callback to when unsupported feature is used. The callback receives
  8740. * an {UNSUPPORTED_FEATURES} argument.
  8741. */
  8742. this.onUnsupportedFeature = null;
  8743. }
  8744. PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */
  8745. {
  8746. /**
  8747. * @return {Promise}
  8748. */
  8749. get promise() {
  8750. return this._capability.promise;
  8751. },
  8752. /**
  8753. * Aborts all network requests and destroys worker.
  8754. * @return {Promise} A promise that is resolved after destruction activity
  8755. * is completed.
  8756. */
  8757. destroy: function () {
  8758. this.destroyed = true;
  8759. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  8760. return transportDestroyed.then(function () {
  8761. this._transport = null;
  8762. if (this._worker) {
  8763. this._worker.destroy();
  8764. this._worker = null;
  8765. }
  8766. }.bind(this));
  8767. },
  8768. /**
  8769. * Registers callbacks to indicate the document loading completion.
  8770. *
  8771. * @param {function} onFulfilled The callback for the loading completion.
  8772. * @param {function} onRejected The callback for the loading failure.
  8773. * @return {Promise} A promise that is resolved after the onFulfilled or
  8774. * onRejected callback.
  8775. */
  8776. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8777. return this.promise.then.apply(this.promise, arguments);
  8778. }
  8779. };
  8780. return PDFDocumentLoadingTask;
  8781. }();
  8782. /**
  8783. * Abstract class to support range requests file loading.
  8784. * @class
  8785. * @alias PDFDataRangeTransport
  8786. * @param {number} length
  8787. * @param {Uint8Array} initialData
  8788. */
  8789. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  8790. function PDFDataRangeTransport(length, initialData) {
  8791. this.length = length;
  8792. this.initialData = initialData;
  8793. this._rangeListeners = [];
  8794. this._progressListeners = [];
  8795. this._progressiveReadListeners = [];
  8796. this._readyCapability = createPromiseCapability();
  8797. }
  8798. PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */
  8799. {
  8800. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  8801. this._rangeListeners.push(listener);
  8802. },
  8803. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  8804. this._progressListeners.push(listener);
  8805. },
  8806. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8807. this._progressiveReadListeners.push(listener);
  8808. },
  8809. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8810. var listeners = this._rangeListeners;
  8811. for (var i = 0, n = listeners.length; i < n; ++i) {
  8812. listeners[i](begin, chunk);
  8813. }
  8814. },
  8815. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8816. this._readyCapability.promise.then(function () {
  8817. var listeners = this._progressListeners;
  8818. for (var i = 0, n = listeners.length; i < n; ++i) {
  8819. listeners[i](loaded);
  8820. }
  8821. }.bind(this));
  8822. },
  8823. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  8824. this._readyCapability.promise.then(function () {
  8825. var listeners = this._progressiveReadListeners;
  8826. for (var i = 0, n = listeners.length; i < n; ++i) {
  8827. listeners[i](chunk);
  8828. }
  8829. }.bind(this));
  8830. },
  8831. transportReady: function PDFDataRangeTransport_transportReady() {
  8832. this._readyCapability.resolve();
  8833. },
  8834. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  8835. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8836. },
  8837. abort: function PDFDataRangeTransport_abort() {
  8838. }
  8839. };
  8840. return PDFDataRangeTransport;
  8841. }();
  8842. /**
  8843. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8844. * properties that can be read synchronously.
  8845. * @class
  8846. * @alias PDFDocumentProxy
  8847. */
  8848. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  8849. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8850. this.pdfInfo = pdfInfo;
  8851. this.transport = transport;
  8852. this.loadingTask = loadingTask;
  8853. }
  8854. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */
  8855. {
  8856. /**
  8857. * @return {number} Total number of pages the PDF contains.
  8858. */
  8859. get numPages() {
  8860. return this.pdfInfo.numPages;
  8861. },
  8862. /**
  8863. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8864. * unique.
  8865. */
  8866. get fingerprint() {
  8867. return this.pdfInfo.fingerprint;
  8868. },
  8869. /**
  8870. * @param {number} pageNumber The page number to get. The first page is 1.
  8871. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8872. * object.
  8873. */
  8874. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8875. return this.transport.getPage(pageNumber);
  8876. },
  8877. /**
  8878. * @param {{num: number, gen: number}} ref The page reference. Must have
  8879. * the 'num' and 'gen' properties.
  8880. * @return {Promise} A promise that is resolved with the page index that is
  8881. * associated with the reference.
  8882. */
  8883. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8884. return this.transport.getPageIndex(ref);
  8885. },
  8886. /**
  8887. * @return {Promise} A promise that is resolved with a lookup table for
  8888. * mapping named destinations to reference numbers.
  8889. *
  8890. * This can be slow for large documents: use getDestination instead
  8891. */
  8892. getDestinations: function PDFDocumentProxy_getDestinations() {
  8893. return this.transport.getDestinations();
  8894. },
  8895. /**
  8896. * @param {string} id The named destination to get.
  8897. * @return {Promise} A promise that is resolved with all information
  8898. * of the given named destination.
  8899. */
  8900. getDestination: function PDFDocumentProxy_getDestination(id) {
  8901. return this.transport.getDestination(id);
  8902. },
  8903. /**
  8904. * @return {Promise} A promise that is resolved with:
  8905. * an Array containing the pageLabels that correspond to the pageIndexes,
  8906. * or `null` when no pageLabels are present in the PDF file.
  8907. */
  8908. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8909. return this.transport.getPageLabels();
  8910. },
  8911. /**
  8912. * @return {Promise} A promise that is resolved with a lookup table for
  8913. * mapping named attachments to their content.
  8914. */
  8915. getAttachments: function PDFDocumentProxy_getAttachments() {
  8916. return this.transport.getAttachments();
  8917. },
  8918. /**
  8919. * @return {Promise} A promise that is resolved with an array of all the
  8920. * JavaScript strings in the name tree.
  8921. */
  8922. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8923. return this.transport.getJavaScript();
  8924. },
  8925. /**
  8926. * @return {Promise} A promise that is resolved with an {Array} that is a
  8927. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8928. * [
  8929. * {
  8930. * title: string,
  8931. * bold: boolean,
  8932. * italic: boolean,
  8933. * color: rgb Uint8Array,
  8934. * dest: dest obj,
  8935. * url: string,
  8936. * items: array of more items like this
  8937. * },
  8938. * ...
  8939. * ].
  8940. */
  8941. getOutline: function PDFDocumentProxy_getOutline() {
  8942. return this.transport.getOutline();
  8943. },
  8944. /**
  8945. * @return {Promise} A promise that is resolved with an {Object} that has
  8946. * info and metadata properties. Info is an {Object} filled with anything
  8947. * available in the information dictionary and similarly metadata is a
  8948. * {Metadata} object with information from the metadata section of the PDF.
  8949. */
  8950. getMetadata: function PDFDocumentProxy_getMetadata() {
  8951. return this.transport.getMetadata();
  8952. },
  8953. /**
  8954. * @return {Promise} A promise that is resolved with a TypedArray that has
  8955. * the raw data from the PDF.
  8956. */
  8957. getData: function PDFDocumentProxy_getData() {
  8958. return this.transport.getData();
  8959. },
  8960. /**
  8961. * @return {Promise} A promise that is resolved when the document's data
  8962. * is loaded. It is resolved with an {Object} that contains the length
  8963. * property that indicates size of the PDF data in bytes.
  8964. */
  8965. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8966. return this.transport.downloadInfoCapability.promise;
  8967. },
  8968. /**
  8969. * @return {Promise} A promise this is resolved with current stats about
  8970. * document structures (see {@link PDFDocumentStats}).
  8971. */
  8972. getStats: function PDFDocumentProxy_getStats() {
  8973. return this.transport.getStats();
  8974. },
  8975. /**
  8976. * Cleans up resources allocated by the document, e.g. created @font-face.
  8977. */
  8978. cleanup: function PDFDocumentProxy_cleanup() {
  8979. this.transport.startCleanup();
  8980. },
  8981. /**
  8982. * Destroys current document instance and terminates worker.
  8983. */
  8984. destroy: function PDFDocumentProxy_destroy() {
  8985. return this.loadingTask.destroy();
  8986. }
  8987. };
  8988. return PDFDocumentProxy;
  8989. }();
  8990. /**
  8991. * Page getTextContent parameters.
  8992. *
  8993. * @typedef {Object} getTextContentParameters
  8994. * @property {boolean} normalizeWhitespace - replaces all occurrences of
  8995. * whitespace with standard spaces (0x20). The default value is `false`.
  8996. * @property {boolean} disableCombineTextItems - do not attempt to combine
  8997. * same line {@link TextItem}'s. The default value is `false`.
  8998. */
  8999. /**
  9000. * Page text content.
  9001. *
  9002. * @typedef {Object} TextContent
  9003. * @property {array} items - array of {@link TextItem}
  9004. * @property {Object} styles - {@link TextStyles} objects, indexed by font name.
  9005. */
  9006. /**
  9007. * Page text content part.
  9008. *
  9009. * @typedef {Object} TextItem
  9010. * @property {string} str - text content.
  9011. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  9012. * @property {array} transform - transformation matrix.
  9013. * @property {number} width - width in device space.
  9014. * @property {number} height - height in device space.
  9015. * @property {string} fontName - font name used by pdf.js for converted font.
  9016. */
  9017. /**
  9018. * Text style.
  9019. *
  9020. * @typedef {Object} TextStyle
  9021. * @property {number} ascent - font ascent.
  9022. * @property {number} descent - font descent.
  9023. * @property {boolean} vertical - text is in vertical mode.
  9024. * @property {string} fontFamily - possible font family
  9025. */
  9026. /**
  9027. * Page annotation parameters.
  9028. *
  9029. * @typedef {Object} GetAnnotationsParameters
  9030. * @property {string} intent - Determines the annotations that will be fetched,
  9031. * can be either 'display' (viewable annotations) or 'print'
  9032. * (printable annotations).
  9033. * If the parameter is omitted, all annotations are fetched.
  9034. */
  9035. /**
  9036. * Page render parameters.
  9037. *
  9038. * @typedef {Object} RenderParameters
  9039. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  9040. * @property {PageViewport} viewport - Rendering viewport obtained by
  9041. * calling of PDFPage.getViewport method.
  9042. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  9043. * (default value is 'display').
  9044. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  9045. * interactive form elements are rendered in the display
  9046. * layer. If so, we do not render them on canvas as well.
  9047. * @property {Array} transform - (optional) Additional transform, applied
  9048. * just before viewport transform.
  9049. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  9050. * endLayout and appendImage functions.
  9051. * @property {function} continueCallback - (deprecated) A function that will be
  9052. * called each time the rendering is paused. To continue
  9053. * rendering call the function that is the first argument
  9054. * to the callback.
  9055. */
  9056. /**
  9057. * PDF page operator list.
  9058. *
  9059. * @typedef {Object} PDFOperatorList
  9060. * @property {Array} fnArray - Array containing the operator functions.
  9061. * @property {Array} argsArray - Array containing the arguments of the
  9062. * functions.
  9063. */
  9064. /**
  9065. * Proxy to a PDFPage in the worker thread.
  9066. * @class
  9067. * @alias PDFPageProxy
  9068. */
  9069. var PDFPageProxy = function PDFPageProxyClosure() {
  9070. function PDFPageProxy(pageIndex, pageInfo, transport) {
  9071. this.pageIndex = pageIndex;
  9072. this.pageInfo = pageInfo;
  9073. this.transport = transport;
  9074. this.stats = new StatTimer();
  9075. this.stats.enabled = getDefaultSetting('enableStats');
  9076. this.commonObjs = transport.commonObjs;
  9077. this.objs = new PDFObjects();
  9078. this.cleanupAfterRender = false;
  9079. this.pendingCleanup = false;
  9080. this.intentStates = Object.create(null);
  9081. this.destroyed = false;
  9082. }
  9083. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */
  9084. {
  9085. /**
  9086. * @return {number} Page number of the page. First page is 1.
  9087. */
  9088. get pageNumber() {
  9089. return this.pageIndex + 1;
  9090. },
  9091. /**
  9092. * @return {number} The number of degrees the page is rotated clockwise.
  9093. */
  9094. get rotate() {
  9095. return this.pageInfo.rotate;
  9096. },
  9097. /**
  9098. * @return {Object} The reference that points to this page. It has 'num' and
  9099. * 'gen' properties.
  9100. */
  9101. get ref() {
  9102. return this.pageInfo.ref;
  9103. },
  9104. /**
  9105. * @return {Array} An array of the visible portion of the PDF page in the
  9106. * user space units - [x1, y1, x2, y2].
  9107. */
  9108. get view() {
  9109. return this.pageInfo.view;
  9110. },
  9111. /**
  9112. * @param {number} scale The desired scale of the viewport.
  9113. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  9114. * defaults to the page rotation.
  9115. * @return {PageViewport} Contains 'width' and 'height' properties
  9116. * along with transforms required for rendering.
  9117. */
  9118. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  9119. if (arguments.length < 2) {
  9120. rotate = this.rotate;
  9121. }
  9122. return new PageViewport(this.view, scale, rotate, 0, 0);
  9123. },
  9124. /**
  9125. * @param {GetAnnotationsParameters} params - Annotation parameters.
  9126. * @return {Promise} A promise that is resolved with an {Array} of the
  9127. * annotation objects.
  9128. */
  9129. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  9130. var intent = params && params.intent || null;
  9131. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  9132. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  9133. this.annotationsIntent = intent;
  9134. }
  9135. return this.annotationsPromise;
  9136. },
  9137. /**
  9138. * Begins the process of rendering a page to the desired context.
  9139. * @param {RenderParameters} params Page render parameters.
  9140. * @return {RenderTask} An object that contains the promise, which
  9141. * is resolved when the page finishes rendering.
  9142. */
  9143. render: function PDFPageProxy_render(params) {
  9144. var stats = this.stats;
  9145. stats.time('Overall');
  9146. // If there was a pending destroy cancel it so no cleanup happens during
  9147. // this call to render.
  9148. this.pendingCleanup = false;
  9149. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  9150. var renderInteractiveForms = params.renderInteractiveForms === true ? true : /* Default */
  9151. false;
  9152. if (!this.intentStates[renderingIntent]) {
  9153. this.intentStates[renderingIntent] = Object.create(null);
  9154. }
  9155. var intentState = this.intentStates[renderingIntent];
  9156. // If there's no displayReadyCapability yet, then the operatorList
  9157. // was never requested before. Make the request and create the promise.
  9158. if (!intentState.displayReadyCapability) {
  9159. intentState.receivingOperatorList = true;
  9160. intentState.displayReadyCapability = createPromiseCapability();
  9161. intentState.operatorList = {
  9162. fnArray: [],
  9163. argsArray: [],
  9164. lastChunk: false
  9165. };
  9166. this.stats.time('Page Request');
  9167. this.transport.messageHandler.send('RenderPageRequest', {
  9168. pageIndex: this.pageNumber - 1,
  9169. intent: renderingIntent,
  9170. renderInteractiveForms: renderInteractiveForms
  9171. });
  9172. }
  9173. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  9174. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  9175. if (!intentState.renderTasks) {
  9176. intentState.renderTasks = [];
  9177. }
  9178. intentState.renderTasks.push(internalRenderTask);
  9179. var renderTask = internalRenderTask.task;
  9180. // Obsolete parameter support
  9181. if (params.continueCallback) {
  9182. deprecated('render is used with continueCallback parameter');
  9183. renderTask.onContinue = params.continueCallback;
  9184. }
  9185. var self = this;
  9186. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  9187. if (self.pendingCleanup) {
  9188. complete();
  9189. return;
  9190. }
  9191. stats.time('Rendering');
  9192. internalRenderTask.initializeGraphics(transparency);
  9193. internalRenderTask.operatorListChanged();
  9194. }, function pageDisplayReadPromiseError(reason) {
  9195. complete(reason);
  9196. });
  9197. function complete(error) {
  9198. var i = intentState.renderTasks.indexOf(internalRenderTask);
  9199. if (i >= 0) {
  9200. intentState.renderTasks.splice(i, 1);
  9201. }
  9202. if (self.cleanupAfterRender) {
  9203. self.pendingCleanup = true;
  9204. }
  9205. self._tryCleanup();
  9206. if (error) {
  9207. internalRenderTask.capability.reject(error);
  9208. } else {
  9209. internalRenderTask.capability.resolve();
  9210. }
  9211. stats.timeEnd('Rendering');
  9212. stats.timeEnd('Overall');
  9213. }
  9214. return renderTask;
  9215. },
  9216. /**
  9217. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  9218. * object that represents page's operator list.
  9219. */
  9220. getOperatorList: function PDFPageProxy_getOperatorList() {
  9221. function operatorListChanged() {
  9222. if (intentState.operatorList.lastChunk) {
  9223. intentState.opListReadCapability.resolve(intentState.operatorList);
  9224. var i = intentState.renderTasks.indexOf(opListTask);
  9225. if (i >= 0) {
  9226. intentState.renderTasks.splice(i, 1);
  9227. }
  9228. }
  9229. }
  9230. var renderingIntent = 'oplist';
  9231. if (!this.intentStates[renderingIntent]) {
  9232. this.intentStates[renderingIntent] = Object.create(null);
  9233. }
  9234. var intentState = this.intentStates[renderingIntent];
  9235. var opListTask;
  9236. if (!intentState.opListReadCapability) {
  9237. opListTask = {};
  9238. opListTask.operatorListChanged = operatorListChanged;
  9239. intentState.receivingOperatorList = true;
  9240. intentState.opListReadCapability = createPromiseCapability();
  9241. intentState.renderTasks = [];
  9242. intentState.renderTasks.push(opListTask);
  9243. intentState.operatorList = {
  9244. fnArray: [],
  9245. argsArray: [],
  9246. lastChunk: false
  9247. };
  9248. this.transport.messageHandler.send('RenderPageRequest', {
  9249. pageIndex: this.pageIndex,
  9250. intent: renderingIntent
  9251. });
  9252. }
  9253. return intentState.opListReadCapability.promise;
  9254. },
  9255. /**
  9256. * @param {getTextContentParameters} params - getTextContent parameters.
  9257. * @return {Promise} That is resolved a {@link TextContent}
  9258. * object that represent the page text content.
  9259. */
  9260. getTextContent: function PDFPageProxy_getTextContent(params) {
  9261. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  9262. pageIndex: this.pageNumber - 1,
  9263. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : /* Default */
  9264. false,
  9265. combineTextItems: params && params.disableCombineTextItems === true ? false : /* Default */
  9266. true
  9267. });
  9268. },
  9269. /**
  9270. * Destroys page object.
  9271. */
  9272. _destroy: function PDFPageProxy_destroy() {
  9273. this.destroyed = true;
  9274. this.transport.pageCache[this.pageIndex] = null;
  9275. var waitOn = [];
  9276. Object.keys(this.intentStates).forEach(function (intent) {
  9277. if (intent === 'oplist') {
  9278. // Avoid errors below, since the renderTasks are just stubs.
  9279. return;
  9280. }
  9281. var intentState = this.intentStates[intent];
  9282. intentState.renderTasks.forEach(function (renderTask) {
  9283. var renderCompleted = renderTask.capability.promise.catch(function () {
  9284. });
  9285. // ignoring failures
  9286. waitOn.push(renderCompleted);
  9287. renderTask.cancel();
  9288. });
  9289. }, this);
  9290. this.objs.clear();
  9291. this.annotationsPromise = null;
  9292. this.pendingCleanup = false;
  9293. return Promise.all(waitOn);
  9294. },
  9295. /**
  9296. * Cleans up resources allocated by the page. (deprecated)
  9297. */
  9298. destroy: function () {
  9299. deprecated('page destroy method, use cleanup() instead');
  9300. this.cleanup();
  9301. },
  9302. /**
  9303. * Cleans up resources allocated by the page.
  9304. */
  9305. cleanup: function PDFPageProxy_cleanup() {
  9306. this.pendingCleanup = true;
  9307. this._tryCleanup();
  9308. },
  9309. /**
  9310. * For internal use only. Attempts to clean up if rendering is in a state
  9311. * where that's possible.
  9312. * @ignore
  9313. */
  9314. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9315. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  9316. var intentState = this.intentStates[intent];
  9317. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  9318. }, this)) {
  9319. return;
  9320. }
  9321. Object.keys(this.intentStates).forEach(function (intent) {
  9322. delete this.intentStates[intent];
  9323. }, this);
  9324. this.objs.clear();
  9325. this.annotationsPromise = null;
  9326. this.pendingCleanup = false;
  9327. },
  9328. /**
  9329. * For internal use only.
  9330. * @ignore
  9331. */
  9332. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  9333. var intentState = this.intentStates[intent];
  9334. // TODO Refactor RenderPageRequest to separate rendering
  9335. // and operator list logic
  9336. if (intentState.displayReadyCapability) {
  9337. intentState.displayReadyCapability.resolve(transparency);
  9338. }
  9339. },
  9340. /**
  9341. * For internal use only.
  9342. * @ignore
  9343. */
  9344. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  9345. var intentState = this.intentStates[intent];
  9346. var i, ii;
  9347. // Add the new chunk to the current operator list.
  9348. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9349. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9350. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  9351. }
  9352. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9353. // Notify all the rendering tasks there are more operators to be consumed.
  9354. for (i = 0; i < intentState.renderTasks.length; i++) {
  9355. intentState.renderTasks[i].operatorListChanged();
  9356. }
  9357. if (operatorListChunk.lastChunk) {
  9358. intentState.receivingOperatorList = false;
  9359. this._tryCleanup();
  9360. }
  9361. }
  9362. };
  9363. return PDFPageProxy;
  9364. }();
  9365. /**
  9366. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9367. * WorkerTransport for them. If creation of a web worker is not possible,
  9368. * a "fake" worker will be used instead.
  9369. * @class
  9370. */
  9371. var PDFWorker = function PDFWorkerClosure() {
  9372. var nextFakeWorkerId = 0;
  9373. function getWorkerSrc() {
  9374. if (typeof workerSrc !== 'undefined') {
  9375. return workerSrc;
  9376. }
  9377. if (getDefaultSetting('workerSrc')) {
  9378. return getDefaultSetting('workerSrc');
  9379. }
  9380. if (pdfjsFilePath) {
  9381. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9382. }
  9383. error('No PDFJS.workerSrc specified');
  9384. }
  9385. var fakeWorkerFilesLoadedCapability;
  9386. // Loads worker code into main thread.
  9387. function setupFakeWorkerGlobal() {
  9388. var WorkerMessageHandler;
  9389. if (fakeWorkerFilesLoadedCapability) {
  9390. return fakeWorkerFilesLoadedCapability.promise;
  9391. }
  9392. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9393. var loader = fakeWorkerFilesLoader || function (callback) {
  9394. Util.loadScript(getWorkerSrc(), function () {
  9395. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9396. });
  9397. };
  9398. loader(fakeWorkerFilesLoadedCapability.resolve);
  9399. return fakeWorkerFilesLoadedCapability.promise;
  9400. }
  9401. function FakeWorkerPort(defer) {
  9402. this._listeners = [];
  9403. this._defer = defer;
  9404. this._deferred = Promise.resolve(undefined);
  9405. }
  9406. FakeWorkerPort.prototype = {
  9407. postMessage: function (obj, transfers) {
  9408. function cloneValue(value) {
  9409. // Trying to perform a structured clone close to the spec, including
  9410. // transfers.
  9411. if (typeof value !== 'object' || value === null) {
  9412. return value;
  9413. }
  9414. if (cloned.has(value)) {
  9415. // already cloned the object
  9416. return cloned.get(value);
  9417. }
  9418. var result;
  9419. var buffer;
  9420. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9421. // We found object with ArrayBuffer (typed array).
  9422. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9423. if (value === buffer) {
  9424. // Special case when we are faking typed arrays in compatibility.js.
  9425. result = value;
  9426. } else if (transferable) {
  9427. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  9428. } else {
  9429. result = new value.constructor(value);
  9430. }
  9431. cloned.set(value, result);
  9432. return result;
  9433. }
  9434. result = isArray(value) ? [] : {};
  9435. cloned.set(value, result);
  9436. // adding to cache now for cyclic references
  9437. // Cloning all value and object properties, however ignoring properties
  9438. // defined via getter.
  9439. for (var i in value) {
  9440. var desc, p = value;
  9441. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9442. p = Object.getPrototypeOf(p);
  9443. }
  9444. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  9445. continue;
  9446. }
  9447. result[i] = cloneValue(desc.value);
  9448. }
  9449. return result;
  9450. }
  9451. if (!this._defer) {
  9452. this._listeners.forEach(function (listener) {
  9453. listener.call(this, { data: obj });
  9454. }, this);
  9455. return;
  9456. }
  9457. var cloned = new WeakMap();
  9458. var e = { data: cloneValue(obj) };
  9459. this._deferred.then(function () {
  9460. this._listeners.forEach(function (listener) {
  9461. listener.call(this, e);
  9462. }, this);
  9463. }.bind(this));
  9464. },
  9465. addEventListener: function (name, listener) {
  9466. this._listeners.push(listener);
  9467. },
  9468. removeEventListener: function (name, listener) {
  9469. var i = this._listeners.indexOf(listener);
  9470. this._listeners.splice(i, 1);
  9471. },
  9472. terminate: function () {
  9473. this._listeners = [];
  9474. }
  9475. };
  9476. function createCDNWrapper(url) {
  9477. // We will rely on blob URL's property to specify origin.
  9478. // We want this function to fail in case if createObjectURL or Blob do not
  9479. // exist or fail for some reason -- our Worker creation will fail anyway.
  9480. var wrapper = 'importScripts(\'' + url + '\');';
  9481. return URL.createObjectURL(new Blob([wrapper]));
  9482. }
  9483. function PDFWorker(name) {
  9484. this.name = name;
  9485. this.destroyed = false;
  9486. this._readyCapability = createPromiseCapability();
  9487. this._port = null;
  9488. this._webWorker = null;
  9489. this._messageHandler = null;
  9490. this._initialize();
  9491. }
  9492. PDFWorker.prototype = /** @lends PDFWorker.prototype */
  9493. {
  9494. get promise() {
  9495. return this._readyCapability.promise;
  9496. },
  9497. get port() {
  9498. return this._port;
  9499. },
  9500. get messageHandler() {
  9501. return this._messageHandler;
  9502. },
  9503. _initialize: function PDFWorker_initialize() {
  9504. // If worker support isn't disabled explicit and the browser has worker
  9505. // support, create a new web worker and test if it/the browser fulfills
  9506. // all requirements to run parts of pdf.js in a web worker.
  9507. // Right now, the requirement is, that an Uint8Array is still an
  9508. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9509. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  9510. var workerSrc = getWorkerSrc();
  9511. try {
  9512. // Wraps workerSrc path into blob URL, if the former does not belong
  9513. // to the same origin.
  9514. if (!isSameOrigin(window.location.href, workerSrc)) {
  9515. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  9516. }
  9517. // Some versions of FF can't create a worker on localhost, see:
  9518. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9519. var worker = new Worker(workerSrc);
  9520. var messageHandler = new MessageHandler('main', 'worker', worker);
  9521. var terminateEarly = function () {
  9522. worker.removeEventListener('error', onWorkerError);
  9523. messageHandler.destroy();
  9524. worker.terminate();
  9525. if (this.destroyed) {
  9526. this._readyCapability.reject(new Error('Worker was destroyed'));
  9527. } else {
  9528. // Fall back to fake worker if the termination is caused by an
  9529. // error (e.g. NetworkError / SecurityError).
  9530. this._setupFakeWorker();
  9531. }
  9532. }.bind(this);
  9533. var onWorkerError = function (event) {
  9534. if (!this._webWorker) {
  9535. // Worker failed to initialize due to an error. Clean up and fall
  9536. // back to the fake worker.
  9537. terminateEarly();
  9538. }
  9539. }.bind(this);
  9540. worker.addEventListener('error', onWorkerError);
  9541. messageHandler.on('test', function PDFWorker_test(data) {
  9542. worker.removeEventListener('error', onWorkerError);
  9543. if (this.destroyed) {
  9544. terminateEarly();
  9545. return;
  9546. }
  9547. // worker was destroyed
  9548. var supportTypedArray = data && data.supportTypedArray;
  9549. if (supportTypedArray) {
  9550. this._messageHandler = messageHandler;
  9551. this._port = worker;
  9552. this._webWorker = worker;
  9553. if (!data.supportTransfers) {
  9554. isPostMessageTransfersDisabled = true;
  9555. }
  9556. this._readyCapability.resolve();
  9557. // Send global setting, e.g. verbosity level.
  9558. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  9559. } else {
  9560. this._setupFakeWorker();
  9561. messageHandler.destroy();
  9562. worker.terminate();
  9563. }
  9564. }.bind(this));
  9565. messageHandler.on('console_log', function (data) {
  9566. console.log.apply(console, data);
  9567. });
  9568. messageHandler.on('console_error', function (data) {
  9569. console.error.apply(console, data);
  9570. });
  9571. messageHandler.on('ready', function (data) {
  9572. worker.removeEventListener('error', onWorkerError);
  9573. if (this.destroyed) {
  9574. terminateEarly();
  9575. return;
  9576. }
  9577. // worker was destroyed
  9578. try {
  9579. sendTest();
  9580. } catch (e) {
  9581. // We need fallback to a faked worker.
  9582. this._setupFakeWorker();
  9583. }
  9584. }.bind(this));
  9585. var sendTest = function () {
  9586. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  9587. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9588. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9589. // typed array. Also, checking if we can use transfers.
  9590. try {
  9591. messageHandler.send('test', testObj, [testObj.buffer]);
  9592. } catch (ex) {
  9593. info('Cannot use postMessage transfers');
  9594. testObj[0] = 0;
  9595. messageHandler.send('test', testObj);
  9596. }
  9597. };
  9598. // It might take time for worker to initialize (especially when AMD
  9599. // loader is used). We will try to send test immediately, and then
  9600. // when 'ready' message will arrive. The worker shall process only
  9601. // first received 'test'.
  9602. sendTest();
  9603. return;
  9604. } catch (e) {
  9605. info('The worker has been disabled.');
  9606. }
  9607. }
  9608. // Either workers are disabled, not supported or have thrown an exception.
  9609. // Thus, we fallback to a faked worker.
  9610. this._setupFakeWorker();
  9611. },
  9612. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9613. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9614. warn('Setting up fake worker.');
  9615. isWorkerDisabled = true;
  9616. }
  9617. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9618. if (this.destroyed) {
  9619. this._readyCapability.reject(new Error('Worker was destroyed'));
  9620. return;
  9621. }
  9622. // We cannot turn on proper fake port simulation (this includes
  9623. // structured cloning) when typed arrays are not supported. Relying
  9624. // on a chance that messages will be sent in proper order.
  9625. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9626. var port = new FakeWorkerPort(isTypedArraysPresent);
  9627. this._port = port;
  9628. // All fake workers use the same port, making id unique.
  9629. var id = 'fake' + nextFakeWorkerId++;
  9630. // If the main thread is our worker, setup the handling for the
  9631. // messages -- the main thread sends to it self.
  9632. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9633. WorkerMessageHandler.setup(workerHandler, port);
  9634. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9635. this._messageHandler = messageHandler;
  9636. this._readyCapability.resolve();
  9637. }.bind(this));
  9638. },
  9639. /**
  9640. * Destroys the worker instance.
  9641. */
  9642. destroy: function PDFWorker_destroy() {
  9643. this.destroyed = true;
  9644. if (this._webWorker) {
  9645. // We need to terminate only web worker created resource.
  9646. this._webWorker.terminate();
  9647. this._webWorker = null;
  9648. }
  9649. this._port = null;
  9650. if (this._messageHandler) {
  9651. this._messageHandler.destroy();
  9652. this._messageHandler = null;
  9653. }
  9654. }
  9655. };
  9656. return PDFWorker;
  9657. }();
  9658. /**
  9659. * For internal use only.
  9660. * @ignore
  9661. */
  9662. var WorkerTransport = function WorkerTransportClosure() {
  9663. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9664. this.messageHandler = messageHandler;
  9665. this.loadingTask = loadingTask;
  9666. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9667. this.commonObjs = new PDFObjects();
  9668. this.fontLoader = new FontLoader(loadingTask.docId);
  9669. this.destroyed = false;
  9670. this.destroyCapability = null;
  9671. this.pageCache = [];
  9672. this.pagePromises = [];
  9673. this.downloadInfoCapability = createPromiseCapability();
  9674. this.setupMessageHandler();
  9675. }
  9676. WorkerTransport.prototype = {
  9677. destroy: function WorkerTransport_destroy() {
  9678. if (this.destroyCapability) {
  9679. return this.destroyCapability.promise;
  9680. }
  9681. this.destroyed = true;
  9682. this.destroyCapability = createPromiseCapability();
  9683. var waitOn = [];
  9684. // We need to wait for all renderings to be completed, e.g.
  9685. // timeout/rAF can take a long time.
  9686. this.pageCache.forEach(function (page) {
  9687. if (page) {
  9688. waitOn.push(page._destroy());
  9689. }
  9690. });
  9691. this.pageCache = [];
  9692. this.pagePromises = [];
  9693. var self = this;
  9694. // We also need to wait for the worker to finish its long running tasks.
  9695. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9696. waitOn.push(terminated);
  9697. Promise.all(waitOn).then(function () {
  9698. self.fontLoader.clear();
  9699. if (self.pdfDataRangeTransport) {
  9700. self.pdfDataRangeTransport.abort();
  9701. self.pdfDataRangeTransport = null;
  9702. }
  9703. if (self.messageHandler) {
  9704. self.messageHandler.destroy();
  9705. self.messageHandler = null;
  9706. }
  9707. self.destroyCapability.resolve();
  9708. }, this.destroyCapability.reject);
  9709. return this.destroyCapability.promise;
  9710. },
  9711. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  9712. var messageHandler = this.messageHandler;
  9713. function updatePassword(password) {
  9714. messageHandler.send('UpdatePassword', password);
  9715. }
  9716. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9717. if (pdfDataRangeTransport) {
  9718. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  9719. messageHandler.send('OnDataRange', {
  9720. begin: begin,
  9721. chunk: chunk
  9722. });
  9723. });
  9724. pdfDataRangeTransport.addProgressListener(function (loaded) {
  9725. messageHandler.send('OnDataProgress', { loaded: loaded });
  9726. });
  9727. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  9728. messageHandler.send('OnDataRange', { chunk: chunk });
  9729. });
  9730. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  9731. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9732. }, this);
  9733. }
  9734. messageHandler.on('GetDoc', function transportDoc(data) {
  9735. var pdfInfo = data.pdfInfo;
  9736. this.numPages = data.pdfInfo.numPages;
  9737. var loadingTask = this.loadingTask;
  9738. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9739. this.pdfDocument = pdfDocument;
  9740. loadingTask._capability.resolve(pdfDocument);
  9741. }, this);
  9742. messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
  9743. var loadingTask = this.loadingTask;
  9744. if (loadingTask.onPassword) {
  9745. return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
  9746. }
  9747. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9748. }, this);
  9749. messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
  9750. var loadingTask = this.loadingTask;
  9751. if (loadingTask.onPassword) {
  9752. return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
  9753. }
  9754. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9755. }, this);
  9756. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9757. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  9758. }, this);
  9759. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9760. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  9761. }, this);
  9762. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  9763. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  9764. }, this);
  9765. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  9766. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  9767. }, this);
  9768. messageHandler.on('DataLoaded', function transportPage(data) {
  9769. this.downloadInfoCapability.resolve(data);
  9770. }, this);
  9771. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9772. if (this.pdfDataRangeTransport) {
  9773. this.pdfDataRangeTransport.transportReady();
  9774. }
  9775. }, this);
  9776. messageHandler.on('StartRenderPage', function transportRender(data) {
  9777. if (this.destroyed) {
  9778. return;
  9779. }
  9780. // Ignore any pending requests if the worker was terminated.
  9781. var page = this.pageCache[data.pageIndex];
  9782. page.stats.timeEnd('Page Request');
  9783. page._startRenderPage(data.transparency, data.intent);
  9784. }, this);
  9785. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9786. if (this.destroyed) {
  9787. return;
  9788. }
  9789. // Ignore any pending requests if the worker was terminated.
  9790. var page = this.pageCache[data.pageIndex];
  9791. page._renderPageChunk(data.operatorList, data.intent);
  9792. }, this);
  9793. messageHandler.on('commonobj', function transportObj(data) {
  9794. if (this.destroyed) {
  9795. return;
  9796. }
  9797. // Ignore any pending requests if the worker was terminated.
  9798. var id = data[0];
  9799. var type = data[1];
  9800. if (this.commonObjs.hasData(id)) {
  9801. return;
  9802. }
  9803. switch (type) {
  9804. case 'Font':
  9805. var exportedData = data[2];
  9806. if ('error' in exportedData) {
  9807. var exportedError = exportedData.error;
  9808. warn('Error during font loading: ' + exportedError);
  9809. this.commonObjs.resolve(id, exportedError);
  9810. break;
  9811. }
  9812. var fontRegistry = null;
  9813. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  9814. fontRegistry = {
  9815. registerFont: function (font, url) {
  9816. globalScope['FontInspector'].fontAdded(font, url);
  9817. }
  9818. };
  9819. }
  9820. var font = new FontFaceObject(exportedData, {
  9821. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9822. disableFontFace: getDefaultSetting('disableFontFace'),
  9823. fontRegistry: fontRegistry
  9824. });
  9825. this.fontLoader.bind([font], function fontReady(fontObjs) {
  9826. this.commonObjs.resolve(id, font);
  9827. }.bind(this));
  9828. break;
  9829. case 'FontPath':
  9830. this.commonObjs.resolve(id, data[2]);
  9831. break;
  9832. default:
  9833. error('Got unknown common object type ' + type);
  9834. }
  9835. }, this);
  9836. messageHandler.on('obj', function transportObj(data) {
  9837. if (this.destroyed) {
  9838. return;
  9839. }
  9840. // Ignore any pending requests if the worker was terminated.
  9841. var id = data[0];
  9842. var pageIndex = data[1];
  9843. var type = data[2];
  9844. var pageProxy = this.pageCache[pageIndex];
  9845. var imageData;
  9846. if (pageProxy.objs.hasData(id)) {
  9847. return;
  9848. }
  9849. switch (type) {
  9850. case 'JpegStream':
  9851. imageData = data[3];
  9852. loadJpegStream(id, imageData, pageProxy.objs);
  9853. break;
  9854. case 'Image':
  9855. imageData = data[3];
  9856. pageProxy.objs.resolve(id, imageData);
  9857. // heuristics that will allow not to store large data
  9858. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9859. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9860. pageProxy.cleanupAfterRender = true;
  9861. }
  9862. break;
  9863. default:
  9864. error('Got unknown object type ' + type);
  9865. }
  9866. }, this);
  9867. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9868. if (this.destroyed) {
  9869. return;
  9870. }
  9871. // Ignore any pending requests if the worker was terminated.
  9872. var loadingTask = this.loadingTask;
  9873. if (loadingTask.onProgress) {
  9874. loadingTask.onProgress({
  9875. loaded: data.loaded,
  9876. total: data.total
  9877. });
  9878. }
  9879. }, this);
  9880. messageHandler.on('PageError', function transportError(data) {
  9881. if (this.destroyed) {
  9882. return;
  9883. }
  9884. // Ignore any pending requests if the worker was terminated.
  9885. var page = this.pageCache[data.pageNum - 1];
  9886. var intentState = page.intentStates[data.intent];
  9887. if (intentState.displayReadyCapability) {
  9888. intentState.displayReadyCapability.reject(data.error);
  9889. } else {
  9890. error(data.error);
  9891. }
  9892. if (intentState.operatorList) {
  9893. // Mark operator list as complete.
  9894. intentState.operatorList.lastChunk = true;
  9895. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9896. intentState.renderTasks[i].operatorListChanged();
  9897. }
  9898. }
  9899. }, this);
  9900. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  9901. if (this.destroyed) {
  9902. return;
  9903. }
  9904. // Ignore any pending requests if the worker was terminated.
  9905. var featureId = data.featureId;
  9906. var loadingTask = this.loadingTask;
  9907. if (loadingTask.onUnsupportedFeature) {
  9908. loadingTask.onUnsupportedFeature(featureId);
  9909. }
  9910. _UnsupportedManager.notify(featureId);
  9911. }, this);
  9912. messageHandler.on('JpegDecode', function (data) {
  9913. if (this.destroyed) {
  9914. return Promise.reject(new Error('Worker was destroyed'));
  9915. }
  9916. var imageUrl = data[0];
  9917. var components = data[1];
  9918. if (components !== 3 && components !== 1) {
  9919. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  9920. }
  9921. return new Promise(function (resolve, reject) {
  9922. var img = new Image();
  9923. img.onload = function () {
  9924. var width = img.width;
  9925. var height = img.height;
  9926. var size = width * height;
  9927. var rgbaLength = size * 4;
  9928. var buf = new Uint8Array(size * components);
  9929. var tmpCanvas = createScratchCanvas(width, height);
  9930. var tmpCtx = tmpCanvas.getContext('2d');
  9931. tmpCtx.drawImage(img, 0, 0);
  9932. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9933. var i, j;
  9934. if (components === 3) {
  9935. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9936. buf[j] = data[i];
  9937. buf[j + 1] = data[i + 1];
  9938. buf[j + 2] = data[i + 2];
  9939. }
  9940. } else if (components === 1) {
  9941. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9942. buf[j] = data[i];
  9943. }
  9944. }
  9945. resolve({
  9946. data: buf,
  9947. width: width,
  9948. height: height
  9949. });
  9950. };
  9951. img.onerror = function () {
  9952. reject(new Error('JpegDecode failed to load image'));
  9953. };
  9954. img.src = imageUrl;
  9955. });
  9956. }, this);
  9957. },
  9958. getData: function WorkerTransport_getData() {
  9959. return this.messageHandler.sendWithPromise('GetData', null);
  9960. },
  9961. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9962. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9963. return Promise.reject(new Error('Invalid page request'));
  9964. }
  9965. var pageIndex = pageNumber - 1;
  9966. if (pageIndex in this.pagePromises) {
  9967. return this.pagePromises[pageIndex];
  9968. }
  9969. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  9970. if (this.destroyed) {
  9971. throw new Error('Transport destroyed');
  9972. }
  9973. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9974. this.pageCache[pageIndex] = page;
  9975. return page;
  9976. }.bind(this));
  9977. this.pagePromises[pageIndex] = promise;
  9978. return promise;
  9979. },
  9980. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9981. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  9982. return Promise.reject(new Error(reason));
  9983. });
  9984. },
  9985. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9986. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9987. pageIndex: pageIndex,
  9988. intent: intent
  9989. });
  9990. },
  9991. getDestinations: function WorkerTransport_getDestinations() {
  9992. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9993. },
  9994. getDestination: function WorkerTransport_getDestination(id) {
  9995. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9996. },
  9997. getPageLabels: function WorkerTransport_getPageLabels() {
  9998. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9999. },
  10000. getAttachments: function WorkerTransport_getAttachments() {
  10001. return this.messageHandler.sendWithPromise('GetAttachments', null);
  10002. },
  10003. getJavaScript: function WorkerTransport_getJavaScript() {
  10004. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  10005. },
  10006. getOutline: function WorkerTransport_getOutline() {
  10007. return this.messageHandler.sendWithPromise('GetOutline', null);
  10008. },
  10009. getMetadata: function WorkerTransport_getMetadata() {
  10010. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  10011. return {
  10012. info: results[0],
  10013. metadata: results[1] ? new Metadata(results[1]) : null
  10014. };
  10015. });
  10016. },
  10017. getStats: function WorkerTransport_getStats() {
  10018. return this.messageHandler.sendWithPromise('GetStats', null);
  10019. },
  10020. startCleanup: function WorkerTransport_startCleanup() {
  10021. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  10022. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  10023. var page = this.pageCache[i];
  10024. if (page) {
  10025. page.cleanup();
  10026. }
  10027. }
  10028. this.commonObjs.clear();
  10029. this.fontLoader.clear();
  10030. }.bind(this));
  10031. }
  10032. };
  10033. return WorkerTransport;
  10034. }();
  10035. /**
  10036. * A PDF document and page is built of many objects. E.g. there are objects
  10037. * for fonts, images, rendering code and such. These objects might get processed
  10038. * inside of a worker. The `PDFObjects` implements some basic functions to
  10039. * manage these objects.
  10040. * @ignore
  10041. */
  10042. var PDFObjects = function PDFObjectsClosure() {
  10043. function PDFObjects() {
  10044. this.objs = Object.create(null);
  10045. }
  10046. PDFObjects.prototype = {
  10047. /**
  10048. * Internal function.
  10049. * Ensures there is an object defined for `objId`.
  10050. */
  10051. ensureObj: function PDFObjects_ensureObj(objId) {
  10052. if (this.objs[objId]) {
  10053. return this.objs[objId];
  10054. }
  10055. var obj = {
  10056. capability: createPromiseCapability(),
  10057. data: null,
  10058. resolved: false
  10059. };
  10060. this.objs[objId] = obj;
  10061. return obj;
  10062. },
  10063. /**
  10064. * If called *without* callback, this returns the data of `objId` but the
  10065. * object needs to be resolved. If it isn't, this function throws.
  10066. *
  10067. * If called *with* a callback, the callback is called with the data of the
  10068. * object once the object is resolved. That means, if you call this
  10069. * function and the object is already resolved, the callback gets called
  10070. * right away.
  10071. */
  10072. get: function PDFObjects_get(objId, callback) {
  10073. // If there is a callback, then the get can be async and the object is
  10074. // not required to be resolved right now
  10075. if (callback) {
  10076. this.ensureObj(objId).capability.promise.then(callback);
  10077. return null;
  10078. }
  10079. // If there isn't a callback, the user expects to get the resolved data
  10080. // directly.
  10081. var obj = this.objs[objId];
  10082. // If there isn't an object yet or the object isn't resolved, then the
  10083. // data isn't ready yet!
  10084. if (!obj || !obj.resolved) {
  10085. error('Requesting object that isn\'t resolved yet ' + objId);
  10086. }
  10087. return obj.data;
  10088. },
  10089. /**
  10090. * Resolves the object `objId` with optional `data`.
  10091. */
  10092. resolve: function PDFObjects_resolve(objId, data) {
  10093. var obj = this.ensureObj(objId);
  10094. obj.resolved = true;
  10095. obj.data = data;
  10096. obj.capability.resolve(data);
  10097. },
  10098. isResolved: function PDFObjects_isResolved(objId) {
  10099. var objs = this.objs;
  10100. if (!objs[objId]) {
  10101. return false;
  10102. } else {
  10103. return objs[objId].resolved;
  10104. }
  10105. },
  10106. hasData: function PDFObjects_hasData(objId) {
  10107. return this.isResolved(objId);
  10108. },
  10109. /**
  10110. * Returns the data of `objId` if object exists, null otherwise.
  10111. */
  10112. getData: function PDFObjects_getData(objId) {
  10113. var objs = this.objs;
  10114. if (!objs[objId] || !objs[objId].resolved) {
  10115. return null;
  10116. } else {
  10117. return objs[objId].data;
  10118. }
  10119. },
  10120. clear: function PDFObjects_clear() {
  10121. this.objs = Object.create(null);
  10122. }
  10123. };
  10124. return PDFObjects;
  10125. }();
  10126. /**
  10127. * Allows controlling of the rendering tasks.
  10128. * @class
  10129. * @alias RenderTask
  10130. */
  10131. var RenderTask = function RenderTaskClosure() {
  10132. function RenderTask(internalRenderTask) {
  10133. this._internalRenderTask = internalRenderTask;
  10134. /**
  10135. * Callback for incremental rendering -- a function that will be called
  10136. * each time the rendering is paused. To continue rendering call the
  10137. * function that is the first argument to the callback.
  10138. * @type {function}
  10139. */
  10140. this.onContinue = null;
  10141. }
  10142. RenderTask.prototype = /** @lends RenderTask.prototype */
  10143. {
  10144. /**
  10145. * Promise for rendering task completion.
  10146. * @return {Promise}
  10147. */
  10148. get promise() {
  10149. return this._internalRenderTask.capability.promise;
  10150. },
  10151. /**
  10152. * Cancels the rendering task. If the task is currently rendering it will
  10153. * not be cancelled until graphics pauses with a timeout. The promise that
  10154. * this object extends will resolved when cancelled.
  10155. */
  10156. cancel: function RenderTask_cancel() {
  10157. this._internalRenderTask.cancel();
  10158. },
  10159. /**
  10160. * Registers callbacks to indicate the rendering task completion.
  10161. *
  10162. * @param {function} onFulfilled The callback for the rendering completion.
  10163. * @param {function} onRejected The callback for the rendering failure.
  10164. * @return {Promise} A promise that is resolved after the onFulfilled or
  10165. * onRejected callback.
  10166. */
  10167. then: function RenderTask_then(onFulfilled, onRejected) {
  10168. return this.promise.then.apply(this.promise, arguments);
  10169. }
  10170. };
  10171. return RenderTask;
  10172. }();
  10173. /**
  10174. * For internal use only.
  10175. * @ignore
  10176. */
  10177. var InternalRenderTask = function InternalRenderTaskClosure() {
  10178. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  10179. this.callback = callback;
  10180. this.params = params;
  10181. this.objs = objs;
  10182. this.commonObjs = commonObjs;
  10183. this.operatorListIdx = null;
  10184. this.operatorList = operatorList;
  10185. this.pageNumber = pageNumber;
  10186. this.running = false;
  10187. this.graphicsReadyCallback = null;
  10188. this.graphicsReady = false;
  10189. this.useRequestAnimationFrame = false;
  10190. this.cancelled = false;
  10191. this.capability = createPromiseCapability();
  10192. this.task = new RenderTask(this);
  10193. // caching this-bound methods
  10194. this._continueBound = this._continue.bind(this);
  10195. this._scheduleNextBound = this._scheduleNext.bind(this);
  10196. this._nextBound = this._next.bind(this);
  10197. }
  10198. InternalRenderTask.prototype = {
  10199. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  10200. if (this.cancelled) {
  10201. return;
  10202. }
  10203. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  10204. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  10205. this.stepper.init(this.operatorList);
  10206. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  10207. }
  10208. var params = this.params;
  10209. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  10210. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  10211. this.operatorListIdx = 0;
  10212. this.graphicsReady = true;
  10213. if (this.graphicsReadyCallback) {
  10214. this.graphicsReadyCallback();
  10215. }
  10216. },
  10217. cancel: function InternalRenderTask_cancel() {
  10218. this.running = false;
  10219. this.cancelled = true;
  10220. this.callback('cancelled');
  10221. },
  10222. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  10223. if (!this.graphicsReady) {
  10224. if (!this.graphicsReadyCallback) {
  10225. this.graphicsReadyCallback = this._continueBound;
  10226. }
  10227. return;
  10228. }
  10229. if (this.stepper) {
  10230. this.stepper.updateOperatorList(this.operatorList);
  10231. }
  10232. if (this.running) {
  10233. return;
  10234. }
  10235. this._continue();
  10236. },
  10237. _continue: function InternalRenderTask__continue() {
  10238. this.running = true;
  10239. if (this.cancelled) {
  10240. return;
  10241. }
  10242. if (this.task.onContinue) {
  10243. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10244. } else {
  10245. this._scheduleNext();
  10246. }
  10247. },
  10248. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10249. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10250. window.requestAnimationFrame(this._nextBound);
  10251. } else {
  10252. Promise.resolve(undefined).then(this._nextBound);
  10253. }
  10254. },
  10255. _next: function InternalRenderTask__next() {
  10256. if (this.cancelled) {
  10257. return;
  10258. }
  10259. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  10260. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10261. this.running = false;
  10262. if (this.operatorList.lastChunk) {
  10263. this.gfx.endDrawing();
  10264. this.callback();
  10265. }
  10266. }
  10267. }
  10268. };
  10269. return InternalRenderTask;
  10270. }();
  10271. /**
  10272. * (Deprecated) Global observer of unsupported feature usages. Use
  10273. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10274. */
  10275. var _UnsupportedManager = function UnsupportedManagerClosure() {
  10276. var listeners = [];
  10277. return {
  10278. listen: function (cb) {
  10279. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10280. listeners.push(cb);
  10281. },
  10282. notify: function (featureId) {
  10283. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10284. listeners[i](featureId);
  10285. }
  10286. }
  10287. };
  10288. }();
  10289. if (typeof pdfjsVersion !== 'undefined') {
  10290. exports.version = pdfjsVersion;
  10291. }
  10292. if (typeof pdfjsBuild !== 'undefined') {
  10293. exports.build = pdfjsBuild;
  10294. }
  10295. exports.getDocument = getDocument;
  10296. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10297. exports.PDFWorker = PDFWorker;
  10298. exports.PDFDocumentProxy = PDFDocumentProxy;
  10299. exports.PDFPageProxy = PDFPageProxy;
  10300. exports._UnsupportedManager = _UnsupportedManager;
  10301. }));
  10302. (function (root, factory) {
  10303. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10304. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  10305. var globalScope = sharedUtil.globalScope;
  10306. var deprecated = sharedUtil.deprecated;
  10307. var warn = sharedUtil.warn;
  10308. var LinkTarget = displayDOMUtils.LinkTarget;
  10309. var isWorker = typeof window === 'undefined';
  10310. // The global PDFJS object is now deprecated and will not be supported in
  10311. // the future. The members below are maintained for backward compatibility
  10312. // and shall not be extended or modified. If the global.js is included as
  10313. // a module, we will create a global PDFJS object instance or use existing.
  10314. if (!globalScope.PDFJS) {
  10315. globalScope.PDFJS = {};
  10316. }
  10317. var PDFJS = globalScope.PDFJS;
  10318. if (typeof pdfjsVersion !== 'undefined') {
  10319. PDFJS.version = pdfjsVersion;
  10320. }
  10321. if (typeof pdfjsBuild !== 'undefined') {
  10322. PDFJS.build = pdfjsBuild;
  10323. }
  10324. PDFJS.pdfBug = false;
  10325. if (PDFJS.verbosity !== undefined) {
  10326. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10327. }
  10328. delete PDFJS.verbosity;
  10329. Object.defineProperty(PDFJS, 'verbosity', {
  10330. get: function () {
  10331. return sharedUtil.getVerbosityLevel();
  10332. },
  10333. set: function (level) {
  10334. sharedUtil.setVerbosityLevel(level);
  10335. },
  10336. enumerable: true,
  10337. configurable: true
  10338. });
  10339. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10340. PDFJS.OPS = sharedUtil.OPS;
  10341. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10342. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10343. PDFJS.shadow = sharedUtil.shadow;
  10344. PDFJS.createBlob = sharedUtil.createBlob;
  10345. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10346. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  10347. };
  10348. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10349. configurable: true,
  10350. get: function PDFJS_isLittleEndian() {
  10351. var value = sharedUtil.isLittleEndian();
  10352. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10353. }
  10354. });
  10355. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10356. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10357. PDFJS.PasswordException = sharedUtil.PasswordException;
  10358. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10359. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10360. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10361. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10362. PDFJS.Util = sharedUtil.Util;
  10363. PDFJS.PageViewport = sharedUtil.PageViewport;
  10364. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10365. /**
  10366. * The maximum allowed image size in total pixels e.g. width * height. Images
  10367. * above this value will not be drawn. Use -1 for no limit.
  10368. * @var {number}
  10369. */
  10370. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  10371. /**
  10372. * The url of where the predefined Adobe CMaps are located. Include trailing
  10373. * slash.
  10374. * @var {string}
  10375. */
  10376. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  10377. /**
  10378. * Specifies if CMaps are binary packed.
  10379. * @var {boolean}
  10380. */
  10381. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10382. /**
  10383. * By default fonts are converted to OpenType fonts and loaded via font face
  10384. * rules. If disabled, the font will be rendered using a built in font
  10385. * renderer that constructs the glyphs with primitive path commands.
  10386. * @var {boolean}
  10387. */
  10388. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  10389. /**
  10390. * Path for image resources, mainly for annotation icons. Include trailing
  10391. * slash.
  10392. * @var {string}
  10393. */
  10394. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  10395. /**
  10396. * Disable the web worker and run all code on the main thread. This will
  10397. * happen automatically if the browser doesn't support workers or sending
  10398. * typed arrays to workers.
  10399. * @var {boolean}
  10400. */
  10401. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  10402. /**
  10403. * Path and filename of the worker file. Required when the worker is enabled
  10404. * in development mode. If unspecified in the production build, the worker
  10405. * will be loaded based on the location of the pdf.js file. It is recommended
  10406. * that the workerSrc is set in a custom application to prevent issues caused
  10407. * by third-party frameworks and libraries.
  10408. * @var {string}
  10409. */
  10410. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  10411. /**
  10412. * Disable range request loading of PDF files. When enabled and if the server
  10413. * supports partial content requests then the PDF will be fetched in chunks.
  10414. * Enabled (false) by default.
  10415. * @var {boolean}
  10416. */
  10417. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  10418. /**
  10419. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10420. * in chunks. This default behavior can be disabled.
  10421. * @var {boolean}
  10422. */
  10423. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  10424. /**
  10425. * Disable pre-fetching of PDF file data. When range requests are enabled
  10426. * PDF.js will automatically keep fetching more data even if it isn't needed
  10427. * to display the current page. This default behavior can be disabled.
  10428. *
  10429. * NOTE: It is also necessary to disable streaming, see above,
  10430. * in order for disabling of pre-fetching to work correctly.
  10431. * @var {boolean}
  10432. */
  10433. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  10434. /**
  10435. * Enables special hooks for debugging PDF.js.
  10436. * @var {boolean}
  10437. */
  10438. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  10439. /**
  10440. * Enables transfer usage in postMessage for ArrayBuffers.
  10441. * @var {boolean}
  10442. */
  10443. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  10444. /**
  10445. * Disables URL.createObjectURL usage.
  10446. * @var {boolean}
  10447. */
  10448. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  10449. /**
  10450. * Disables WebGL usage.
  10451. * @var {boolean}
  10452. */
  10453. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  10454. /**
  10455. * Specifies the |target| attribute for external links.
  10456. * The constants from PDFJS.LinkTarget should be used:
  10457. * - NONE [default]
  10458. * - SELF
  10459. * - BLANK
  10460. * - PARENT
  10461. * - TOP
  10462. * @var {number}
  10463. */
  10464. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  10465. /**
  10466. * Specifies the |rel| attribute for external links. Defaults to stripping
  10467. * the referrer.
  10468. * @var {string}
  10469. */
  10470. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel;
  10471. /**
  10472. * Determines if we can eval strings as JS. Primarily used to improve
  10473. * performance for font rendering.
  10474. * @var {boolean}
  10475. */
  10476. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  10477. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10478. delete PDFJS.openExternalLinksInNewWindow;
  10479. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10480. get: function () {
  10481. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10482. },
  10483. set: function (value) {
  10484. if (value) {
  10485. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10486. }
  10487. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10488. warn('PDFJS.externalLinkTarget is already initialized');
  10489. return;
  10490. }
  10491. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10492. },
  10493. enumerable: true,
  10494. configurable: true
  10495. });
  10496. if (savedOpenExternalLinksInNewWindow) {
  10497. /**
  10498. * (Deprecated) Opens external links in a new window if enabled.
  10499. * The default behavior opens external links in the PDF.js window.
  10500. *
  10501. * NOTE: This property has been deprecated, please use
  10502. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10503. * @var {boolean}
  10504. */
  10505. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10506. }
  10507. PDFJS.getDocument = displayAPI.getDocument;
  10508. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10509. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10510. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10511. configurable: true,
  10512. get: function PDFJS_hasCanvasTypedArrays() {
  10513. var value = displayDOMUtils.hasCanvasTypedArrays();
  10514. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10515. }
  10516. });
  10517. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10518. PDFJS.LinkTarget = LinkTarget;
  10519. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10520. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10521. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10522. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10523. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10524. PDFJS.Metadata = displayMetadata.Metadata;
  10525. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10526. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10527. exports.globalScope = globalScope;
  10528. exports.isWorker = isWorker;
  10529. exports.PDFJS = globalScope.PDFJS;
  10530. }));
  10531. }.call(pdfjsLibs));
  10532. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10533. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10534. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10535. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10536. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10537. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10538. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10539. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10540. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10541. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10542. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10543. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10544. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10545. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10546. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10547. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10548. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10549. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10550. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10551. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10552. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10553. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10554. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10555. }));