pdf.js 366 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* jshint globalstrict: false */
  16. /* umdutils ignore */
  17. (function (root, factory) {
  18. 'use strict';
  19. if (typeof define === 'function' && define.amd) {
  20. define('pdfjs-dist/build/pdf', ['exports'], factory);
  21. } else if (typeof exports !== 'undefined') {
  22. factory(exports);
  23. } else {
  24. factory((root.pdfjsDistBuildPdf = {}));
  25. }
  26. }(this, function (exports) {
  27. // Use strict in our context only - users might not want it
  28. 'use strict';
  29. var pdfjsVersion = '1.5.488';
  30. var pdfjsBuild = '6c263c1';
  31. var pdfjsFilePath =
  32. typeof document !== 'undefined' && document.currentScript ?
  33. document.currentScript.src : null;
  34. var pdfjsLibs = {};
  35. (function pdfjsWrapper() {
  36. (function (root, factory) {
  37. {
  38. factory((root.pdfjsSharedUtil = {}));
  39. }
  40. }(this, function (exports) {
  41. var globalScope = (typeof window !== 'undefined') ? window :
  42. (typeof global !== 'undefined') ? global :
  43. (typeof self !== 'undefined') ? self : this;
  44. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  45. var TextRenderingMode = {
  46. FILL: 0,
  47. STROKE: 1,
  48. FILL_STROKE: 2,
  49. INVISIBLE: 3,
  50. FILL_ADD_TO_PATH: 4,
  51. STROKE_ADD_TO_PATH: 5,
  52. FILL_STROKE_ADD_TO_PATH: 6,
  53. ADD_TO_PATH: 7,
  54. FILL_STROKE_MASK: 3,
  55. ADD_TO_PATH_FLAG: 4
  56. };
  57. var ImageKind = {
  58. GRAYSCALE_1BPP: 1,
  59. RGB_24BPP: 2,
  60. RGBA_32BPP: 3
  61. };
  62. var AnnotationType = {
  63. TEXT: 1,
  64. LINK: 2,
  65. FREETEXT: 3,
  66. LINE: 4,
  67. SQUARE: 5,
  68. CIRCLE: 6,
  69. POLYGON: 7,
  70. POLYLINE: 8,
  71. HIGHLIGHT: 9,
  72. UNDERLINE: 10,
  73. SQUIGGLY: 11,
  74. STRIKEOUT: 12,
  75. STAMP: 13,
  76. CARET: 14,
  77. INK: 15,
  78. POPUP: 16,
  79. FILEATTACHMENT: 17,
  80. SOUND: 18,
  81. MOVIE: 19,
  82. WIDGET: 20,
  83. SCREEN: 21,
  84. PRINTERMARK: 22,
  85. TRAPNET: 23,
  86. WATERMARK: 24,
  87. THREED: 25,
  88. REDACT: 26
  89. };
  90. var AnnotationFlag = {
  91. INVISIBLE: 0x01,
  92. HIDDEN: 0x02,
  93. PRINT: 0x04,
  94. NOZOOM: 0x08,
  95. NOROTATE: 0x10,
  96. NOVIEW: 0x20,
  97. READONLY: 0x40,
  98. LOCKED: 0x80,
  99. TOGGLENOVIEW: 0x100,
  100. LOCKEDCONTENTS: 0x200
  101. };
  102. var AnnotationFieldFlag = {
  103. READONLY: 0x0000001,
  104. REQUIRED: 0x0000002,
  105. NOEXPORT: 0x0000004,
  106. MULTILINE: 0x0001000,
  107. PASSWORD: 0x0002000,
  108. NOTOGGLETOOFF: 0x0004000,
  109. RADIO: 0x0008000,
  110. PUSHBUTTON: 0x0010000,
  111. COMBO: 0x0020000,
  112. EDIT: 0x0040000,
  113. SORT: 0x0080000,
  114. FILESELECT: 0x0100000,
  115. MULTISELECT: 0x0200000,
  116. DONOTSPELLCHECK: 0x0400000,
  117. DONOTSCROLL: 0x0800000,
  118. COMB: 0x1000000,
  119. RICHTEXT: 0x2000000,
  120. RADIOSINUNISON: 0x2000000,
  121. COMMITONSELCHANGE: 0x4000000,
  122. };
  123. var AnnotationBorderStyleType = {
  124. SOLID: 1,
  125. DASHED: 2,
  126. BEVELED: 3,
  127. INSET: 4,
  128. UNDERLINE: 5
  129. };
  130. var StreamType = {
  131. UNKNOWN: 0,
  132. FLATE: 1,
  133. LZW: 2,
  134. DCT: 3,
  135. JPX: 4,
  136. JBIG: 5,
  137. A85: 6,
  138. AHX: 7,
  139. CCF: 8,
  140. RL: 9
  141. };
  142. var FontType = {
  143. UNKNOWN: 0,
  144. TYPE1: 1,
  145. TYPE1C: 2,
  146. CIDFONTTYPE0: 3,
  147. CIDFONTTYPE0C: 4,
  148. TRUETYPE: 5,
  149. CIDFONTTYPE2: 6,
  150. TYPE3: 7,
  151. OPENTYPE: 8,
  152. TYPE0: 9,
  153. MMTYPE1: 10
  154. };
  155. var VERBOSITY_LEVELS = {
  156. errors: 0,
  157. warnings: 1,
  158. infos: 5
  159. };
  160. // All the possible operations for an operator list.
  161. var OPS = {
  162. // Intentionally start from 1 so it is easy to spot bad operators that will be
  163. // 0's.
  164. dependency: 1,
  165. setLineWidth: 2,
  166. setLineCap: 3,
  167. setLineJoin: 4,
  168. setMiterLimit: 5,
  169. setDash: 6,
  170. setRenderingIntent: 7,
  171. setFlatness: 8,
  172. setGState: 9,
  173. save: 10,
  174. restore: 11,
  175. transform: 12,
  176. moveTo: 13,
  177. lineTo: 14,
  178. curveTo: 15,
  179. curveTo2: 16,
  180. curveTo3: 17,
  181. closePath: 18,
  182. rectangle: 19,
  183. stroke: 20,
  184. closeStroke: 21,
  185. fill: 22,
  186. eoFill: 23,
  187. fillStroke: 24,
  188. eoFillStroke: 25,
  189. closeFillStroke: 26,
  190. closeEOFillStroke: 27,
  191. endPath: 28,
  192. clip: 29,
  193. eoClip: 30,
  194. beginText: 31,
  195. endText: 32,
  196. setCharSpacing: 33,
  197. setWordSpacing: 34,
  198. setHScale: 35,
  199. setLeading: 36,
  200. setFont: 37,
  201. setTextRenderingMode: 38,
  202. setTextRise: 39,
  203. moveText: 40,
  204. setLeadingMoveText: 41,
  205. setTextMatrix: 42,
  206. nextLine: 43,
  207. showText: 44,
  208. showSpacedText: 45,
  209. nextLineShowText: 46,
  210. nextLineSetSpacingShowText: 47,
  211. setCharWidth: 48,
  212. setCharWidthAndBounds: 49,
  213. setStrokeColorSpace: 50,
  214. setFillColorSpace: 51,
  215. setStrokeColor: 52,
  216. setStrokeColorN: 53,
  217. setFillColor: 54,
  218. setFillColorN: 55,
  219. setStrokeGray: 56,
  220. setFillGray: 57,
  221. setStrokeRGBColor: 58,
  222. setFillRGBColor: 59,
  223. setStrokeCMYKColor: 60,
  224. setFillCMYKColor: 61,
  225. shadingFill: 62,
  226. beginInlineImage: 63,
  227. beginImageData: 64,
  228. endInlineImage: 65,
  229. paintXObject: 66,
  230. markPoint: 67,
  231. markPointProps: 68,
  232. beginMarkedContent: 69,
  233. beginMarkedContentProps: 70,
  234. endMarkedContent: 71,
  235. beginCompat: 72,
  236. endCompat: 73,
  237. paintFormXObjectBegin: 74,
  238. paintFormXObjectEnd: 75,
  239. beginGroup: 76,
  240. endGroup: 77,
  241. beginAnnotations: 78,
  242. endAnnotations: 79,
  243. beginAnnotation: 80,
  244. endAnnotation: 81,
  245. paintJpegXObject: 82,
  246. paintImageMaskXObject: 83,
  247. paintImageMaskXObjectGroup: 84,
  248. paintImageXObject: 85,
  249. paintInlineImageXObject: 86,
  250. paintInlineImageXObjectGroup: 87,
  251. paintImageXObjectRepeat: 88,
  252. paintImageMaskXObjectRepeat: 89,
  253. paintSolidColorImageMask: 90,
  254. constructPath: 91
  255. };
  256. var verbosity = VERBOSITY_LEVELS.warnings;
  257. function setVerbosityLevel(level) {
  258. verbosity = level;
  259. }
  260. function getVerbosityLevel() {
  261. return verbosity;
  262. }
  263. // A notice for devs. These are good for things that are helpful to devs, such
  264. // as warning that Workers were disabled, which is important to devs but not
  265. // end users.
  266. function info(msg) {
  267. if (verbosity >= VERBOSITY_LEVELS.infos) {
  268. console.log('Info: ' + msg);
  269. }
  270. }
  271. // Non-fatal warnings.
  272. function warn(msg) {
  273. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  274. console.log('Warning: ' + msg);
  275. }
  276. }
  277. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  278. function deprecated(details) {
  279. console.log('Deprecated API usage: ' + details);
  280. }
  281. // Fatal errors that should trigger the fallback UI and halt execution by
  282. // throwing an exception.
  283. function error(msg) {
  284. if (verbosity >= VERBOSITY_LEVELS.errors) {
  285. console.log('Error: ' + msg);
  286. console.log(backtrace());
  287. }
  288. throw new Error(msg);
  289. }
  290. function backtrace() {
  291. try {
  292. throw new Error();
  293. } catch (e) {
  294. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  295. }
  296. }
  297. function assert(cond, msg) {
  298. if (!cond) {
  299. error(msg);
  300. }
  301. }
  302. var UNSUPPORTED_FEATURES = {
  303. unknown: 'unknown',
  304. forms: 'forms',
  305. javaScript: 'javaScript',
  306. smask: 'smask',
  307. shadingPattern: 'shadingPattern',
  308. font: 'font'
  309. };
  310. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  311. function isSameOrigin(baseUrl, otherUrl) {
  312. try {
  313. var base = new URL(baseUrl);
  314. if (!base.origin || base.origin === 'null') {
  315. return false; // non-HTTP url
  316. }
  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, { value: value,
  348. enumerable: true,
  349. configurable: true,
  350. writable: false });
  351. return value;
  352. }
  353. function getLookupTableFactory(initializer) {
  354. var lookup;
  355. return function () {
  356. if (initializer) {
  357. lookup = Object.create(null);
  358. initializer(lookup);
  359. initializer = null;
  360. }
  361. return lookup;
  362. };
  363. }
  364. var PasswordResponses = {
  365. NEED_PASSWORD: 1,
  366. INCORRECT_PASSWORD: 2
  367. };
  368. var PasswordException = (function PasswordExceptionClosure() {
  369. function PasswordException(msg, code) {
  370. this.name = 'PasswordException';
  371. this.message = msg;
  372. this.code = code;
  373. }
  374. PasswordException.prototype = new Error();
  375. PasswordException.constructor = PasswordException;
  376. return PasswordException;
  377. })();
  378. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  379. function UnknownErrorException(msg, details) {
  380. this.name = 'UnknownErrorException';
  381. this.message = msg;
  382. this.details = details;
  383. }
  384. UnknownErrorException.prototype = new Error();
  385. UnknownErrorException.constructor = UnknownErrorException;
  386. return UnknownErrorException;
  387. })();
  388. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  389. function InvalidPDFException(msg) {
  390. this.name = 'InvalidPDFException';
  391. this.message = msg;
  392. }
  393. InvalidPDFException.prototype = new Error();
  394. InvalidPDFException.constructor = InvalidPDFException;
  395. return InvalidPDFException;
  396. })();
  397. var MissingPDFException = (function MissingPDFExceptionClosure() {
  398. function MissingPDFException(msg) {
  399. this.name = 'MissingPDFException';
  400. this.message = msg;
  401. }
  402. MissingPDFException.prototype = new Error();
  403. MissingPDFException.constructor = MissingPDFException;
  404. return MissingPDFException;
  405. })();
  406. var UnexpectedResponseException =
  407. (function UnexpectedResponseExceptionClosure() {
  408. function UnexpectedResponseException(msg, status) {
  409. this.name = 'UnexpectedResponseException';
  410. this.message = msg;
  411. this.status = status;
  412. }
  413. UnexpectedResponseException.prototype = new Error();
  414. UnexpectedResponseException.constructor = UnexpectedResponseException;
  415. return UnexpectedResponseException;
  416. })();
  417. var NotImplementedException = (function NotImplementedExceptionClosure() {
  418. function NotImplementedException(msg) {
  419. this.message = msg;
  420. }
  421. NotImplementedException.prototype = new Error();
  422. NotImplementedException.prototype.name = 'NotImplementedException';
  423. NotImplementedException.constructor = NotImplementedException;
  424. return NotImplementedException;
  425. })();
  426. var MissingDataException = (function MissingDataExceptionClosure() {
  427. function MissingDataException(begin, end) {
  428. this.begin = begin;
  429. this.end = end;
  430. this.message = 'Missing data [' + begin + ', ' + end + ')';
  431. }
  432. MissingDataException.prototype = new Error();
  433. MissingDataException.prototype.name = 'MissingDataException';
  434. MissingDataException.constructor = MissingDataException;
  435. return MissingDataException;
  436. })();
  437. var XRefParseException = (function XRefParseExceptionClosure() {
  438. function XRefParseException(msg) {
  439. this.message = msg;
  440. }
  441. XRefParseException.prototype = new Error();
  442. XRefParseException.prototype.name = 'XRefParseException';
  443. XRefParseException.constructor = XRefParseException;
  444. return XRefParseException;
  445. })();
  446. var NullCharactersRegExp = /\x00/g;
  447. function removeNullCharacters(str) {
  448. if (typeof str !== 'string') {
  449. warn('The argument for removeNullCharacters must be a string.');
  450. return str;
  451. }
  452. return str.replace(NullCharactersRegExp, '');
  453. }
  454. function bytesToString(bytes) {
  455. assert(bytes !== null && typeof bytes === 'object' &&
  456. 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,
  528. (value >> 8) & 0xff, value & 0xff);
  529. }
  530. function log2(x) {
  531. var n = 1, i = 0;
  532. while (x > n) {
  533. n <<= 1;
  534. i++;
  535. }
  536. return i;
  537. }
  538. function readInt8(data, start) {
  539. return (data[start] << 24) >> 24;
  540. }
  541. function readUint16(data, offset) {
  542. return (data[offset] << 8) | data[offset + 1];
  543. }
  544. function readUint32(data, offset) {
  545. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  546. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  547. }
  548. // Lazy test the endianness of the platform
  549. // NOTE: This will be 'true' for simulated TypedArrays
  550. function isLittleEndian() {
  551. var buffer8 = new Uint8Array(2);
  552. buffer8[0] = 1;
  553. var buffer16 = new Uint16Array(buffer8.buffer);
  554. return (buffer16[0] === 1);
  555. }
  556. // Checks if it's possible to eval JS expressions.
  557. function isEvalSupported() {
  558. try {
  559. /* jshint evil: true */
  560. new Function('');
  561. return true;
  562. } catch (e) {
  563. return false;
  564. }
  565. }
  566. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  567. function Uint32ArrayView(buffer, length) {
  568. this.buffer = buffer;
  569. this.byteLength = buffer.length;
  570. this.length = length === undefined ? (this.byteLength >> 2) : length;
  571. ensureUint32ArrayViewProps(this.length);
  572. }
  573. Uint32ArrayView.prototype = Object.create(null);
  574. var uint32ArrayViewSetters = 0;
  575. function createUint32ArrayProp(index) {
  576. return {
  577. get: function () {
  578. var buffer = this.buffer, offset = index << 2;
  579. return (buffer[offset] | (buffer[offset + 1] << 8) |
  580. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  581. },
  582. set: function (value) {
  583. var buffer = this.buffer, offset = index << 2;
  584. buffer[offset] = value & 255;
  585. buffer[offset + 1] = (value >> 8) & 255;
  586. buffer[offset + 2] = (value >> 16) & 255;
  587. buffer[offset + 3] = (value >>> 24) & 255;
  588. }
  589. };
  590. }
  591. function ensureUint32ArrayViewProps(length) {
  592. while (uint32ArrayViewSetters < length) {
  593. Object.defineProperty(Uint32ArrayView.prototype,
  594. uint32ArrayViewSetters,
  595. createUint32ArrayProp(uint32ArrayViewSetters));
  596. uint32ArrayViewSetters++;
  597. }
  598. }
  599. return Uint32ArrayView;
  600. })();
  601. exports.Uint32ArrayView = Uint32ArrayView;
  602. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  603. var Util = (function UtilClosure() {
  604. function Util() {}
  605. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  606. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  607. // creating many intermediate strings.
  608. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  609. rgbBuf[1] = r;
  610. rgbBuf[3] = g;
  611. rgbBuf[5] = b;
  612. return rgbBuf.join('');
  613. };
  614. // Concatenates two transformation matrices together and returns the result.
  615. Util.transform = function Util_transform(m1, m2) {
  616. return [
  617. m1[0] * m2[0] + m1[2] * m2[1],
  618. m1[1] * m2[0] + m1[3] * m2[1],
  619. m1[0] * m2[2] + m1[2] * m2[3],
  620. m1[1] * m2[2] + m1[3] * m2[3],
  621. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  622. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  623. ];
  624. };
  625. // For 2d affine transforms
  626. Util.applyTransform = function Util_applyTransform(p, m) {
  627. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  628. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  629. return [xt, yt];
  630. };
  631. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  632. var d = m[0] * m[3] - m[1] * m[2];
  633. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  634. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  635. return [xt, yt];
  636. };
  637. // Applies the transform to the rectangle and finds the minimum axially
  638. // aligned bounding box.
  639. Util.getAxialAlignedBoundingBox =
  640. function Util_getAxialAlignedBoundingBox(r, m) {
  641. var p1 = Util.applyTransform(r, m);
  642. var p2 = Util.applyTransform(r.slice(2, 4), m);
  643. var p3 = Util.applyTransform([r[0], r[3]], m);
  644. var p4 = Util.applyTransform([r[2], r[1]], m);
  645. return [
  646. Math.min(p1[0], p2[0], p3[0], p4[0]),
  647. Math.min(p1[1], p2[1], p3[1], p4[1]),
  648. Math.max(p1[0], p2[0], p3[0], p4[0]),
  649. Math.max(p1[1], p2[1], p3[1], p4[1])
  650. ];
  651. };
  652. Util.inverseTransform = function Util_inverseTransform(m) {
  653. var d = m[0] * m[3] - m[1] * m[2];
  654. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  655. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  656. };
  657. // Apply a generic 3d matrix M on a 3-vector v:
  658. // | a b c | | X |
  659. // | d e f | x | Y |
  660. // | g h i | | Z |
  661. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  662. // with v as [X,Y,Z]
  663. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  664. return [
  665. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  666. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  667. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  668. ];
  669. };
  670. // This calculation uses Singular Value Decomposition.
  671. // The SVD can be represented with formula A = USV. We are interested in the
  672. // matrix S here because it represents the scale values.
  673. Util.singularValueDecompose2dScale =
  674. function Util_singularValueDecompose2dScale(m) {
  675. var transpose = [m[0], m[2], m[1], m[3]];
  676. // Multiply matrix m with its transpose.
  677. var a = m[0] * transpose[0] + m[1] * transpose[2];
  678. var b = m[0] * transpose[1] + m[1] * transpose[3];
  679. var c = m[2] * transpose[0] + m[3] * transpose[2];
  680. var d = m[2] * transpose[1] + m[3] * transpose[3];
  681. // Solve the second degree polynomial to get roots.
  682. var first = (a + d) / 2;
  683. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  684. var sx = first + second || 1;
  685. var sy = first - second || 1;
  686. // Scale values are the square roots of the eigenvalues.
  687. return [Math.sqrt(sx), Math.sqrt(sy)];
  688. };
  689. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  690. // For coordinate systems whose origin lies in the bottom-left, this
  691. // means normalization to (BL,TR) ordering. For systems with origin in the
  692. // top-left, this means (TL,BR) ordering.
  693. Util.normalizeRect = function Util_normalizeRect(rect) {
  694. var r = rect.slice(0); // clone rect
  695. if (rect[0] > rect[2]) {
  696. r[0] = rect[2];
  697. r[2] = rect[0];
  698. }
  699. if (rect[1] > rect[3]) {
  700. r[1] = rect[3];
  701. r[3] = rect[1];
  702. }
  703. return r;
  704. };
  705. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  706. // intersection of rect1 and rect2. If no intersection, returns 'false'
  707. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  708. Util.intersect = function Util_intersect(rect1, rect2) {
  709. function compare(a, b) {
  710. return a - b;
  711. }
  712. // Order points along the axes
  713. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  714. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  715. result = [];
  716. rect1 = Util.normalizeRect(rect1);
  717. rect2 = Util.normalizeRect(rect2);
  718. // X: first and second points belong to different rectangles?
  719. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  720. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  721. // Intersection must be between second and third points
  722. result[0] = orderedX[1];
  723. result[2] = orderedX[2];
  724. } else {
  725. return false;
  726. }
  727. // Y: first and second points belong to different rectangles?
  728. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  729. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  730. // Intersection must be between second and third points
  731. result[1] = orderedY[1];
  732. result[3] = orderedY[2];
  733. } else {
  734. return false;
  735. }
  736. return result;
  737. };
  738. Util.sign = function Util_sign(num) {
  739. return num < 0 ? -1 : 1;
  740. };
  741. var ROMAN_NUMBER_MAP = [
  742. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  743. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  744. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  745. ];
  746. /**
  747. * Converts positive integers to (upper case) Roman numerals.
  748. * @param {integer} number - The number that should be converted.
  749. * @param {boolean} lowerCase - Indicates if the result should be converted
  750. * to lower case letters. The default is false.
  751. * @return {string} The resulting Roman number.
  752. */
  753. Util.toRoman = function Util_toRoman(number, lowerCase) {
  754. assert(isInt(number) && number > 0,
  755. 'The number should be a positive integer.');
  756. var pos, romanBuf = [];
  757. // Thousands
  758. while (number >= 1000) {
  759. number -= 1000;
  760. romanBuf.push('M');
  761. }
  762. // Hundreds
  763. pos = (number / 100) | 0;
  764. number %= 100;
  765. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  766. // Tens
  767. pos = (number / 10) | 0;
  768. number %= 10;
  769. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  770. // Ones
  771. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  772. var romanStr = romanBuf.join('');
  773. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  774. };
  775. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  776. Array.prototype.push.apply(arr1, arr2);
  777. };
  778. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  779. Array.prototype.unshift.apply(arr1, arr2);
  780. };
  781. Util.extendObj = function extendObj(obj1, obj2) {
  782. for (var key in obj2) {
  783. obj1[key] = obj2[key];
  784. }
  785. };
  786. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  787. name) {
  788. while (dict && !dict.has(name)) {
  789. dict = dict.get('Parent');
  790. }
  791. if (!dict) {
  792. return null;
  793. }
  794. return dict.get(name);
  795. };
  796. Util.inherit = function Util_inherit(sub, base, prototype) {
  797. sub.prototype = Object.create(base.prototype);
  798. sub.prototype.constructor = sub;
  799. for (var prop in prototype) {
  800. sub.prototype[prop] = prototype[prop];
  801. }
  802. };
  803. Util.loadScript = function Util_loadScript(src, callback) {
  804. var script = document.createElement('script');
  805. var loaded = false;
  806. script.setAttribute('src', src);
  807. if (callback) {
  808. script.onload = function() {
  809. if (!loaded) {
  810. callback();
  811. }
  812. loaded = true;
  813. };
  814. }
  815. document.getElementsByTagName('head')[0].appendChild(script);
  816. };
  817. return Util;
  818. })();
  819. /**
  820. * PDF page viewport created based on scale, rotation and offset.
  821. * @class
  822. * @alias PageViewport
  823. */
  824. var PageViewport = (function PageViewportClosure() {
  825. /**
  826. * @constructor
  827. * @private
  828. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  829. * @param scale {number} scale of the viewport.
  830. * @param rotation {number} rotations of the viewport in degrees.
  831. * @param offsetX {number} offset X
  832. * @param offsetY {number} offset Y
  833. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  834. */
  835. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  836. this.viewBox = viewBox;
  837. this.scale = scale;
  838. this.rotation = rotation;
  839. this.offsetX = offsetX;
  840. this.offsetY = offsetY;
  841. // creating transform to convert pdf coordinate system to the normal
  842. // canvas like coordinates taking in account scale and rotation
  843. var centerX = (viewBox[2] + viewBox[0]) / 2;
  844. var centerY = (viewBox[3] + viewBox[1]) / 2;
  845. var rotateA, rotateB, rotateC, rotateD;
  846. rotation = rotation % 360;
  847. rotation = rotation < 0 ? rotation + 360 : rotation;
  848. switch (rotation) {
  849. case 180:
  850. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  851. break;
  852. case 90:
  853. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  854. break;
  855. case 270:
  856. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  857. break;
  858. //case 0:
  859. default:
  860. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  861. break;
  862. }
  863. if (dontFlip) {
  864. rotateC = -rotateC; rotateD = -rotateD;
  865. }
  866. var offsetCanvasX, offsetCanvasY;
  867. var width, height;
  868. if (rotateA === 0) {
  869. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  870. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  871. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  872. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  873. } else {
  874. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  875. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  876. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  877. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  878. }
  879. // creating transform for the following operations:
  880. // translate(-centerX, -centerY), rotate and flip vertically,
  881. // scale, and translate(offsetCanvasX, offsetCanvasY)
  882. this.transform = [
  883. rotateA * scale,
  884. rotateB * scale,
  885. rotateC * scale,
  886. rotateD * scale,
  887. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  888. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  889. ];
  890. this.width = width;
  891. this.height = height;
  892. this.fontScale = scale;
  893. }
  894. PageViewport.prototype = /** @lends PageViewport.prototype */ {
  895. /**
  896. * Clones viewport with additional properties.
  897. * @param args {Object} (optional) If specified, may contain the 'scale' or
  898. * 'rotation' properties to override the corresponding properties in
  899. * the cloned viewport.
  900. * @returns {PageViewport} Cloned viewport.
  901. */
  902. clone: function PageViewPort_clone(args) {
  903. args = args || {};
  904. var scale = 'scale' in args ? args.scale : this.scale;
  905. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  906. return new PageViewport(this.viewBox.slice(), scale, rotation,
  907. this.offsetX, this.offsetY, args.dontFlip);
  908. },
  909. /**
  910. * Converts PDF point to the viewport coordinates. For examples, useful for
  911. * converting PDF location into canvas pixel coordinates.
  912. * @param x {number} X coordinate.
  913. * @param y {number} Y coordinate.
  914. * @returns {Object} Object that contains 'x' and 'y' properties of the
  915. * point in the viewport coordinate space.
  916. * @see {@link convertToPdfPoint}
  917. * @see {@link convertToViewportRectangle}
  918. */
  919. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  920. return Util.applyTransform([x, y], this.transform);
  921. },
  922. /**
  923. * Converts PDF rectangle to the viewport coordinates.
  924. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  925. * @returns {Array} Contains corresponding coordinates of the rectangle
  926. * in the viewport coordinate space.
  927. * @see {@link convertToViewportPoint}
  928. */
  929. convertToViewportRectangle:
  930. function PageViewport_convertToViewportRectangle(rect) {
  931. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  932. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  933. return [tl[0], tl[1], br[0], br[1]];
  934. },
  935. /**
  936. * Converts viewport coordinates to the PDF location. For examples, useful
  937. * for converting canvas pixel location into PDF one.
  938. * @param x {number} X coordinate.
  939. * @param y {number} Y coordinate.
  940. * @returns {Object} Object that contains 'x' and 'y' properties of the
  941. * point in the PDF coordinate space.
  942. * @see {@link convertToViewportPoint}
  943. */
  944. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  945. return Util.applyInverseTransform([x, y], this.transform);
  946. }
  947. };
  948. return PageViewport;
  949. })();
  950. var PDFStringTranslateTable = [
  951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  952. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  957. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  958. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  959. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  960. ];
  961. function stringToPDFString(str) {
  962. var i, n = str.length, strBuf = [];
  963. if (str[0] === '\xFE' && str[1] === '\xFF') {
  964. // UTF16BE BOM
  965. for (i = 2; i < n; i += 2) {
  966. strBuf.push(String.fromCharCode(
  967. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  968. }
  969. } else {
  970. for (i = 0; i < n; ++i) {
  971. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  972. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  973. }
  974. }
  975. return strBuf.join('');
  976. }
  977. function stringToUTF8String(str) {
  978. return decodeURIComponent(escape(str));
  979. }
  980. function utf8StringToString(str) {
  981. return unescape(encodeURIComponent(str));
  982. }
  983. function isEmptyObj(obj) {
  984. for (var key in obj) {
  985. return false;
  986. }
  987. return true;
  988. }
  989. function isBool(v) {
  990. return typeof v === 'boolean';
  991. }
  992. function isInt(v) {
  993. return typeof v === 'number' && ((v | 0) === v);
  994. }
  995. function isNum(v) {
  996. return typeof v === 'number';
  997. }
  998. function isString(v) {
  999. return typeof v === 'string';
  1000. }
  1001. function isArray(v) {
  1002. return v instanceof Array;
  1003. }
  1004. function isArrayBuffer(v) {
  1005. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1006. }
  1007. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1008. function isSpace(ch) {
  1009. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  1010. }
  1011. /**
  1012. * Promise Capability object.
  1013. *
  1014. * @typedef {Object} PromiseCapability
  1015. * @property {Promise} promise - A promise object.
  1016. * @property {function} resolve - Fulfills the promise.
  1017. * @property {function} reject - Rejects the promise.
  1018. */
  1019. /**
  1020. * Creates a promise capability object.
  1021. * @alias createPromiseCapability
  1022. *
  1023. * @return {PromiseCapability} A capability object contains:
  1024. * - a Promise, resolve and reject methods.
  1025. */
  1026. function createPromiseCapability() {
  1027. var capability = {};
  1028. capability.promise = new Promise(function (resolve, reject) {
  1029. capability.resolve = resolve;
  1030. capability.reject = reject;
  1031. });
  1032. return capability;
  1033. }
  1034. /**
  1035. * Polyfill for Promises:
  1036. * The following promise implementation tries to generally implement the
  1037. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1038. * - There currently isn't a separate deferred and promise object.
  1039. * - Unhandled rejections eventually show an error if they aren't handled.
  1040. *
  1041. * Based off of the work in:
  1042. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1043. */
  1044. (function PromiseClosure() {
  1045. if (globalScope.Promise) {
  1046. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1047. if (typeof globalScope.Promise.all !== 'function') {
  1048. globalScope.Promise.all = function (iterable) {
  1049. var count = 0, results = [], resolve, reject;
  1050. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1051. resolve = resolve_;
  1052. reject = reject_;
  1053. });
  1054. iterable.forEach(function (p, i) {
  1055. count++;
  1056. p.then(function (result) {
  1057. results[i] = result;
  1058. count--;
  1059. if (count === 0) {
  1060. resolve(results);
  1061. }
  1062. }, reject);
  1063. });
  1064. if (count === 0) {
  1065. resolve(results);
  1066. }
  1067. return promise;
  1068. };
  1069. }
  1070. if (typeof globalScope.Promise.resolve !== 'function') {
  1071. globalScope.Promise.resolve = function (value) {
  1072. return new globalScope.Promise(function (resolve) { resolve(value); });
  1073. };
  1074. }
  1075. if (typeof globalScope.Promise.reject !== 'function') {
  1076. globalScope.Promise.reject = function (reason) {
  1077. return new globalScope.Promise(function (resolve, reject) {
  1078. reject(reason);
  1079. });
  1080. };
  1081. }
  1082. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1083. globalScope.Promise.prototype.catch = function (onReject) {
  1084. return globalScope.Promise.prototype.then(undefined, onReject);
  1085. };
  1086. }
  1087. return;
  1088. }
  1089. var STATUS_PENDING = 0;
  1090. var STATUS_RESOLVED = 1;
  1091. var STATUS_REJECTED = 2;
  1092. // In an attempt to avoid silent exceptions, unhandled rejections are
  1093. // tracked and if they aren't handled in a certain amount of time an
  1094. // error is logged.
  1095. var REJECTION_TIMEOUT = 500;
  1096. var HandlerManager = {
  1097. handlers: [],
  1098. running: false,
  1099. unhandledRejections: [],
  1100. pendingRejectionCheck: false,
  1101. scheduleHandlers: function scheduleHandlers(promise) {
  1102. if (promise._status === STATUS_PENDING) {
  1103. return;
  1104. }
  1105. this.handlers = this.handlers.concat(promise._handlers);
  1106. promise._handlers = [];
  1107. if (this.running) {
  1108. return;
  1109. }
  1110. this.running = true;
  1111. setTimeout(this.runHandlers.bind(this), 0);
  1112. },
  1113. runHandlers: function runHandlers() {
  1114. var RUN_TIMEOUT = 1; // ms
  1115. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1116. while (this.handlers.length > 0) {
  1117. var handler = this.handlers.shift();
  1118. var nextStatus = handler.thisPromise._status;
  1119. var nextValue = handler.thisPromise._value;
  1120. try {
  1121. if (nextStatus === STATUS_RESOLVED) {
  1122. if (typeof handler.onResolve === 'function') {
  1123. nextValue = handler.onResolve(nextValue);
  1124. }
  1125. } else if (typeof handler.onReject === 'function') {
  1126. nextValue = handler.onReject(nextValue);
  1127. nextStatus = STATUS_RESOLVED;
  1128. if (handler.thisPromise._unhandledRejection) {
  1129. this.removeUnhandeledRejection(handler.thisPromise);
  1130. }
  1131. }
  1132. } catch (ex) {
  1133. nextStatus = STATUS_REJECTED;
  1134. nextValue = ex;
  1135. }
  1136. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1137. if (Date.now() >= timeoutAt) {
  1138. break;
  1139. }
  1140. }
  1141. if (this.handlers.length > 0) {
  1142. setTimeout(this.runHandlers.bind(this), 0);
  1143. return;
  1144. }
  1145. this.running = false;
  1146. },
  1147. addUnhandledRejection: function addUnhandledRejection(promise) {
  1148. this.unhandledRejections.push({
  1149. promise: promise,
  1150. time: Date.now()
  1151. });
  1152. this.scheduleRejectionCheck();
  1153. },
  1154. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1155. promise._unhandledRejection = false;
  1156. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1157. if (this.unhandledRejections[i].promise === promise) {
  1158. this.unhandledRejections.splice(i);
  1159. i--;
  1160. }
  1161. }
  1162. },
  1163. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1164. if (this.pendingRejectionCheck) {
  1165. return;
  1166. }
  1167. this.pendingRejectionCheck = true;
  1168. setTimeout(function rejectionCheck() {
  1169. this.pendingRejectionCheck = false;
  1170. var now = Date.now();
  1171. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1172. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1173. var unhandled = this.unhandledRejections[i].promise._value;
  1174. var msg = 'Unhandled rejection: ' + unhandled;
  1175. if (unhandled.stack) {
  1176. msg += '\n' + unhandled.stack;
  1177. }
  1178. warn(msg);
  1179. this.unhandledRejections.splice(i);
  1180. i--;
  1181. }
  1182. }
  1183. if (this.unhandledRejections.length) {
  1184. this.scheduleRejectionCheck();
  1185. }
  1186. }.bind(this), REJECTION_TIMEOUT);
  1187. }
  1188. };
  1189. function Promise(resolver) {
  1190. this._status = STATUS_PENDING;
  1191. this._handlers = [];
  1192. try {
  1193. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1194. } catch (e) {
  1195. this._reject(e);
  1196. }
  1197. }
  1198. /**
  1199. * Builds a promise that is resolved when all the passed in promises are
  1200. * resolved.
  1201. * @param {array} promises array of data and/or promises to wait for.
  1202. * @return {Promise} New dependent promise.
  1203. */
  1204. Promise.all = function Promise_all(promises) {
  1205. var resolveAll, rejectAll;
  1206. var deferred = new Promise(function (resolve, reject) {
  1207. resolveAll = resolve;
  1208. rejectAll = reject;
  1209. });
  1210. var unresolved = promises.length;
  1211. var results = [];
  1212. if (unresolved === 0) {
  1213. resolveAll(results);
  1214. return deferred;
  1215. }
  1216. function reject(reason) {
  1217. if (deferred._status === STATUS_REJECTED) {
  1218. return;
  1219. }
  1220. results = [];
  1221. rejectAll(reason);
  1222. }
  1223. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1224. var promise = promises[i];
  1225. var resolve = (function(i) {
  1226. return function(value) {
  1227. if (deferred._status === STATUS_REJECTED) {
  1228. return;
  1229. }
  1230. results[i] = value;
  1231. unresolved--;
  1232. if (unresolved === 0) {
  1233. resolveAll(results);
  1234. }
  1235. };
  1236. })(i);
  1237. if (Promise.isPromise(promise)) {
  1238. promise.then(resolve, reject);
  1239. } else {
  1240. resolve(promise);
  1241. }
  1242. }
  1243. return deferred;
  1244. };
  1245. /**
  1246. * Checks if the value is likely a promise (has a 'then' function).
  1247. * @return {boolean} true if value is thenable
  1248. */
  1249. Promise.isPromise = function Promise_isPromise(value) {
  1250. return value && typeof value.then === 'function';
  1251. };
  1252. /**
  1253. * Creates resolved promise
  1254. * @param value resolve value
  1255. * @returns {Promise}
  1256. */
  1257. Promise.resolve = function Promise_resolve(value) {
  1258. return new Promise(function (resolve) { resolve(value); });
  1259. };
  1260. /**
  1261. * Creates rejected promise
  1262. * @param reason rejection value
  1263. * @returns {Promise}
  1264. */
  1265. Promise.reject = function Promise_reject(reason) {
  1266. return new Promise(function (resolve, reject) { reject(reason); });
  1267. };
  1268. Promise.prototype = {
  1269. _status: null,
  1270. _value: null,
  1271. _handlers: null,
  1272. _unhandledRejection: null,
  1273. _updateStatus: function Promise__updateStatus(status, value) {
  1274. if (this._status === STATUS_RESOLVED ||
  1275. this._status === STATUS_REJECTED) {
  1276. return;
  1277. }
  1278. if (status === STATUS_RESOLVED &&
  1279. Promise.isPromise(value)) {
  1280. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1281. this._updateStatus.bind(this, STATUS_REJECTED));
  1282. return;
  1283. }
  1284. this._status = status;
  1285. this._value = value;
  1286. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1287. this._unhandledRejection = true;
  1288. HandlerManager.addUnhandledRejection(this);
  1289. }
  1290. HandlerManager.scheduleHandlers(this);
  1291. },
  1292. _resolve: function Promise_resolve(value) {
  1293. this._updateStatus(STATUS_RESOLVED, value);
  1294. },
  1295. _reject: function Promise_reject(reason) {
  1296. this._updateStatus(STATUS_REJECTED, reason);
  1297. },
  1298. then: function Promise_then(onResolve, onReject) {
  1299. var nextPromise = new Promise(function (resolve, reject) {
  1300. this.resolve = resolve;
  1301. this.reject = reject;
  1302. });
  1303. this._handlers.push({
  1304. thisPromise: this,
  1305. onResolve: onResolve,
  1306. onReject: onReject,
  1307. nextPromise: nextPromise
  1308. });
  1309. HandlerManager.scheduleHandlers(this);
  1310. return nextPromise;
  1311. },
  1312. catch: function Promise_catch(onReject) {
  1313. return this.then(undefined, onReject);
  1314. }
  1315. };
  1316. globalScope.Promise = Promise;
  1317. })();
  1318. (function WeakMapClosure() {
  1319. if (globalScope.WeakMap) {
  1320. return;
  1321. }
  1322. var id = 0;
  1323. function WeakMap() {
  1324. this.id = '$weakmap' + (id++);
  1325. }
  1326. WeakMap.prototype = {
  1327. has: function(obj) {
  1328. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1329. },
  1330. get: function(obj, defaultValue) {
  1331. return this.has(obj) ? obj[this.id] : defaultValue;
  1332. },
  1333. set: function(obj, value) {
  1334. Object.defineProperty(obj, this.id, {
  1335. value: value,
  1336. enumerable: false,
  1337. configurable: true
  1338. });
  1339. },
  1340. delete: function(obj) {
  1341. delete obj[this.id];
  1342. }
  1343. };
  1344. globalScope.WeakMap = WeakMap;
  1345. })();
  1346. var StatTimer = (function StatTimerClosure() {
  1347. function rpad(str, pad, length) {
  1348. while (str.length < length) {
  1349. str += pad;
  1350. }
  1351. return str;
  1352. }
  1353. function StatTimer() {
  1354. this.started = Object.create(null);
  1355. this.times = [];
  1356. this.enabled = true;
  1357. }
  1358. StatTimer.prototype = {
  1359. time: function StatTimer_time(name) {
  1360. if (!this.enabled) {
  1361. return;
  1362. }
  1363. if (name in this.started) {
  1364. warn('Timer is already running for ' + name);
  1365. }
  1366. this.started[name] = Date.now();
  1367. },
  1368. timeEnd: function StatTimer_timeEnd(name) {
  1369. if (!this.enabled) {
  1370. return;
  1371. }
  1372. if (!(name in this.started)) {
  1373. warn('Timer has not been started for ' + name);
  1374. }
  1375. this.times.push({
  1376. 'name': name,
  1377. 'start': this.started[name],
  1378. 'end': Date.now()
  1379. });
  1380. // Remove timer from started so it can be called again.
  1381. delete this.started[name];
  1382. },
  1383. toString: function StatTimer_toString() {
  1384. var i, ii;
  1385. var times = this.times;
  1386. var out = '';
  1387. // Find the longest name for padding purposes.
  1388. var longest = 0;
  1389. for (i = 0, ii = times.length; i < ii; ++i) {
  1390. var name = times[i]['name'];
  1391. if (name.length > longest) {
  1392. longest = name.length;
  1393. }
  1394. }
  1395. for (i = 0, ii = times.length; i < ii; ++i) {
  1396. var span = times[i];
  1397. var duration = span.end - span.start;
  1398. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1399. }
  1400. return out;
  1401. }
  1402. };
  1403. return StatTimer;
  1404. })();
  1405. var createBlob = function createBlob(data, contentType) {
  1406. if (typeof Blob !== 'undefined') {
  1407. return new Blob([data], { type: contentType });
  1408. }
  1409. warn('The "Blob" constructor is not supported.');
  1410. };
  1411. var createObjectURL = (function createObjectURLClosure() {
  1412. // Blob/createObjectURL is not available, falling back to data schema.
  1413. var digits =
  1414. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1415. return function createObjectURL(data, contentType, forceDataSchema) {
  1416. if (!forceDataSchema &&
  1417. typeof URL !== 'undefined' && URL.createObjectURL) {
  1418. var blob = createBlob(data, contentType);
  1419. return URL.createObjectURL(blob);
  1420. }
  1421. var buffer = 'data:' + contentType + ';base64,';
  1422. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1423. var b1 = data[i] & 0xFF;
  1424. var b2 = data[i + 1] & 0xFF;
  1425. var b3 = data[i + 2] & 0xFF;
  1426. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1427. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1428. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1429. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1430. }
  1431. return buffer;
  1432. };
  1433. })();
  1434. function MessageHandler(sourceName, targetName, comObj) {
  1435. this.sourceName = sourceName;
  1436. this.targetName = targetName;
  1437. this.comObj = comObj;
  1438. this.callbackIndex = 1;
  1439. this.postMessageTransfers = true;
  1440. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1441. var ah = this.actionHandler = Object.create(null);
  1442. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1443. var data = event.data;
  1444. if (data.targetName !== this.sourceName) {
  1445. return;
  1446. }
  1447. if (data.isReply) {
  1448. var callbackId = data.callbackId;
  1449. if (data.callbackId in callbacksCapabilities) {
  1450. var callback = callbacksCapabilities[callbackId];
  1451. delete callbacksCapabilities[callbackId];
  1452. if ('error' in data) {
  1453. callback.reject(data.error);
  1454. } else {
  1455. callback.resolve(data.data);
  1456. }
  1457. } else {
  1458. error('Cannot resolve callback ' + callbackId);
  1459. }
  1460. } else if (data.action in ah) {
  1461. var action = ah[data.action];
  1462. if (data.callbackId) {
  1463. var sourceName = this.sourceName;
  1464. var targetName = data.sourceName;
  1465. Promise.resolve().then(function () {
  1466. return action[0].call(action[1], data.data);
  1467. }).then(function (result) {
  1468. comObj.postMessage({
  1469. sourceName: sourceName,
  1470. targetName: targetName,
  1471. isReply: true,
  1472. callbackId: data.callbackId,
  1473. data: result
  1474. });
  1475. }, function (reason) {
  1476. if (reason instanceof Error) {
  1477. // Serialize error to avoid "DataCloneError"
  1478. reason = reason + '';
  1479. }
  1480. comObj.postMessage({
  1481. sourceName: sourceName,
  1482. targetName: targetName,
  1483. isReply: true,
  1484. callbackId: data.callbackId,
  1485. error: reason
  1486. });
  1487. });
  1488. } else {
  1489. action[0].call(action[1], data.data);
  1490. }
  1491. } else {
  1492. error('Unknown action from worker: ' + data.action);
  1493. }
  1494. }.bind(this);
  1495. comObj.addEventListener('message', this._onComObjOnMessage);
  1496. }
  1497. MessageHandler.prototype = {
  1498. on: function messageHandlerOn(actionName, handler, scope) {
  1499. var ah = this.actionHandler;
  1500. if (ah[actionName]) {
  1501. error('There is already an actionName called "' + actionName + '"');
  1502. }
  1503. ah[actionName] = [handler, scope];
  1504. },
  1505. /**
  1506. * Sends a message to the comObj to invoke the action with the supplied data.
  1507. * @param {String} actionName Action to call.
  1508. * @param {JSON} data JSON data to send.
  1509. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1510. */
  1511. send: function messageHandlerSend(actionName, data, transfers) {
  1512. var message = {
  1513. sourceName: this.sourceName,
  1514. targetName: this.targetName,
  1515. action: actionName,
  1516. data: data
  1517. };
  1518. this.postMessage(message, transfers);
  1519. },
  1520. /**
  1521. * Sends a message to the comObj to invoke the action with the supplied data.
  1522. * Expects that other side will callback with the response.
  1523. * @param {String} actionName Action to call.
  1524. * @param {JSON} data JSON data to send.
  1525. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1526. * @returns {Promise} Promise to be resolved with response data.
  1527. */
  1528. sendWithPromise:
  1529. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1530. var callbackId = this.callbackIndex++;
  1531. var message = {
  1532. sourceName: this.sourceName,
  1533. targetName: this.targetName,
  1534. action: actionName,
  1535. data: data,
  1536. callbackId: callbackId
  1537. };
  1538. var capability = createPromiseCapability();
  1539. this.callbacksCapabilities[callbackId] = capability;
  1540. try {
  1541. this.postMessage(message, transfers);
  1542. } catch (e) {
  1543. capability.reject(e);
  1544. }
  1545. return capability.promise;
  1546. },
  1547. /**
  1548. * Sends raw message to the comObj.
  1549. * @private
  1550. * @param message {Object} Raw message.
  1551. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1552. */
  1553. postMessage: function (message, transfers) {
  1554. if (transfers && this.postMessageTransfers) {
  1555. this.comObj.postMessage(message, transfers);
  1556. } else {
  1557. this.comObj.postMessage(message);
  1558. }
  1559. },
  1560. destroy: function () {
  1561. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1562. }
  1563. };
  1564. function loadJpegStream(id, imageUrl, objs) {
  1565. var img = new Image();
  1566. img.onload = (function loadJpegStream_onloadClosure() {
  1567. objs.resolve(id, img);
  1568. });
  1569. img.onerror = (function loadJpegStream_onerrorClosure() {
  1570. objs.resolve(id, null);
  1571. warn('Error during JPEG image loading');
  1572. });
  1573. img.src = imageUrl;
  1574. }
  1575. // Polyfill from https://github.com/Polymer/URL
  1576. /* Any copyright is dedicated to the Public Domain.
  1577. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1578. (function checkURLConstructor(scope) {
  1579. // feature detect for URL constructor
  1580. var hasWorkingUrl = false;
  1581. try {
  1582. if (typeof URL === 'function' &&
  1583. typeof URL.prototype === 'object' &&
  1584. ('origin' in URL.prototype)) {
  1585. var u = new URL('b', 'http://a');
  1586. u.pathname = 'c%20d';
  1587. hasWorkingUrl = u.href === 'http://a/c%20d';
  1588. }
  1589. } catch(e) { }
  1590. if (hasWorkingUrl) {
  1591. return;
  1592. }
  1593. var relative = Object.create(null);
  1594. relative['ftp'] = 21;
  1595. relative['file'] = 0;
  1596. relative['gopher'] = 70;
  1597. relative['http'] = 80;
  1598. relative['https'] = 443;
  1599. relative['ws'] = 80;
  1600. relative['wss'] = 443;
  1601. var relativePathDotMapping = Object.create(null);
  1602. relativePathDotMapping['%2e'] = '.';
  1603. relativePathDotMapping['.%2e'] = '..';
  1604. relativePathDotMapping['%2e.'] = '..';
  1605. relativePathDotMapping['%2e%2e'] = '..';
  1606. function isRelativeScheme(scheme) {
  1607. return relative[scheme] !== undefined;
  1608. }
  1609. function invalid() {
  1610. clear.call(this);
  1611. this._isInvalid = true;
  1612. }
  1613. function IDNAToASCII(h) {
  1614. if ('' === h) {
  1615. invalid.call(this);
  1616. }
  1617. // XXX
  1618. return h.toLowerCase();
  1619. }
  1620. function percentEscape(c) {
  1621. var unicode = c.charCodeAt(0);
  1622. if (unicode > 0x20 &&
  1623. unicode < 0x7F &&
  1624. // " # < > ? `
  1625. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1
  1626. ) {
  1627. return c;
  1628. }
  1629. return encodeURIComponent(c);
  1630. }
  1631. function percentEscapeQuery(c) {
  1632. // XXX This actually needs to encode c using encoding and then
  1633. // convert the bytes one-by-one.
  1634. var unicode = c.charCodeAt(0);
  1635. if (unicode > 0x20 &&
  1636. unicode < 0x7F &&
  1637. // " # < > ` (do not escape '?')
  1638. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1
  1639. ) {
  1640. return c;
  1641. }
  1642. return encodeURIComponent(c);
  1643. }
  1644. var EOF, ALPHA = /[a-zA-Z]/,
  1645. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1646. function parse(input, stateOverride, base) {
  1647. function err(message) {
  1648. errors.push(message);
  1649. }
  1650. var state = stateOverride || 'scheme start',
  1651. cursor = 0,
  1652. buffer = '',
  1653. seenAt = false,
  1654. seenBracket = false,
  1655. errors = [];
  1656. loop: while ((input[cursor - 1] !== EOF || cursor === 0) &&
  1657. !this._isInvalid) {
  1658. var c = input[cursor];
  1659. switch (state) {
  1660. case 'scheme start':
  1661. if (c && ALPHA.test(c)) {
  1662. buffer += c.toLowerCase(); // ASCII-safe
  1663. state = 'scheme';
  1664. } else if (!stateOverride) {
  1665. buffer = '';
  1666. state = 'no scheme';
  1667. continue;
  1668. } else {
  1669. err('Invalid scheme.');
  1670. break loop;
  1671. }
  1672. break;
  1673. case 'scheme':
  1674. if (c && ALPHANUMERIC.test(c)) {
  1675. buffer += c.toLowerCase(); // ASCII-safe
  1676. } else if (':' === c) {
  1677. this._scheme = buffer;
  1678. buffer = '';
  1679. if (stateOverride) {
  1680. break loop;
  1681. }
  1682. if (isRelativeScheme(this._scheme)) {
  1683. this._isRelative = true;
  1684. }
  1685. if ('file' === this._scheme) {
  1686. state = 'relative';
  1687. } else if (this._isRelative && base &&
  1688. base._scheme === this._scheme) {
  1689. state = 'relative or authority';
  1690. } else if (this._isRelative) {
  1691. state = 'authority first slash';
  1692. } else {
  1693. state = 'scheme data';
  1694. }
  1695. } else if (!stateOverride) {
  1696. buffer = '';
  1697. cursor = 0;
  1698. state = 'no scheme';
  1699. continue;
  1700. } else if (EOF === c) {
  1701. break loop;
  1702. } else {
  1703. err('Code point not allowed in scheme: ' + c);
  1704. break loop;
  1705. }
  1706. break;
  1707. case 'scheme data':
  1708. if ('?' === c) {
  1709. this._query = '?';
  1710. state = 'query';
  1711. } else if ('#' === c) {
  1712. this._fragment = '#';
  1713. state = 'fragment';
  1714. } else {
  1715. // XXX error handling
  1716. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1717. this._schemeData += percentEscape(c);
  1718. }
  1719. }
  1720. break;
  1721. case 'no scheme':
  1722. if (!base || !(isRelativeScheme(base._scheme))) {
  1723. err('Missing scheme.');
  1724. invalid.call(this);
  1725. } else {
  1726. state = 'relative';
  1727. continue;
  1728. }
  1729. break;
  1730. case 'relative or authority':
  1731. if ('/' === c && '/' === input[cursor+1]) {
  1732. state = 'authority ignore slashes';
  1733. } else {
  1734. err('Expected /, got: ' + c);
  1735. state = 'relative';
  1736. continue;
  1737. }
  1738. break;
  1739. case 'relative':
  1740. this._isRelative = true;
  1741. if ('file' !== this._scheme) {
  1742. this._scheme = base._scheme;
  1743. }
  1744. if (EOF === c) {
  1745. this._host = base._host;
  1746. this._port = base._port;
  1747. this._path = base._path.slice();
  1748. this._query = base._query;
  1749. this._username = base._username;
  1750. this._password = base._password;
  1751. break loop;
  1752. } else if ('/' === c || '\\' === c) {
  1753. if ('\\' === c) {
  1754. err('\\ is an invalid code point.');
  1755. }
  1756. state = 'relative slash';
  1757. } else if ('?' === c) {
  1758. this._host = base._host;
  1759. this._port = base._port;
  1760. this._path = base._path.slice();
  1761. this._query = '?';
  1762. this._username = base._username;
  1763. this._password = base._password;
  1764. state = 'query';
  1765. } else if ('#' === c) {
  1766. this._host = base._host;
  1767. this._port = base._port;
  1768. this._path = base._path.slice();
  1769. this._query = base._query;
  1770. this._fragment = '#';
  1771. this._username = base._username;
  1772. this._password = base._password;
  1773. state = 'fragment';
  1774. } else {
  1775. var nextC = input[cursor+1];
  1776. var nextNextC = input[cursor+2];
  1777. if ('file' !== this._scheme || !ALPHA.test(c) ||
  1778. (nextC !== ':' && nextC !== '|') ||
  1779. (EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC &&
  1780. '?' !== nextNextC && '#' !== nextNextC)) {
  1781. this._host = base._host;
  1782. this._port = base._port;
  1783. this._username = base._username;
  1784. this._password = base._password;
  1785. this._path = base._path.slice();
  1786. this._path.pop();
  1787. }
  1788. state = 'relative path';
  1789. continue;
  1790. }
  1791. break;
  1792. case 'relative slash':
  1793. if ('/' === c || '\\' === c) {
  1794. if ('\\' === c) {
  1795. err('\\ is an invalid code point.');
  1796. }
  1797. if ('file' === this._scheme) {
  1798. state = 'file host';
  1799. } else {
  1800. state = 'authority ignore slashes';
  1801. }
  1802. } else {
  1803. if ('file' !== this._scheme) {
  1804. this._host = base._host;
  1805. this._port = base._port;
  1806. this._username = base._username;
  1807. this._password = base._password;
  1808. }
  1809. state = 'relative path';
  1810. continue;
  1811. }
  1812. break;
  1813. case 'authority first slash':
  1814. if ('/' === c) {
  1815. state = 'authority second slash';
  1816. } else {
  1817. err('Expected \'/\', got: ' + c);
  1818. state = 'authority ignore slashes';
  1819. continue;
  1820. }
  1821. break;
  1822. case 'authority second slash':
  1823. state = 'authority ignore slashes';
  1824. if ('/' !== c) {
  1825. err('Expected \'/\', got: ' + c);
  1826. continue;
  1827. }
  1828. break;
  1829. case 'authority ignore slashes':
  1830. if ('/' !== c && '\\' !== c) {
  1831. state = 'authority';
  1832. continue;
  1833. } else {
  1834. err('Expected authority, got: ' + c);
  1835. }
  1836. break;
  1837. case 'authority':
  1838. if ('@' === c) {
  1839. if (seenAt) {
  1840. err('@ already seen.');
  1841. buffer += '%40';
  1842. }
  1843. seenAt = true;
  1844. for (var i = 0; i < buffer.length; i++) {
  1845. var cp = buffer[i];
  1846. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  1847. err('Invalid whitespace in authority.');
  1848. continue;
  1849. }
  1850. // XXX check URL code points
  1851. if (':' === cp && null === this._password) {
  1852. this._password = '';
  1853. continue;
  1854. }
  1855. var tempC = percentEscape(cp);
  1856. if (null !== this._password) {
  1857. this._password += tempC;
  1858. } else {
  1859. this._username += tempC;
  1860. }
  1861. }
  1862. buffer = '';
  1863. } else if (EOF === c || '/' === c || '\\' === c ||
  1864. '?' === c || '#' === c) {
  1865. cursor -= buffer.length;
  1866. buffer = '';
  1867. state = 'host';
  1868. continue;
  1869. } else {
  1870. buffer += c;
  1871. }
  1872. break;
  1873. case 'file host':
  1874. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  1875. if (buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1876. (buffer[1] === ':' || buffer[1] === '|')) {
  1877. state = 'relative path';
  1878. } else if (buffer.length === 0) {
  1879. state = 'relative path start';
  1880. } else {
  1881. this._host = IDNAToASCII.call(this, buffer);
  1882. buffer = '';
  1883. state = 'relative path start';
  1884. }
  1885. continue;
  1886. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1887. err('Invalid whitespace in file host.');
  1888. } else {
  1889. buffer += c;
  1890. }
  1891. break;
  1892. case 'host':
  1893. case 'hostname':
  1894. if (':' === c && !seenBracket) {
  1895. // XXX host parsing
  1896. this._host = IDNAToASCII.call(this, buffer);
  1897. buffer = '';
  1898. state = 'port';
  1899. if ('hostname' === stateOverride) {
  1900. break loop;
  1901. }
  1902. } else if (EOF === c || '/' === c ||
  1903. '\\' === c || '?' === c || '#' === c) {
  1904. this._host = IDNAToASCII.call(this, buffer);
  1905. buffer = '';
  1906. state = 'relative path start';
  1907. if (stateOverride) {
  1908. break loop;
  1909. }
  1910. continue;
  1911. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1912. if ('[' === c) {
  1913. seenBracket = true;
  1914. } else if (']' === c) {
  1915. seenBracket = false;
  1916. }
  1917. buffer += c;
  1918. } else {
  1919. err('Invalid code point in host/hostname: ' + c);
  1920. }
  1921. break;
  1922. case 'port':
  1923. if (/[0-9]/.test(c)) {
  1924. buffer += c;
  1925. } else if (EOF === c || '/' === c || '\\' === c ||
  1926. '?' === c || '#' === c || stateOverride) {
  1927. if ('' !== buffer) {
  1928. var temp = parseInt(buffer, 10);
  1929. if (temp !== relative[this._scheme]) {
  1930. this._port = temp + '';
  1931. }
  1932. buffer = '';
  1933. }
  1934. if (stateOverride) {
  1935. break loop;
  1936. }
  1937. state = 'relative path start';
  1938. continue;
  1939. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1940. err('Invalid code point in port: ' + c);
  1941. } else {
  1942. invalid.call(this);
  1943. }
  1944. break;
  1945. case 'relative path start':
  1946. if ('\\' === c) {
  1947. err('\'\\\' not allowed in path.');
  1948. }
  1949. state = 'relative path';
  1950. if ('/' !== c && '\\' !== c) {
  1951. continue;
  1952. }
  1953. break;
  1954. case 'relative path':
  1955. if (EOF === c || '/' === c || '\\' === c ||
  1956. (!stateOverride && ('?' === c || '#' === c))) {
  1957. if ('\\' === c) {
  1958. err('\\ not allowed in relative path.');
  1959. }
  1960. var tmp;
  1961. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1962. buffer = tmp;
  1963. }
  1964. if ('..' === buffer) {
  1965. this._path.pop();
  1966. if ('/' !== c && '\\' !== c) {
  1967. this._path.push('');
  1968. }
  1969. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  1970. this._path.push('');
  1971. } else if ('.' !== buffer) {
  1972. if ('file' === this._scheme && this._path.length === 0 &&
  1973. buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1974. buffer[1] === '|') {
  1975. buffer = buffer[0] + ':';
  1976. }
  1977. this._path.push(buffer);
  1978. }
  1979. buffer = '';
  1980. if ('?' === c) {
  1981. this._query = '?';
  1982. state = 'query';
  1983. } else if ('#' === c) {
  1984. this._fragment = '#';
  1985. state = 'fragment';
  1986. }
  1987. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1988. buffer += percentEscape(c);
  1989. }
  1990. break;
  1991. case 'query':
  1992. if (!stateOverride && '#' === c) {
  1993. this._fragment = '#';
  1994. state = 'fragment';
  1995. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1996. this._query += percentEscapeQuery(c);
  1997. }
  1998. break;
  1999. case 'fragment':
  2000. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2001. this._fragment += c;
  2002. }
  2003. break;
  2004. }
  2005. cursor++;
  2006. }
  2007. }
  2008. function clear() {
  2009. this._scheme = '';
  2010. this._schemeData = '';
  2011. this._username = '';
  2012. this._password = null;
  2013. this._host = '';
  2014. this._port = '';
  2015. this._path = [];
  2016. this._query = '';
  2017. this._fragment = '';
  2018. this._isInvalid = false;
  2019. this._isRelative = false;
  2020. }
  2021. // Does not process domain names or IP addresses.
  2022. // Does not handle encoding for the query parameter.
  2023. function JURL(url, base /* , encoding */) {
  2024. if (base !== undefined && !(base instanceof JURL)) {
  2025. base = new JURL(String(base));
  2026. }
  2027. this._url = url;
  2028. clear.call(this);
  2029. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2030. // encoding = encoding || 'utf-8'
  2031. parse.call(this, input, null, base);
  2032. }
  2033. JURL.prototype = {
  2034. toString: function() {
  2035. return this.href;
  2036. },
  2037. get href() {
  2038. if (this._isInvalid) {
  2039. return this._url;
  2040. }
  2041. var authority = '';
  2042. if ('' !== this._username || null !== this._password) {
  2043. authority = this._username +
  2044. (null !== this._password ? ':' + this._password : '') + '@';
  2045. }
  2046. return this.protocol +
  2047. (this._isRelative ? '//' + authority + this.host : '') +
  2048. this.pathname + this._query + this._fragment;
  2049. },
  2050. set href(href) {
  2051. clear.call(this);
  2052. parse.call(this, href);
  2053. },
  2054. get protocol() {
  2055. return this._scheme + ':';
  2056. },
  2057. set protocol(protocol) {
  2058. if (this._isInvalid) {
  2059. return;
  2060. }
  2061. parse.call(this, protocol + ':', 'scheme start');
  2062. },
  2063. get host() {
  2064. return this._isInvalid ? '' : this._port ?
  2065. this._host + ':' + this._port : this._host;
  2066. },
  2067. set host(host) {
  2068. if (this._isInvalid || !this._isRelative) {
  2069. return;
  2070. }
  2071. parse.call(this, host, 'host');
  2072. },
  2073. get hostname() {
  2074. return this._host;
  2075. },
  2076. set hostname(hostname) {
  2077. if (this._isInvalid || !this._isRelative) {
  2078. return;
  2079. }
  2080. parse.call(this, hostname, 'hostname');
  2081. },
  2082. get port() {
  2083. return this._port;
  2084. },
  2085. set port(port) {
  2086. if (this._isInvalid || !this._isRelative) {
  2087. return;
  2088. }
  2089. parse.call(this, port, 'port');
  2090. },
  2091. get pathname() {
  2092. return this._isInvalid ? '' : this._isRelative ?
  2093. '/' + this._path.join('/') : this._schemeData;
  2094. },
  2095. set pathname(pathname) {
  2096. if (this._isInvalid || !this._isRelative) {
  2097. return;
  2098. }
  2099. this._path = [];
  2100. parse.call(this, pathname, 'relative path start');
  2101. },
  2102. get search() {
  2103. return this._isInvalid || !this._query || '?' === this._query ?
  2104. '' : this._query;
  2105. },
  2106. set search(search) {
  2107. if (this._isInvalid || !this._isRelative) {
  2108. return;
  2109. }
  2110. this._query = '?';
  2111. if ('?' === search[0]) {
  2112. search = search.slice(1);
  2113. }
  2114. parse.call(this, search, 'query');
  2115. },
  2116. get hash() {
  2117. return this._isInvalid || !this._fragment || '#' === this._fragment ?
  2118. '' : this._fragment;
  2119. },
  2120. set hash(hash) {
  2121. if (this._isInvalid) {
  2122. return;
  2123. }
  2124. this._fragment = '#';
  2125. if ('#' === hash[0]) {
  2126. hash = hash.slice(1);
  2127. }
  2128. parse.call(this, hash, 'fragment');
  2129. },
  2130. get origin() {
  2131. var host;
  2132. if (this._isInvalid || !this._scheme) {
  2133. return '';
  2134. }
  2135. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2136. // Gecko throws error for "data://"
  2137. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2138. // Gecko returns String("") for file: mailto:
  2139. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2140. switch (this._scheme) {
  2141. case 'data':
  2142. case 'file':
  2143. case 'javascript':
  2144. case 'mailto':
  2145. return 'null';
  2146. }
  2147. host = this.host;
  2148. if (!host) {
  2149. return '';
  2150. }
  2151. return this._scheme + '://' + host;
  2152. }
  2153. };
  2154. // Copy over the static methods
  2155. var OriginalURL = scope.URL;
  2156. if (OriginalURL) {
  2157. JURL.createObjectURL = function(blob) {
  2158. // IE extension allows a second optional options argument.
  2159. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2160. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2161. };
  2162. JURL.revokeObjectURL = function(url) {
  2163. OriginalURL.revokeObjectURL(url);
  2164. };
  2165. }
  2166. scope.URL = JURL;
  2167. })(globalScope);
  2168. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2169. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2170. exports.OPS = OPS;
  2171. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2172. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2173. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2174. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2175. exports.AnnotationFlag = AnnotationFlag;
  2176. exports.AnnotationType = AnnotationType;
  2177. exports.FontType = FontType;
  2178. exports.ImageKind = ImageKind;
  2179. exports.InvalidPDFException = InvalidPDFException;
  2180. exports.MessageHandler = MessageHandler;
  2181. exports.MissingDataException = MissingDataException;
  2182. exports.MissingPDFException = MissingPDFException;
  2183. exports.NotImplementedException = NotImplementedException;
  2184. exports.PageViewport = PageViewport;
  2185. exports.PasswordException = PasswordException;
  2186. exports.PasswordResponses = PasswordResponses;
  2187. exports.StatTimer = StatTimer;
  2188. exports.StreamType = StreamType;
  2189. exports.TextRenderingMode = TextRenderingMode;
  2190. exports.UnexpectedResponseException = UnexpectedResponseException;
  2191. exports.UnknownErrorException = UnknownErrorException;
  2192. exports.Util = Util;
  2193. exports.XRefParseException = XRefParseException;
  2194. exports.arrayByteLength = arrayByteLength;
  2195. exports.arraysToBytes = arraysToBytes;
  2196. exports.assert = assert;
  2197. exports.bytesToString = bytesToString;
  2198. exports.createBlob = createBlob;
  2199. exports.createPromiseCapability = createPromiseCapability;
  2200. exports.createObjectURL = createObjectURL;
  2201. exports.deprecated = deprecated;
  2202. exports.error = error;
  2203. exports.getLookupTableFactory = getLookupTableFactory;
  2204. exports.getVerbosityLevel = getVerbosityLevel;
  2205. exports.globalScope = globalScope;
  2206. exports.info = info;
  2207. exports.isArray = isArray;
  2208. exports.isArrayBuffer = isArrayBuffer;
  2209. exports.isBool = isBool;
  2210. exports.isEmptyObj = isEmptyObj;
  2211. exports.isInt = isInt;
  2212. exports.isNum = isNum;
  2213. exports.isString = isString;
  2214. exports.isSpace = isSpace;
  2215. exports.isSameOrigin = isSameOrigin;
  2216. exports.isValidUrl = isValidUrl;
  2217. exports.isLittleEndian = isLittleEndian;
  2218. exports.isEvalSupported = isEvalSupported;
  2219. exports.loadJpegStream = loadJpegStream;
  2220. exports.log2 = log2;
  2221. exports.readInt8 = readInt8;
  2222. exports.readUint16 = readUint16;
  2223. exports.readUint32 = readUint32;
  2224. exports.removeNullCharacters = removeNullCharacters;
  2225. exports.setVerbosityLevel = setVerbosityLevel;
  2226. exports.shadow = shadow;
  2227. exports.string32 = string32;
  2228. exports.stringToBytes = stringToBytes;
  2229. exports.stringToPDFString = stringToPDFString;
  2230. exports.stringToUTF8String = stringToUTF8String;
  2231. exports.utf8StringToString = utf8StringToString;
  2232. exports.warn = warn;
  2233. }));
  2234. (function (root, factory) {
  2235. {
  2236. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil);
  2237. }
  2238. }(this, function (exports, sharedUtil) {
  2239. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2240. var warn = sharedUtil.warn;
  2241. /**
  2242. * Optimised CSS custom property getter/setter.
  2243. * @class
  2244. */
  2245. var CustomStyle = (function CustomStyleClosure() {
  2246. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2247. // animate-css-transforms-firefox-webkit.html
  2248. // in some versions of IE9 it is critical that ms appear in this list
  2249. // before Moz
  2250. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  2251. var _cache = Object.create(null);
  2252. function CustomStyle() {}
  2253. CustomStyle.getProp = function get(propName, element) {
  2254. // check cache only when no element is given
  2255. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2256. return _cache[propName];
  2257. }
  2258. element = element || document.documentElement;
  2259. var style = element.style, prefixed, uPropName;
  2260. // test standard property first
  2261. if (typeof style[propName] === 'string') {
  2262. return (_cache[propName] = propName);
  2263. }
  2264. // capitalize
  2265. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2266. // test vendor specific properties
  2267. for (var i = 0, l = prefixes.length; i < l; i++) {
  2268. prefixed = prefixes[i] + uPropName;
  2269. if (typeof style[prefixed] === 'string') {
  2270. return (_cache[propName] = prefixed);
  2271. }
  2272. }
  2273. //if all fails then set to undefined
  2274. return (_cache[propName] = 'undefined');
  2275. };
  2276. CustomStyle.setProp = function set(propName, element, str) {
  2277. var prop = this.getProp(propName);
  2278. if (prop !== 'undefined') {
  2279. element.style[prop] = str;
  2280. }
  2281. };
  2282. return CustomStyle;
  2283. })();
  2284. function hasCanvasTypedArrays() {
  2285. var canvas = document.createElement('canvas');
  2286. canvas.width = canvas.height = 1;
  2287. var ctx = canvas.getContext('2d');
  2288. var imageData = ctx.createImageData(1, 1);
  2289. return (typeof imageData.data.buffer !== 'undefined');
  2290. }
  2291. var LinkTarget = {
  2292. NONE: 0, // Default value.
  2293. SELF: 1,
  2294. BLANK: 2,
  2295. PARENT: 3,
  2296. TOP: 4,
  2297. };
  2298. var LinkTargetStringMap = [
  2299. '',
  2300. '_self',
  2301. '_blank',
  2302. '_parent',
  2303. '_top'
  2304. ];
  2305. /**
  2306. * @typedef ExternalLinkParameters
  2307. * @typedef {Object} ExternalLinkParameters
  2308. * @property {string} url - An absolute URL.
  2309. * @property {LinkTarget} target - The link target.
  2310. * @property {string} rel - The link relationship.
  2311. */
  2312. /**
  2313. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2314. * @param {HTMLLinkElement} link - The link element.
  2315. * @param {ExternalLinkParameters} params
  2316. */
  2317. function addLinkAttributes(link, params) {
  2318. var url = params && params.url;
  2319. link.href = link.title = (url ? removeNullCharacters(url) : '');
  2320. if (url) {
  2321. var target = params.target;
  2322. if (typeof target === 'undefined') {
  2323. target = getDefaultSetting('externalLinkTarget');
  2324. }
  2325. link.target = LinkTargetStringMap[target];
  2326. var rel = params.rel;
  2327. if (typeof rel === 'undefined') {
  2328. rel = getDefaultSetting('externalLinkRel');
  2329. }
  2330. link.rel = rel;
  2331. }
  2332. }
  2333. // Gets the file name from a given URL.
  2334. function getFilenameFromUrl(url) {
  2335. var anchor = url.indexOf('#');
  2336. var query = url.indexOf('?');
  2337. var end = Math.min(
  2338. anchor > 0 ? anchor : url.length,
  2339. query > 0 ? query : url.length);
  2340. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2341. }
  2342. function getDefaultSetting(id) {
  2343. // The list of the settings and their default is maintained for backward
  2344. // compatibility and shall not be extended or modified. See also global.js.
  2345. var globalSettings = sharedUtil.globalScope.PDFJS;
  2346. switch (id) {
  2347. case 'pdfBug':
  2348. return globalSettings ? globalSettings.pdfBug : false;
  2349. case 'disableAutoFetch':
  2350. return globalSettings ? globalSettings.disableAutoFetch : false;
  2351. case 'disableStream':
  2352. return globalSettings ? globalSettings.disableStream : false;
  2353. case 'disableRange':
  2354. return globalSettings ? globalSettings.disableRange : false;
  2355. case 'disableFontFace':
  2356. return globalSettings ? globalSettings.disableFontFace : false;
  2357. case 'disableCreateObjectURL':
  2358. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2359. case 'disableWebGL':
  2360. return globalSettings ? globalSettings.disableWebGL : true;
  2361. case 'cMapUrl':
  2362. return globalSettings ? globalSettings.cMapUrl : null;
  2363. case 'cMapPacked':
  2364. return globalSettings ? globalSettings.cMapPacked : false;
  2365. case 'postMessageTransfers':
  2366. return globalSettings ? globalSettings.postMessageTransfers : true;
  2367. case 'workerSrc':
  2368. return globalSettings ? globalSettings.workerSrc : null;
  2369. case 'disableWorker':
  2370. return globalSettings ? globalSettings.disableWorker : false;
  2371. case 'maxImageSize':
  2372. return globalSettings ? globalSettings.maxImageSize : -1;
  2373. case 'imageResourcesPath':
  2374. return globalSettings ? globalSettings.imageResourcesPath : '';
  2375. case 'isEvalSupported':
  2376. return globalSettings ? globalSettings.isEvalSupported : true;
  2377. case 'externalLinkTarget':
  2378. if (!globalSettings) {
  2379. return LinkTarget.NONE;
  2380. }
  2381. switch (globalSettings.externalLinkTarget) {
  2382. case LinkTarget.NONE:
  2383. case LinkTarget.SELF:
  2384. case LinkTarget.BLANK:
  2385. case LinkTarget.PARENT:
  2386. case LinkTarget.TOP:
  2387. return globalSettings.externalLinkTarget;
  2388. }
  2389. warn('PDFJS.externalLinkTarget is invalid: ' +
  2390. globalSettings.externalLinkTarget);
  2391. // Reset the external link target, to suppress further warnings.
  2392. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2393. return LinkTarget.NONE;
  2394. case 'externalLinkRel':
  2395. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2396. case 'enableStats':
  2397. return !!(globalSettings && globalSettings.enableStats);
  2398. default:
  2399. throw new Error('Unknown default setting: ' + id);
  2400. }
  2401. }
  2402. function isExternalLinkTargetSet() {
  2403. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2404. switch (externalLinkTarget) {
  2405. case LinkTarget.NONE:
  2406. return false;
  2407. case LinkTarget.SELF:
  2408. case LinkTarget.BLANK:
  2409. case LinkTarget.PARENT:
  2410. case LinkTarget.TOP:
  2411. return true;
  2412. }
  2413. }
  2414. exports.CustomStyle = CustomStyle;
  2415. exports.addLinkAttributes = addLinkAttributes;
  2416. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2417. exports.getFilenameFromUrl = getFilenameFromUrl;
  2418. exports.LinkTarget = LinkTarget;
  2419. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2420. exports.getDefaultSetting = getDefaultSetting;
  2421. }));
  2422. (function (root, factory) {
  2423. {
  2424. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil);
  2425. }
  2426. }(this, function (exports, sharedUtil) {
  2427. var assert = sharedUtil.assert;
  2428. var bytesToString = sharedUtil.bytesToString;
  2429. var string32 = sharedUtil.string32;
  2430. var shadow = sharedUtil.shadow;
  2431. var warn = sharedUtil.warn;
  2432. function FontLoader(docId) {
  2433. this.docId = docId;
  2434. this.styleElement = null;
  2435. this.nativeFontFaces = [];
  2436. this.loadTestFontId = 0;
  2437. this.loadingContext = {
  2438. requests: [],
  2439. nextRequestId: 0
  2440. };
  2441. }
  2442. FontLoader.prototype = {
  2443. insertRule: function fontLoaderInsertRule(rule) {
  2444. var styleElement = this.styleElement;
  2445. if (!styleElement) {
  2446. styleElement = this.styleElement = document.createElement('style');
  2447. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2448. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2449. styleElement);
  2450. }
  2451. var styleSheet = styleElement.sheet;
  2452. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2453. },
  2454. clear: function fontLoaderClear() {
  2455. var styleElement = this.styleElement;
  2456. if (styleElement) {
  2457. styleElement.parentNode.removeChild(styleElement);
  2458. styleElement = this.styleElement = null;
  2459. }
  2460. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2461. document.fonts.delete(nativeFontFace);
  2462. });
  2463. this.nativeFontFaces.length = 0;
  2464. },
  2465. get loadTestFont() {
  2466. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2467. // height.
  2468. return shadow(this, 'loadTestFont', atob(
  2469. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2470. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2471. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2472. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2473. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2474. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2475. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2476. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2477. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2478. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2479. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2480. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2481. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2482. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2483. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2484. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2485. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2486. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2487. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2488. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2489. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2490. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2491. ));
  2492. },
  2493. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2494. this.nativeFontFaces.push(nativeFontFace);
  2495. document.fonts.add(nativeFontFace);
  2496. },
  2497. bind: function fontLoaderBind(fonts, callback) {
  2498. var rules = [];
  2499. var fontsToLoad = [];
  2500. var fontLoadPromises = [];
  2501. var getNativeFontPromise = function(nativeFontFace) {
  2502. // Return a promise that is always fulfilled, even when the font fails to
  2503. // load.
  2504. return nativeFontFace.loaded.catch(function(e) {
  2505. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2506. });
  2507. };
  2508. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2509. var font = fonts[i];
  2510. // Add the font to the DOM only once or skip if the font
  2511. // is already loaded.
  2512. if (font.attached || font.loading === false) {
  2513. continue;
  2514. }
  2515. font.attached = true;
  2516. if (FontLoader.isFontLoadingAPISupported) {
  2517. var nativeFontFace = font.createNativeFontFace();
  2518. if (nativeFontFace) {
  2519. this.addNativeFontFace(nativeFontFace);
  2520. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2521. }
  2522. } else {
  2523. var rule = font.createFontFaceRule();
  2524. if (rule) {
  2525. this.insertRule(rule);
  2526. rules.push(rule);
  2527. fontsToLoad.push(font);
  2528. }
  2529. }
  2530. }
  2531. var request = this.queueLoadingCallback(callback);
  2532. if (FontLoader.isFontLoadingAPISupported) {
  2533. Promise.all(fontLoadPromises).then(function() {
  2534. request.complete();
  2535. });
  2536. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2537. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2538. } else {
  2539. request.complete();
  2540. }
  2541. },
  2542. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  2543. function LoadLoader_completeRequest() {
  2544. assert(!request.end, 'completeRequest() cannot be called twice');
  2545. request.end = Date.now();
  2546. // sending all completed requests in order how they were queued
  2547. while (context.requests.length > 0 && context.requests[0].end) {
  2548. var otherRequest = context.requests.shift();
  2549. setTimeout(otherRequest.callback, 0);
  2550. }
  2551. }
  2552. var context = this.loadingContext;
  2553. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  2554. var request = {
  2555. id: requestId,
  2556. complete: LoadLoader_completeRequest,
  2557. callback: callback,
  2558. started: Date.now()
  2559. };
  2560. context.requests.push(request);
  2561. return request;
  2562. },
  2563. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  2564. fonts,
  2565. request) {
  2566. /** Hack begin */
  2567. // There's currently no event when a font has finished downloading so the
  2568. // following code is a dirty hack to 'guess' when a font is
  2569. // ready. It's assumed fonts are loaded in order, so add a known test
  2570. // font after the desired fonts and then test for the loading of that
  2571. // test font.
  2572. function int32(data, offset) {
  2573. return (data.charCodeAt(offset) << 24) |
  2574. (data.charCodeAt(offset + 1) << 16) |
  2575. (data.charCodeAt(offset + 2) << 8) |
  2576. (data.charCodeAt(offset + 3) & 0xff);
  2577. }
  2578. function spliceString(s, offset, remove, insert) {
  2579. var chunk1 = s.substr(0, offset);
  2580. var chunk2 = s.substr(offset + remove);
  2581. return chunk1 + insert + chunk2;
  2582. }
  2583. var i, ii;
  2584. var canvas = document.createElement('canvas');
  2585. canvas.width = 1;
  2586. canvas.height = 1;
  2587. var ctx = canvas.getContext('2d');
  2588. var called = 0;
  2589. function isFontReady(name, callback) {
  2590. called++;
  2591. // With setTimeout clamping this gives the font ~100ms to load.
  2592. if(called > 30) {
  2593. warn('Load test font never loaded.');
  2594. callback();
  2595. return;
  2596. }
  2597. ctx.font = '30px ' + name;
  2598. ctx.fillText('.', 0, 20);
  2599. var imageData = ctx.getImageData(0, 0, 1, 1);
  2600. if (imageData.data[3] > 0) {
  2601. callback();
  2602. return;
  2603. }
  2604. setTimeout(isFontReady.bind(null, name, callback));
  2605. }
  2606. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2607. // Chromium seems to cache fonts based on a hash of the actual font data,
  2608. // so the font must be modified for each load test else it will appear to
  2609. // be loaded already.
  2610. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2611. // font by splitting it in chunks before hand and padding the font id.
  2612. var data = this.loadTestFont;
  2613. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  2614. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  2615. loadTestFontId);
  2616. // CFF checksum is important for IE, adjusting it
  2617. var CFF_CHECKSUM_OFFSET = 16;
  2618. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  2619. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2620. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2621. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  2622. }
  2623. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  2624. checksum = (checksum - XXXX_VALUE +
  2625. int32(loadTestFontId + 'XXX', i)) | 0;
  2626. }
  2627. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2628. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2629. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  2630. url + '}';
  2631. this.insertRule(rule);
  2632. var names = [];
  2633. for (i = 0, ii = fonts.length; i < ii; i++) {
  2634. names.push(fonts[i].loadedName);
  2635. }
  2636. names.push(loadTestFontId);
  2637. var div = document.createElement('div');
  2638. div.setAttribute('style',
  2639. 'visibility: hidden;' +
  2640. 'width: 10px; height: 10px;' +
  2641. 'position: absolute; top: 0px; left: 0px;');
  2642. for (i = 0, ii = names.length; i < ii; ++i) {
  2643. var span = document.createElement('span');
  2644. span.textContent = 'Hi';
  2645. span.style.fontFamily = names[i];
  2646. div.appendChild(span);
  2647. }
  2648. document.body.appendChild(div);
  2649. isFontReady(loadTestFontId, function() {
  2650. document.body.removeChild(div);
  2651. request.complete();
  2652. });
  2653. /** Hack end */
  2654. }
  2655. };
  2656. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' &&
  2657. !!document.fonts;
  2658. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2659. get: function () {
  2660. if (typeof navigator === 'undefined') {
  2661. // node.js - we can pretend sync font loading is supported.
  2662. return shadow(FontLoader, 'isSyncFontLoadingSupported', true);
  2663. }
  2664. var supported = false;
  2665. // User agent string sniffing is bad, but there is no reliable way to tell
  2666. // if font is fully loaded and ready to be used with canvas.
  2667. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2668. if (m && m[1] >= 14) {
  2669. supported = true;
  2670. }
  2671. // TODO other browsers
  2672. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  2673. },
  2674. enumerable: true,
  2675. configurable: true
  2676. });
  2677. var IsEvalSupportedCached = {
  2678. get value() {
  2679. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2680. }
  2681. };
  2682. var FontFaceObject = (function FontFaceObjectClosure() {
  2683. function FontFaceObject(translatedData, options) {
  2684. this.compiledGlyphs = Object.create(null);
  2685. // importing translated data
  2686. for (var i in translatedData) {
  2687. this[i] = translatedData[i];
  2688. }
  2689. this.options = options;
  2690. }
  2691. FontFaceObject.prototype = {
  2692. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2693. if (!this.data) {
  2694. return null;
  2695. }
  2696. if (this.options.disableFontFace) {
  2697. this.disableFontFace = true;
  2698. return null;
  2699. }
  2700. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2701. if (this.options.fontRegistry) {
  2702. this.options.fontRegistry.registerFont(this);
  2703. }
  2704. return nativeFontFace;
  2705. },
  2706. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2707. if (!this.data) {
  2708. return null;
  2709. }
  2710. if (this.options.disableFontFace) {
  2711. this.disableFontFace = true;
  2712. return null;
  2713. }
  2714. var data = bytesToString(new Uint8Array(this.data));
  2715. var fontName = this.loadedName;
  2716. // Add the font-face rule to the document
  2717. var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
  2718. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2719. if (this.options.fontRegistry) {
  2720. this.options.fontRegistry.registerFont(this, url);
  2721. }
  2722. return rule;
  2723. },
  2724. getPathGenerator:
  2725. function FontFaceObject_getPathGenerator(objs, character) {
  2726. if (!(character in this.compiledGlyphs)) {
  2727. var cmds = objs.get(this.loadedName + '_path_' + character);
  2728. var current, i, len;
  2729. // If we can, compile cmds into JS for MAXIMUM SPEED
  2730. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2731. var args, js = '';
  2732. for (i = 0, len = cmds.length; i < len; i++) {
  2733. current = cmds[i];
  2734. if (current.args !== undefined) {
  2735. args = current.args.join(',');
  2736. } else {
  2737. args = '';
  2738. }
  2739. js += 'c.' + current.cmd + '(' + args + ');\n';
  2740. }
  2741. /* jshint -W054 */
  2742. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2743. } else {
  2744. // But fall back on using Function.prototype.apply() if we're
  2745. // blocked from using eval() for whatever reason (like CSP policies)
  2746. this.compiledGlyphs[character] = function(c, size) {
  2747. for (i = 0, len = cmds.length; i < len; i++) {
  2748. current = cmds[i];
  2749. if (current.cmd === 'scale') {
  2750. current.args = [size, -size];
  2751. }
  2752. c[current.cmd].apply(c, current.args);
  2753. }
  2754. };
  2755. }
  2756. }
  2757. return this.compiledGlyphs[character];
  2758. }
  2759. };
  2760. return FontFaceObject;
  2761. })();
  2762. exports.FontFaceObject = FontFaceObject;
  2763. exports.FontLoader = FontLoader;
  2764. }));
  2765. (function (root, factory) {
  2766. {
  2767. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  2768. }
  2769. }(this, function (exports, sharedUtil) {
  2770. var error = sharedUtil.error;
  2771. function fixMetadata(meta) {
  2772. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2773. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2774. function(code, d1, d2, d3) {
  2775. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2776. });
  2777. var chars = '';
  2778. for (var i = 0; i < bytes.length; i += 2) {
  2779. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2780. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2781. code !== 38 && false ? String.fromCharCode(code) :
  2782. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2783. }
  2784. return '>' + chars;
  2785. });
  2786. }
  2787. function Metadata(meta) {
  2788. if (typeof meta === 'string') {
  2789. // Ghostscript produces invalid metadata
  2790. meta = fixMetadata(meta);
  2791. var parser = new DOMParser();
  2792. meta = parser.parseFromString(meta, 'application/xml');
  2793. } else if (!(meta instanceof Document)) {
  2794. error('Metadata: Invalid metadata object');
  2795. }
  2796. this.metaDocument = meta;
  2797. this.metadata = Object.create(null);
  2798. this.parse();
  2799. }
  2800. Metadata.prototype = {
  2801. parse: function Metadata_parse() {
  2802. var doc = this.metaDocument;
  2803. var rdf = doc.documentElement;
  2804. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2805. rdf = rdf.firstChild;
  2806. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2807. rdf = rdf.nextSibling;
  2808. }
  2809. }
  2810. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2811. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2812. return;
  2813. }
  2814. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2815. for (i = 0, length = children.length; i < length; i++) {
  2816. desc = children[i];
  2817. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2818. continue;
  2819. }
  2820. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2821. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2822. entry = desc.childNodes[ii];
  2823. name = entry.nodeName.toLowerCase();
  2824. this.metadata[name] = entry.textContent.trim();
  2825. }
  2826. }
  2827. }
  2828. },
  2829. get: function Metadata_get(name) {
  2830. return this.metadata[name] || null;
  2831. },
  2832. has: function Metadata_has(name) {
  2833. return typeof this.metadata[name] !== 'undefined';
  2834. }
  2835. };
  2836. exports.Metadata = Metadata;
  2837. }));
  2838. (function (root, factory) {
  2839. {
  2840. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  2841. }
  2842. }(this, function (exports, sharedUtil) {
  2843. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2844. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2845. var ImageKind = sharedUtil.ImageKind;
  2846. var OPS = sharedUtil.OPS;
  2847. var Util = sharedUtil.Util;
  2848. var isNum = sharedUtil.isNum;
  2849. var isArray = sharedUtil.isArray;
  2850. var warn = sharedUtil.warn;
  2851. var createObjectURL = sharedUtil.createObjectURL;
  2852. var SVG_DEFAULTS = {
  2853. fontStyle: 'normal',
  2854. fontWeight: 'normal',
  2855. fillColor: '#000000'
  2856. };
  2857. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  2858. var PNG_HEADER =
  2859. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  2860. var CHUNK_WRAPPER_SIZE = 12;
  2861. var crcTable = new Int32Array(256);
  2862. for (var i = 0; i < 256; i++) {
  2863. var c = i;
  2864. for (var h = 0; h < 8; h++) {
  2865. if (c & 1) {
  2866. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  2867. } else {
  2868. c = (c >> 1) & 0x7fffffff;
  2869. }
  2870. }
  2871. crcTable[i] = c;
  2872. }
  2873. function crc32(data, start, end) {
  2874. var crc = -1;
  2875. for (var i = start; i < end; i++) {
  2876. var a = (crc ^ data[i]) & 0xff;
  2877. var b = crcTable[a];
  2878. crc = (crc >>> 8) ^ b;
  2879. }
  2880. return crc ^ -1;
  2881. }
  2882. function writePngChunk(type, body, data, offset) {
  2883. var p = offset;
  2884. var len = body.length;
  2885. data[p] = len >> 24 & 0xff;
  2886. data[p + 1] = len >> 16 & 0xff;
  2887. data[p + 2] = len >> 8 & 0xff;
  2888. data[p + 3] = len & 0xff;
  2889. p += 4;
  2890. data[p] = type.charCodeAt(0) & 0xff;
  2891. data[p + 1] = type.charCodeAt(1) & 0xff;
  2892. data[p + 2] = type.charCodeAt(2) & 0xff;
  2893. data[p + 3] = type.charCodeAt(3) & 0xff;
  2894. p += 4;
  2895. data.set(body, p);
  2896. p += body.length;
  2897. var crc = crc32(data, offset + 4, p);
  2898. data[p] = crc >> 24 & 0xff;
  2899. data[p + 1] = crc >> 16 & 0xff;
  2900. data[p + 2] = crc >> 8 & 0xff;
  2901. data[p + 3] = crc & 0xff;
  2902. }
  2903. function adler32(data, start, end) {
  2904. var a = 1;
  2905. var b = 0;
  2906. for (var i = start; i < end; ++i) {
  2907. a = (a + (data[i] & 0xff)) % 65521;
  2908. b = (b + a) % 65521;
  2909. }
  2910. return (b << 16) | a;
  2911. }
  2912. function encode(imgData, kind, forceDataSchema) {
  2913. var width = imgData.width;
  2914. var height = imgData.height;
  2915. var bitDepth, colorType, lineSize;
  2916. var bytes = imgData.data;
  2917. switch (kind) {
  2918. case ImageKind.GRAYSCALE_1BPP:
  2919. colorType = 0;
  2920. bitDepth = 1;
  2921. lineSize = (width + 7) >> 3;
  2922. break;
  2923. case ImageKind.RGB_24BPP:
  2924. colorType = 2;
  2925. bitDepth = 8;
  2926. lineSize = width * 3;
  2927. break;
  2928. case ImageKind.RGBA_32BPP:
  2929. colorType = 6;
  2930. bitDepth = 8;
  2931. lineSize = width * 4;
  2932. break;
  2933. default:
  2934. throw new Error('invalid format');
  2935. }
  2936. // prefix every row with predictor 0
  2937. var literals = new Uint8Array((1 + lineSize) * height);
  2938. var offsetLiterals = 0, offsetBytes = 0;
  2939. var y, i;
  2940. for (y = 0; y < height; ++y) {
  2941. literals[offsetLiterals++] = 0; // no prediction
  2942. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  2943. offsetLiterals);
  2944. offsetBytes += lineSize;
  2945. offsetLiterals += lineSize;
  2946. }
  2947. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2948. // inverting for B/W
  2949. offsetLiterals = 0;
  2950. for (y = 0; y < height; y++) {
  2951. offsetLiterals++; // skipping predictor
  2952. for (i = 0; i < lineSize; i++) {
  2953. literals[offsetLiterals++] ^= 0xFF;
  2954. }
  2955. }
  2956. }
  2957. var ihdr = new Uint8Array([
  2958. width >> 24 & 0xff,
  2959. width >> 16 & 0xff,
  2960. width >> 8 & 0xff,
  2961. width & 0xff,
  2962. height >> 24 & 0xff,
  2963. height >> 16 & 0xff,
  2964. height >> 8 & 0xff,
  2965. height & 0xff,
  2966. bitDepth, // bit depth
  2967. colorType, // color type
  2968. 0x00, // compression method
  2969. 0x00, // filter method
  2970. 0x00 // interlace method
  2971. ]);
  2972. var len = literals.length;
  2973. var maxBlockLength = 0xFFFF;
  2974. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2975. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2976. var pi = 0;
  2977. idat[pi++] = 0x78; // compression method and flags
  2978. idat[pi++] = 0x9c; // flags
  2979. var pos = 0;
  2980. while (len > maxBlockLength) {
  2981. // writing non-final DEFLATE blocks type 0 and length of 65535
  2982. idat[pi++] = 0x00;
  2983. idat[pi++] = 0xff;
  2984. idat[pi++] = 0xff;
  2985. idat[pi++] = 0x00;
  2986. idat[pi++] = 0x00;
  2987. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2988. pi += maxBlockLength;
  2989. pos += maxBlockLength;
  2990. len -= maxBlockLength;
  2991. }
  2992. // writing non-final DEFLATE blocks type 0
  2993. idat[pi++] = 0x01;
  2994. idat[pi++] = len & 0xff;
  2995. idat[pi++] = len >> 8 & 0xff;
  2996. idat[pi++] = (~len & 0xffff) & 0xff;
  2997. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  2998. idat.set(literals.subarray(pos), pi);
  2999. pi += literals.length - pos;
  3000. var adler = adler32(literals, 0, literals.length); // checksum
  3001. idat[pi++] = adler >> 24 & 0xff;
  3002. idat[pi++] = adler >> 16 & 0xff;
  3003. idat[pi++] = adler >> 8 & 0xff;
  3004. idat[pi++] = adler & 0xff;
  3005. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3006. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  3007. ihdr.length + idat.length;
  3008. var data = new Uint8Array(pngLength);
  3009. var offset = 0;
  3010. data.set(PNG_HEADER, offset);
  3011. offset += PNG_HEADER.length;
  3012. writePngChunk('IHDR', ihdr, data, offset);
  3013. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3014. writePngChunk('IDATA', idat, data, offset);
  3015. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3016. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3017. return createObjectURL(data, 'image/png', forceDataSchema);
  3018. }
  3019. return function convertImgDataToPng(imgData, forceDataSchema) {
  3020. var kind = (imgData.kind === undefined ?
  3021. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  3022. return encode(imgData, kind, forceDataSchema);
  3023. };
  3024. })();
  3025. var SVGExtraState = (function SVGExtraStateClosure() {
  3026. function SVGExtraState() {
  3027. this.fontSizeScale = 1;
  3028. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3029. this.fontSize = 0;
  3030. this.textMatrix = IDENTITY_MATRIX;
  3031. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3032. this.leading = 0;
  3033. // Current point (in user coordinates)
  3034. this.x = 0;
  3035. this.y = 0;
  3036. // Start of text line (in text coordinates)
  3037. this.lineX = 0;
  3038. this.lineY = 0;
  3039. // Character and word spacing
  3040. this.charSpacing = 0;
  3041. this.wordSpacing = 0;
  3042. this.textHScale = 1;
  3043. this.textRise = 0;
  3044. // Default foreground and background colors
  3045. this.fillColor = SVG_DEFAULTS.fillColor;
  3046. this.strokeColor = '#000000';
  3047. this.fillAlpha = 1;
  3048. this.strokeAlpha = 1;
  3049. this.lineWidth = 1;
  3050. this.lineJoin = '';
  3051. this.lineCap = '';
  3052. this.miterLimit = 0;
  3053. this.dashArray = [];
  3054. this.dashPhase = 0;
  3055. this.dependencies = [];
  3056. // Clipping
  3057. this.clipId = '';
  3058. this.pendingClip = false;
  3059. this.maskId = '';
  3060. }
  3061. SVGExtraState.prototype = {
  3062. clone: function SVGExtraState_clone() {
  3063. return Object.create(this);
  3064. },
  3065. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3066. this.x = x;
  3067. this.y = y;
  3068. }
  3069. };
  3070. return SVGExtraState;
  3071. })();
  3072. var SVGGraphics = (function SVGGraphicsClosure() {
  3073. function createScratchSVG(width, height) {
  3074. var NS = 'http://www.w3.org/2000/svg';
  3075. var svg = document.createElementNS(NS, 'svg:svg');
  3076. svg.setAttributeNS(null, 'version', '1.1');
  3077. svg.setAttributeNS(null, 'width', width + 'px');
  3078. svg.setAttributeNS(null, 'height', height + 'px');
  3079. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3080. return svg;
  3081. }
  3082. function opListToTree(opList) {
  3083. var opTree = [];
  3084. var tmp = [];
  3085. var opListLen = opList.length;
  3086. for (var x = 0; x < opListLen; x++) {
  3087. if (opList[x].fn === 'save') {
  3088. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3089. tmp.push(opTree);
  3090. opTree = opTree[opTree.length - 1].items;
  3091. continue;
  3092. }
  3093. if(opList[x].fn === 'restore') {
  3094. opTree = tmp.pop();
  3095. } else {
  3096. opTree.push(opList[x]);
  3097. }
  3098. }
  3099. return opTree;
  3100. }
  3101. /**
  3102. * Formats float number.
  3103. * @param value {number} number to format.
  3104. * @returns {string}
  3105. */
  3106. function pf(value) {
  3107. if (value === (value | 0)) { // integer number
  3108. return value.toString();
  3109. }
  3110. var s = value.toFixed(10);
  3111. var i = s.length - 1;
  3112. if (s[i] !== '0') {
  3113. return s;
  3114. }
  3115. // removing trailing zeros
  3116. do {
  3117. i--;
  3118. } while (s[i] === '0');
  3119. return s.substr(0, s[i] === '.' ? i : i + 1);
  3120. }
  3121. /**
  3122. * Formats transform matrix. The standard rotation, scale and translate
  3123. * matrices are replaced by their shorter forms, and for identity matrix
  3124. * returns empty string to save the memory.
  3125. * @param m {Array} matrix to format.
  3126. * @returns {string}
  3127. */
  3128. function pm(m) {
  3129. if (m[4] === 0 && m[5] === 0) {
  3130. if (m[1] === 0 && m[2] === 0) {
  3131. if (m[0] === 1 && m[3] === 1) {
  3132. return '';
  3133. }
  3134. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3135. }
  3136. if (m[0] === m[3] && m[1] === -m[2]) {
  3137. var a = Math.acos(m[0]) * 180 / Math.PI;
  3138. return 'rotate(' + pf(a) + ')';
  3139. }
  3140. } else {
  3141. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3142. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3143. }
  3144. }
  3145. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3146. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3147. }
  3148. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3149. this.current = new SVGExtraState();
  3150. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3151. this.transformStack = [];
  3152. this.extraStack = [];
  3153. this.commonObjs = commonObjs;
  3154. this.objs = objs;
  3155. this.pendingEOFill = false;
  3156. this.embedFonts = false;
  3157. this.embeddedFonts = Object.create(null);
  3158. this.cssStyle = null;
  3159. this.forceDataSchema = !!forceDataSchema;
  3160. }
  3161. var NS = 'http://www.w3.org/2000/svg';
  3162. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3163. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3164. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3165. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3166. var clipCount = 0;
  3167. var maskCount = 0;
  3168. SVGGraphics.prototype = {
  3169. save: function SVGGraphics_save() {
  3170. this.transformStack.push(this.transformMatrix);
  3171. var old = this.current;
  3172. this.extraStack.push(old);
  3173. this.current = old.clone();
  3174. },
  3175. restore: function SVGGraphics_restore() {
  3176. this.transformMatrix = this.transformStack.pop();
  3177. this.current = this.extraStack.pop();
  3178. this.tgrp = document.createElementNS(NS, 'svg:g');
  3179. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3180. this.pgrp.appendChild(this.tgrp);
  3181. },
  3182. group: function SVGGraphics_group(items) {
  3183. this.save();
  3184. this.executeOpTree(items);
  3185. this.restore();
  3186. },
  3187. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3188. var fnArray = operatorList.fnArray;
  3189. var fnArrayLen = fnArray.length;
  3190. var argsArray = operatorList.argsArray;
  3191. var self = this;
  3192. for (var i = 0; i < fnArrayLen; i++) {
  3193. if (OPS.dependency === fnArray[i]) {
  3194. var deps = argsArray[i];
  3195. for (var n = 0, nn = deps.length; n < nn; n++) {
  3196. var obj = deps[n];
  3197. var common = obj.substring(0, 2) === 'g_';
  3198. var promise;
  3199. if (common) {
  3200. promise = new Promise(function(resolve) {
  3201. self.commonObjs.get(obj, resolve);
  3202. });
  3203. } else {
  3204. promise = new Promise(function(resolve) {
  3205. self.objs.get(obj, resolve);
  3206. });
  3207. }
  3208. this.current.dependencies.push(promise);
  3209. }
  3210. }
  3211. }
  3212. return Promise.all(this.current.dependencies);
  3213. },
  3214. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3215. var transformMatrix = [a, b, c, d, e, f];
  3216. this.transformMatrix = Util.transform(this.transformMatrix,
  3217. transformMatrix);
  3218. this.tgrp = document.createElementNS(NS, 'svg:g');
  3219. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3220. },
  3221. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3222. this.svg = createScratchSVG(viewport.width, viewport.height);
  3223. this.viewport = viewport;
  3224. return this.loadDependencies(operatorList).then(function () {
  3225. this.transformMatrix = IDENTITY_MATRIX;
  3226. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3227. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3228. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3229. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3230. this.defs = document.createElementNS(NS, 'svg:defs');
  3231. this.pgrp.appendChild(this.defs);
  3232. this.pgrp.appendChild(this.tgrp);
  3233. this.svg.appendChild(this.pgrp);
  3234. var opTree = this.convertOpList(operatorList);
  3235. this.executeOpTree(opTree);
  3236. return this.svg;
  3237. }.bind(this));
  3238. },
  3239. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3240. var argsArray = operatorList.argsArray;
  3241. var fnArray = operatorList.fnArray;
  3242. var fnArrayLen = fnArray.length;
  3243. var REVOPS = [];
  3244. var opList = [];
  3245. for (var op in OPS) {
  3246. REVOPS[OPS[op]] = op;
  3247. }
  3248. for (var x = 0; x < fnArrayLen; x++) {
  3249. var fnId = fnArray[x];
  3250. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3251. }
  3252. return opListToTree(opList);
  3253. },
  3254. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3255. var opTreeLen = opTree.length;
  3256. for(var x = 0; x < opTreeLen; x++) {
  3257. var fn = opTree[x].fn;
  3258. var fnId = opTree[x].fnId;
  3259. var args = opTree[x].args;
  3260. switch (fnId | 0) {
  3261. case OPS.beginText:
  3262. this.beginText();
  3263. break;
  3264. case OPS.setLeading:
  3265. this.setLeading(args);
  3266. break;
  3267. case OPS.setLeadingMoveText:
  3268. this.setLeadingMoveText(args[0], args[1]);
  3269. break;
  3270. case OPS.setFont:
  3271. this.setFont(args);
  3272. break;
  3273. case OPS.showText:
  3274. this.showText(args[0]);
  3275. break;
  3276. case OPS.showSpacedText:
  3277. this.showText(args[0]);
  3278. break;
  3279. case OPS.endText:
  3280. this.endText();
  3281. break;
  3282. case OPS.moveText:
  3283. this.moveText(args[0], args[1]);
  3284. break;
  3285. case OPS.setCharSpacing:
  3286. this.setCharSpacing(args[0]);
  3287. break;
  3288. case OPS.setWordSpacing:
  3289. this.setWordSpacing(args[0]);
  3290. break;
  3291. case OPS.setHScale:
  3292. this.setHScale(args[0]);
  3293. break;
  3294. case OPS.setTextMatrix:
  3295. this.setTextMatrix(args[0], args[1], args[2],
  3296. args[3], args[4], args[5]);
  3297. break;
  3298. case OPS.setLineWidth:
  3299. this.setLineWidth(args[0]);
  3300. break;
  3301. case OPS.setLineJoin:
  3302. this.setLineJoin(args[0]);
  3303. break;
  3304. case OPS.setLineCap:
  3305. this.setLineCap(args[0]);
  3306. break;
  3307. case OPS.setMiterLimit:
  3308. this.setMiterLimit(args[0]);
  3309. break;
  3310. case OPS.setFillRGBColor:
  3311. this.setFillRGBColor(args[0], args[1], args[2]);
  3312. break;
  3313. case OPS.setStrokeRGBColor:
  3314. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3315. break;
  3316. case OPS.setDash:
  3317. this.setDash(args[0], args[1]);
  3318. break;
  3319. case OPS.setGState:
  3320. this.setGState(args[0]);
  3321. break;
  3322. case OPS.fill:
  3323. this.fill();
  3324. break;
  3325. case OPS.eoFill:
  3326. this.eoFill();
  3327. break;
  3328. case OPS.stroke:
  3329. this.stroke();
  3330. break;
  3331. case OPS.fillStroke:
  3332. this.fillStroke();
  3333. break;
  3334. case OPS.eoFillStroke:
  3335. this.eoFillStroke();
  3336. break;
  3337. case OPS.clip:
  3338. this.clip('nonzero');
  3339. break;
  3340. case OPS.eoClip:
  3341. this.clip('evenodd');
  3342. break;
  3343. case OPS.paintSolidColorImageMask:
  3344. this.paintSolidColorImageMask();
  3345. break;
  3346. case OPS.paintJpegXObject:
  3347. this.paintJpegXObject(args[0], args[1], args[2]);
  3348. break;
  3349. case OPS.paintImageXObject:
  3350. this.paintImageXObject(args[0]);
  3351. break;
  3352. case OPS.paintInlineImageXObject:
  3353. this.paintInlineImageXObject(args[0]);
  3354. break;
  3355. case OPS.paintImageMaskXObject:
  3356. this.paintImageMaskXObject(args[0]);
  3357. break;
  3358. case OPS.paintFormXObjectBegin:
  3359. this.paintFormXObjectBegin(args[0], args[1]);
  3360. break;
  3361. case OPS.paintFormXObjectEnd:
  3362. this.paintFormXObjectEnd();
  3363. break;
  3364. case OPS.closePath:
  3365. this.closePath();
  3366. break;
  3367. case OPS.closeStroke:
  3368. this.closeStroke();
  3369. break;
  3370. case OPS.closeFillStroke:
  3371. this.closeFillStroke();
  3372. break;
  3373. case OPS.nextLine:
  3374. this.nextLine();
  3375. break;
  3376. case OPS.transform:
  3377. this.transform(args[0], args[1], args[2], args[3],
  3378. args[4], args[5]);
  3379. break;
  3380. case OPS.constructPath:
  3381. this.constructPath(args[0], args[1]);
  3382. break;
  3383. case OPS.endPath:
  3384. this.endPath();
  3385. break;
  3386. case 92:
  3387. this.group(opTree[x].items);
  3388. break;
  3389. default:
  3390. warn('Unimplemented method '+ fn);
  3391. break;
  3392. }
  3393. }
  3394. },
  3395. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3396. this.current.wordSpacing = wordSpacing;
  3397. },
  3398. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3399. this.current.charSpacing = charSpacing;
  3400. },
  3401. nextLine: function SVGGraphics_nextLine() {
  3402. this.moveText(0, this.current.leading);
  3403. },
  3404. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3405. var current = this.current;
  3406. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3407. this.current.x = this.current.lineX = 0;
  3408. this.current.y = this.current.lineY = 0;
  3409. current.xcoords = [];
  3410. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3411. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3412. current.tspan.setAttributeNS(null, 'font-size',
  3413. pf(current.fontSize) + 'px');
  3414. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3415. current.txtElement = document.createElementNS(NS, 'svg:text');
  3416. current.txtElement.appendChild(current.tspan);
  3417. },
  3418. beginText: function SVGGraphics_beginText() {
  3419. this.current.x = this.current.lineX = 0;
  3420. this.current.y = this.current.lineY = 0;
  3421. this.current.textMatrix = IDENTITY_MATRIX;
  3422. this.current.lineMatrix = IDENTITY_MATRIX;
  3423. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3424. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3425. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3426. this.current.xcoords = [];
  3427. },
  3428. moveText: function SVGGraphics_moveText(x, y) {
  3429. var current = this.current;
  3430. this.current.x = this.current.lineX += x;
  3431. this.current.y = this.current.lineY += y;
  3432. current.xcoords = [];
  3433. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3434. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3435. current.tspan.setAttributeNS(null, 'font-size',
  3436. pf(current.fontSize) + 'px');
  3437. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3438. },
  3439. showText: function SVGGraphics_showText(glyphs) {
  3440. var current = this.current;
  3441. var font = current.font;
  3442. var fontSize = current.fontSize;
  3443. if (fontSize === 0) {
  3444. return;
  3445. }
  3446. var charSpacing = current.charSpacing;
  3447. var wordSpacing = current.wordSpacing;
  3448. var fontDirection = current.fontDirection;
  3449. var textHScale = current.textHScale * fontDirection;
  3450. var glyphsLength = glyphs.length;
  3451. var vertical = font.vertical;
  3452. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3453. var x = 0, i;
  3454. for (i = 0; i < glyphsLength; ++i) {
  3455. var glyph = glyphs[i];
  3456. if (glyph === null) {
  3457. // word break
  3458. x += fontDirection * wordSpacing;
  3459. continue;
  3460. } else if (isNum(glyph)) {
  3461. x += -glyph * fontSize * 0.001;
  3462. continue;
  3463. }
  3464. current.xcoords.push(current.x + x * textHScale);
  3465. var width = glyph.width;
  3466. var character = glyph.fontChar;
  3467. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3468. x += charWidth;
  3469. current.tspan.textContent += character;
  3470. }
  3471. if (vertical) {
  3472. current.y -= x * textHScale;
  3473. } else {
  3474. current.x += x * textHScale;
  3475. }
  3476. current.tspan.setAttributeNS(null, 'x',
  3477. current.xcoords.map(pf).join(' '));
  3478. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3479. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3480. current.tspan.setAttributeNS(null, 'font-size',
  3481. pf(current.fontSize) + 'px');
  3482. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3483. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3484. }
  3485. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3486. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3487. }
  3488. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3489. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3490. }
  3491. current.txtElement.setAttributeNS(null, 'transform',
  3492. pm(current.textMatrix) +
  3493. ' scale(1, -1)' );
  3494. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3495. current.txtElement.appendChild(current.tspan);
  3496. current.txtgrp.appendChild(current.txtElement);
  3497. this.tgrp.appendChild(current.txtElement);
  3498. },
  3499. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3500. this.setLeading(-y);
  3501. this.moveText(x, y);
  3502. },
  3503. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3504. if (!this.cssStyle) {
  3505. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3506. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3507. this.defs.appendChild(this.cssStyle);
  3508. }
  3509. var url = createObjectURL(fontObj.data, fontObj.mimetype,
  3510. this.forceDataSchema);
  3511. this.cssStyle.textContent +=
  3512. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3513. ' src: url(' + url + '); }\n';
  3514. },
  3515. setFont: function SVGGraphics_setFont(details) {
  3516. var current = this.current;
  3517. var fontObj = this.commonObjs.get(details[0]);
  3518. var size = details[1];
  3519. this.current.font = fontObj;
  3520. if (this.embedFonts && fontObj.data &&
  3521. !this.embeddedFonts[fontObj.loadedName]) {
  3522. this.addFontStyle(fontObj);
  3523. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3524. }
  3525. current.fontMatrix = (fontObj.fontMatrix ?
  3526. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3527. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3528. (fontObj.bold ? 'bold' : 'normal');
  3529. var italic = fontObj.italic ? 'italic' : 'normal';
  3530. if (size < 0) {
  3531. size = -size;
  3532. current.fontDirection = -1;
  3533. } else {
  3534. current.fontDirection = 1;
  3535. }
  3536. current.fontSize = size;
  3537. current.fontFamily = fontObj.loadedName;
  3538. current.fontWeight = bold;
  3539. current.fontStyle = italic;
  3540. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3541. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3542. current.xcoords = [];
  3543. },
  3544. endText: function SVGGraphics_endText() {
  3545. if (this.current.pendingClip) {
  3546. this.cgrp.appendChild(this.tgrp);
  3547. this.pgrp.appendChild(this.cgrp);
  3548. } else {
  3549. this.pgrp.appendChild(this.tgrp);
  3550. }
  3551. this.tgrp = document.createElementNS(NS, 'svg:g');
  3552. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3553. },
  3554. // Path properties
  3555. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3556. this.current.lineWidth = width;
  3557. },
  3558. setLineCap: function SVGGraphics_setLineCap(style) {
  3559. this.current.lineCap = LINE_CAP_STYLES[style];
  3560. },
  3561. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3562. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3563. },
  3564. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3565. this.current.miterLimit = limit;
  3566. },
  3567. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3568. var color = Util.makeCssRgb(r, g, b);
  3569. this.current.strokeColor = color;
  3570. },
  3571. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3572. var color = Util.makeCssRgb(r, g, b);
  3573. this.current.fillColor = color;
  3574. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3575. this.current.xcoords = [];
  3576. },
  3577. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3578. this.current.dashArray = dashArray;
  3579. this.current.dashPhase = dashPhase;
  3580. },
  3581. constructPath: function SVGGraphics_constructPath(ops, args) {
  3582. var current = this.current;
  3583. var x = current.x, y = current.y;
  3584. current.path = document.createElementNS(NS, 'svg:path');
  3585. var d = [];
  3586. var opLength = ops.length;
  3587. for (var i = 0, j = 0; i < opLength; i++) {
  3588. switch (ops[i] | 0) {
  3589. case OPS.rectangle:
  3590. x = args[j++];
  3591. y = args[j++];
  3592. var width = args[j++];
  3593. var height = args[j++];
  3594. var xw = x + width;
  3595. var yh = y + height;
  3596. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  3597. 'L', pf(x), pf(yh), 'Z');
  3598. break;
  3599. case OPS.moveTo:
  3600. x = args[j++];
  3601. y = args[j++];
  3602. d.push('M', pf(x), pf(y));
  3603. break;
  3604. case OPS.lineTo:
  3605. x = args[j++];
  3606. y = args[j++];
  3607. d.push('L', pf(x) , pf(y));
  3608. break;
  3609. case OPS.curveTo:
  3610. x = args[j + 4];
  3611. y = args[j + 5];
  3612. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  3613. pf(args[j + 3]), pf(x), pf(y));
  3614. j += 6;
  3615. break;
  3616. case OPS.curveTo2:
  3617. x = args[j + 2];
  3618. y = args[j + 3];
  3619. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  3620. pf(args[j + 2]), pf(args[j + 3]));
  3621. j += 4;
  3622. break;
  3623. case OPS.curveTo3:
  3624. x = args[j + 2];
  3625. y = args[j + 3];
  3626. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  3627. pf(x), pf(y));
  3628. j += 4;
  3629. break;
  3630. case OPS.closePath:
  3631. d.push('Z');
  3632. break;
  3633. }
  3634. }
  3635. current.path.setAttributeNS(null, 'd', d.join(' '));
  3636. current.path.setAttributeNS(null, 'stroke-miterlimit',
  3637. pf(current.miterLimit));
  3638. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3639. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3640. current.path.setAttributeNS(null, 'stroke-width',
  3641. pf(current.lineWidth) + 'px');
  3642. current.path.setAttributeNS(null, 'stroke-dasharray',
  3643. current.dashArray.map(pf).join(' '));
  3644. current.path.setAttributeNS(null, 'stroke-dashoffset',
  3645. pf(current.dashPhase) + 'px');
  3646. current.path.setAttributeNS(null, 'fill', 'none');
  3647. this.tgrp.appendChild(current.path);
  3648. if (current.pendingClip) {
  3649. this.cgrp.appendChild(this.tgrp);
  3650. this.pgrp.appendChild(this.cgrp);
  3651. } else {
  3652. this.pgrp.appendChild(this.tgrp);
  3653. }
  3654. // Saving a reference in current.element so that it can be addressed
  3655. // in 'fill' and 'stroke'
  3656. current.element = current.path;
  3657. current.setCurrentPoint(x, y);
  3658. },
  3659. endPath: function SVGGraphics_endPath() {
  3660. var current = this.current;
  3661. if (current.pendingClip) {
  3662. this.cgrp.appendChild(this.tgrp);
  3663. this.pgrp.appendChild(this.cgrp);
  3664. } else {
  3665. this.pgrp.appendChild(this.tgrp);
  3666. }
  3667. this.tgrp = document.createElementNS(NS, 'svg:g');
  3668. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3669. },
  3670. clip: function SVGGraphics_clip(type) {
  3671. var current = this.current;
  3672. // Add current path to clipping path
  3673. current.clipId = 'clippath' + clipCount;
  3674. clipCount++;
  3675. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3676. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3677. var clipElement = current.element.cloneNode();
  3678. if (type === 'evenodd') {
  3679. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3680. } else {
  3681. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3682. }
  3683. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3684. this.clippath.appendChild(clipElement);
  3685. this.defs.appendChild(this.clippath);
  3686. // Create a new group with that attribute
  3687. current.pendingClip = true;
  3688. this.cgrp = document.createElementNS(NS, 'svg:g');
  3689. this.cgrp.setAttributeNS(null, 'clip-path',
  3690. 'url(#' + current.clipId + ')');
  3691. this.pgrp.appendChild(this.cgrp);
  3692. },
  3693. closePath: function SVGGraphics_closePath() {
  3694. var current = this.current;
  3695. var d = current.path.getAttributeNS(null, 'd');
  3696. d += 'Z';
  3697. current.path.setAttributeNS(null, 'd', d);
  3698. },
  3699. setLeading: function SVGGraphics_setLeading(leading) {
  3700. this.current.leading = -leading;
  3701. },
  3702. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3703. this.current.textRise = textRise;
  3704. },
  3705. setHScale: function SVGGraphics_setHScale(scale) {
  3706. this.current.textHScale = scale / 100;
  3707. },
  3708. setGState: function SVGGraphics_setGState(states) {
  3709. for (var i = 0, ii = states.length; i < ii; i++) {
  3710. var state = states[i];
  3711. var key = state[0];
  3712. var value = state[1];
  3713. switch (key) {
  3714. case 'LW':
  3715. this.setLineWidth(value);
  3716. break;
  3717. case 'LC':
  3718. this.setLineCap(value);
  3719. break;
  3720. case 'LJ':
  3721. this.setLineJoin(value);
  3722. break;
  3723. case 'ML':
  3724. this.setMiterLimit(value);
  3725. break;
  3726. case 'D':
  3727. this.setDash(value[0], value[1]);
  3728. break;
  3729. case 'RI':
  3730. break;
  3731. case 'FL':
  3732. break;
  3733. case 'Font':
  3734. this.setFont(value);
  3735. break;
  3736. case 'CA':
  3737. break;
  3738. case 'ca':
  3739. break;
  3740. case 'BM':
  3741. break;
  3742. case 'SMask':
  3743. break;
  3744. }
  3745. }
  3746. },
  3747. fill: function SVGGraphics_fill() {
  3748. var current = this.current;
  3749. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3750. },
  3751. stroke: function SVGGraphics_stroke() {
  3752. var current = this.current;
  3753. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3754. current.element.setAttributeNS(null, 'fill', 'none');
  3755. },
  3756. eoFill: function SVGGraphics_eoFill() {
  3757. var current = this.current;
  3758. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3759. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3760. },
  3761. fillStroke: function SVGGraphics_fillStroke() {
  3762. // Order is important since stroke wants fill to be none.
  3763. // First stroke, then if fill needed, it will be overwritten.
  3764. this.stroke();
  3765. this.fill();
  3766. },
  3767. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3768. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3769. this.fillStroke();
  3770. },
  3771. closeStroke: function SVGGraphics_closeStroke() {
  3772. this.closePath();
  3773. this.stroke();
  3774. },
  3775. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3776. this.closePath();
  3777. this.fillStroke();
  3778. },
  3779. paintSolidColorImageMask:
  3780. function SVGGraphics_paintSolidColorImageMask() {
  3781. var current = this.current;
  3782. var rect = document.createElementNS(NS, 'svg:rect');
  3783. rect.setAttributeNS(null, 'x', '0');
  3784. rect.setAttributeNS(null, 'y', '0');
  3785. rect.setAttributeNS(null, 'width', '1px');
  3786. rect.setAttributeNS(null, 'height', '1px');
  3787. rect.setAttributeNS(null, 'fill', current.fillColor);
  3788. this.tgrp.appendChild(rect);
  3789. },
  3790. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3791. var current = this.current;
  3792. var imgObj = this.objs.get(objId);
  3793. var imgEl = document.createElementNS(NS, 'svg:image');
  3794. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3795. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3796. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3797. imgEl.setAttributeNS(null, 'x', '0');
  3798. imgEl.setAttributeNS(null, 'y', pf(-h));
  3799. imgEl.setAttributeNS(null, 'transform',
  3800. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3801. this.tgrp.appendChild(imgEl);
  3802. if (current.pendingClip) {
  3803. this.cgrp.appendChild(this.tgrp);
  3804. this.pgrp.appendChild(this.cgrp);
  3805. } else {
  3806. this.pgrp.appendChild(this.tgrp);
  3807. }
  3808. },
  3809. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3810. var imgData = this.objs.get(objId);
  3811. if (!imgData) {
  3812. warn('Dependent image isn\'t ready yet');
  3813. return;
  3814. }
  3815. this.paintInlineImageXObject(imgData);
  3816. },
  3817. paintInlineImageXObject:
  3818. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3819. var current = this.current;
  3820. var width = imgData.width;
  3821. var height = imgData.height;
  3822. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3823. var cliprect = document.createElementNS(NS, 'svg:rect');
  3824. cliprect.setAttributeNS(null, 'x', '0');
  3825. cliprect.setAttributeNS(null, 'y', '0');
  3826. cliprect.setAttributeNS(null, 'width', pf(width));
  3827. cliprect.setAttributeNS(null, 'height', pf(height));
  3828. current.element = cliprect;
  3829. this.clip('nonzero');
  3830. var imgEl = document.createElementNS(NS, 'svg:image');
  3831. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3832. imgEl.setAttributeNS(null, 'x', '0');
  3833. imgEl.setAttributeNS(null, 'y', pf(-height));
  3834. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3835. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3836. imgEl.setAttributeNS(null, 'transform',
  3837. 'scale(' + pf(1 / width) + ' ' +
  3838. pf(-1 / height) + ')');
  3839. if (mask) {
  3840. mask.appendChild(imgEl);
  3841. } else {
  3842. this.tgrp.appendChild(imgEl);
  3843. }
  3844. if (current.pendingClip) {
  3845. this.cgrp.appendChild(this.tgrp);
  3846. this.pgrp.appendChild(this.cgrp);
  3847. } else {
  3848. this.pgrp.appendChild(this.tgrp);
  3849. }
  3850. },
  3851. paintImageMaskXObject:
  3852. function SVGGraphics_paintImageMaskXObject(imgData) {
  3853. var current = this.current;
  3854. var width = imgData.width;
  3855. var height = imgData.height;
  3856. var fillColor = current.fillColor;
  3857. current.maskId = 'mask' + maskCount++;
  3858. var mask = document.createElementNS(NS, 'svg:mask');
  3859. mask.setAttributeNS(null, 'id', current.maskId);
  3860. var rect = document.createElementNS(NS, 'svg:rect');
  3861. rect.setAttributeNS(null, 'x', '0');
  3862. rect.setAttributeNS(null, 'y', '0');
  3863. rect.setAttributeNS(null, 'width', pf(width));
  3864. rect.setAttributeNS(null, 'height', pf(height));
  3865. rect.setAttributeNS(null, 'fill', fillColor);
  3866. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  3867. this.defs.appendChild(mask);
  3868. this.tgrp.appendChild(rect);
  3869. this.paintInlineImageXObject(imgData, mask);
  3870. },
  3871. paintFormXObjectBegin:
  3872. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3873. this.save();
  3874. if (isArray(matrix) && matrix.length === 6) {
  3875. this.transform(matrix[0], matrix[1], matrix[2],
  3876. matrix[3], matrix[4], matrix[5]);
  3877. }
  3878. if (isArray(bbox) && bbox.length === 4) {
  3879. var width = bbox[2] - bbox[0];
  3880. var height = bbox[3] - bbox[1];
  3881. var cliprect = document.createElementNS(NS, 'svg:rect');
  3882. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3883. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3884. cliprect.setAttributeNS(null, 'width', pf(width));
  3885. cliprect.setAttributeNS(null, 'height', pf(height));
  3886. this.current.element = cliprect;
  3887. this.clip('nonzero');
  3888. this.endPath();
  3889. }
  3890. },
  3891. paintFormXObjectEnd:
  3892. function SVGGraphics_paintFormXObjectEnd() {
  3893. this.restore();
  3894. }
  3895. };
  3896. return SVGGraphics;
  3897. })();
  3898. exports.SVGGraphics = SVGGraphics;
  3899. }));
  3900. (function (root, factory) {
  3901. {
  3902. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  3903. root.pdfjsDisplayDOMUtils);
  3904. }
  3905. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3906. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3907. var AnnotationType = sharedUtil.AnnotationType;
  3908. var Util = sharedUtil.Util;
  3909. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3910. var LinkTarget = displayDOMUtils.LinkTarget;
  3911. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3912. var warn = sharedUtil.warn;
  3913. var CustomStyle = displayDOMUtils.CustomStyle;
  3914. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3915. /**
  3916. * @typedef {Object} AnnotationElementParameters
  3917. * @property {Object} data
  3918. * @property {HTMLDivElement} layer
  3919. * @property {PDFPage} page
  3920. * @property {PageViewport} viewport
  3921. * @property {IPDFLinkService} linkService
  3922. * @property {DownloadManager} downloadManager
  3923. * @property {string} imageResourcesPath
  3924. * @property {boolean} renderInteractiveForms
  3925. */
  3926. /**
  3927. * @class
  3928. * @alias AnnotationElementFactory
  3929. */
  3930. function AnnotationElementFactory() {}
  3931. AnnotationElementFactory.prototype =
  3932. /** @lends AnnotationElementFactory.prototype */ {
  3933. /**
  3934. * @param {AnnotationElementParameters} parameters
  3935. * @returns {AnnotationElement}
  3936. */
  3937. create: function AnnotationElementFactory_create(parameters) {
  3938. var subtype = parameters.data.annotationType;
  3939. switch (subtype) {
  3940. case AnnotationType.LINK:
  3941. return new LinkAnnotationElement(parameters);
  3942. case AnnotationType.TEXT:
  3943. return new TextAnnotationElement(parameters);
  3944. case AnnotationType.WIDGET:
  3945. var fieldType = parameters.data.fieldType;
  3946. switch (fieldType) {
  3947. case 'Tx':
  3948. return new TextWidgetAnnotationElement(parameters);
  3949. }
  3950. return new WidgetAnnotationElement(parameters);
  3951. case AnnotationType.POPUP:
  3952. return new PopupAnnotationElement(parameters);
  3953. case AnnotationType.HIGHLIGHT:
  3954. return new HighlightAnnotationElement(parameters);
  3955. case AnnotationType.UNDERLINE:
  3956. return new UnderlineAnnotationElement(parameters);
  3957. case AnnotationType.SQUIGGLY:
  3958. return new SquigglyAnnotationElement(parameters);
  3959. case AnnotationType.STRIKEOUT:
  3960. return new StrikeOutAnnotationElement(parameters);
  3961. case AnnotationType.FILEATTACHMENT:
  3962. return new FileAttachmentAnnotationElement(parameters);
  3963. default:
  3964. return new AnnotationElement(parameters);
  3965. }
  3966. }
  3967. };
  3968. /**
  3969. * @class
  3970. * @alias AnnotationElement
  3971. */
  3972. var AnnotationElement = (function AnnotationElementClosure() {
  3973. function AnnotationElement(parameters, isRenderable) {
  3974. this.isRenderable = isRenderable || false;
  3975. this.data = parameters.data;
  3976. this.layer = parameters.layer;
  3977. this.page = parameters.page;
  3978. this.viewport = parameters.viewport;
  3979. this.linkService = parameters.linkService;
  3980. this.downloadManager = parameters.downloadManager;
  3981. this.imageResourcesPath = parameters.imageResourcesPath;
  3982. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3983. if (isRenderable) {
  3984. this.container = this._createContainer();
  3985. }
  3986. }
  3987. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3988. /**
  3989. * Create an empty container for the annotation's HTML element.
  3990. *
  3991. * @private
  3992. * @memberof AnnotationElement
  3993. * @returns {HTMLSectionElement}
  3994. */
  3995. _createContainer: function AnnotationElement_createContainer() {
  3996. var data = this.data, page = this.page, viewport = this.viewport;
  3997. var container = document.createElement('section');
  3998. var width = data.rect[2] - data.rect[0];
  3999. var height = data.rect[3] - data.rect[1];
  4000. container.setAttribute('data-annotation-id', data.id);
  4001. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4002. // position on subsequent calls to `_createContainer` (see issue 6804).
  4003. var rect = Util.normalizeRect([
  4004. data.rect[0],
  4005. page.view[3] - data.rect[1] + page.view[1],
  4006. data.rect[2],
  4007. page.view[3] - data.rect[3] + page.view[1]
  4008. ]);
  4009. CustomStyle.setProp('transform', container,
  4010. 'matrix(' + viewport.transform.join(',') + ')');
  4011. CustomStyle.setProp('transformOrigin', container,
  4012. -rect[0] + 'px ' + -rect[1] + 'px');
  4013. if (data.borderStyle.width > 0) {
  4014. container.style.borderWidth = data.borderStyle.width + 'px';
  4015. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4016. // Underline styles only have a bottom border, so we do not need
  4017. // to adjust for all borders. This yields a similar result as
  4018. // Adobe Acrobat/Reader.
  4019. width = width - 2 * data.borderStyle.width;
  4020. height = height - 2 * data.borderStyle.width;
  4021. }
  4022. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4023. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4024. if (horizontalRadius > 0 || verticalRadius > 0) {
  4025. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4026. CustomStyle.setProp('borderRadius', container, radius);
  4027. }
  4028. switch (data.borderStyle.style) {
  4029. case AnnotationBorderStyleType.SOLID:
  4030. container.style.borderStyle = 'solid';
  4031. break;
  4032. case AnnotationBorderStyleType.DASHED:
  4033. container.style.borderStyle = 'dashed';
  4034. break;
  4035. case AnnotationBorderStyleType.BEVELED:
  4036. warn('Unimplemented border style: beveled');
  4037. break;
  4038. case AnnotationBorderStyleType.INSET:
  4039. warn('Unimplemented border style: inset');
  4040. break;
  4041. case AnnotationBorderStyleType.UNDERLINE:
  4042. container.style.borderBottomStyle = 'solid';
  4043. break;
  4044. default:
  4045. break;
  4046. }
  4047. if (data.color) {
  4048. container.style.borderColor =
  4049. Util.makeCssRgb(data.color[0] | 0,
  4050. data.color[1] | 0,
  4051. data.color[2] | 0);
  4052. } else {
  4053. // Transparent (invisible) border, so do not draw it at all.
  4054. container.style.borderWidth = 0;
  4055. }
  4056. }
  4057. container.style.left = rect[0] + 'px';
  4058. container.style.top = rect[1] + 'px';
  4059. container.style.width = width + 'px';
  4060. container.style.height = height + 'px';
  4061. return container;
  4062. },
  4063. /**
  4064. * Create a popup for the annotation's HTML element. This is used for
  4065. * annotations that do not have a Popup entry in the dictionary, but
  4066. * are of a type that works with popups (such as Highlight annotations).
  4067. *
  4068. * @private
  4069. * @param {HTMLSectionElement} container
  4070. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4071. * @param {Object} data
  4072. * @memberof AnnotationElement
  4073. */
  4074. _createPopup:
  4075. function AnnotationElement_createPopup(container, trigger, data) {
  4076. // If no trigger element is specified, create it.
  4077. if (!trigger) {
  4078. trigger = document.createElement('div');
  4079. trigger.style.height = container.style.height;
  4080. trigger.style.width = container.style.width;
  4081. container.appendChild(trigger);
  4082. }
  4083. var popupElement = new PopupElement({
  4084. container: container,
  4085. trigger: trigger,
  4086. color: data.color,
  4087. title: data.title,
  4088. contents: data.contents,
  4089. hideWrapper: true
  4090. });
  4091. var popup = popupElement.render();
  4092. // Position the popup next to the annotation's container.
  4093. popup.style.left = container.style.width;
  4094. container.appendChild(popup);
  4095. },
  4096. /**
  4097. * Render the annotation's HTML element in the empty container.
  4098. *
  4099. * @public
  4100. * @memberof AnnotationElement
  4101. */
  4102. render: function AnnotationElement_render() {
  4103. throw new Error('Abstract method AnnotationElement.render called');
  4104. }
  4105. };
  4106. return AnnotationElement;
  4107. })();
  4108. /**
  4109. * @class
  4110. * @alias LinkAnnotationElement
  4111. */
  4112. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4113. function LinkAnnotationElement(parameters) {
  4114. AnnotationElement.call(this, parameters, true);
  4115. }
  4116. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4117. /**
  4118. * Render the link annotation's HTML element in the empty container.
  4119. *
  4120. * @public
  4121. * @memberof LinkAnnotationElement
  4122. * @returns {HTMLSectionElement}
  4123. */
  4124. render: function LinkAnnotationElement_render() {
  4125. this.container.className = 'linkAnnotation';
  4126. var link = document.createElement('a');
  4127. addLinkAttributes(link, {
  4128. url: this.data.url,
  4129. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4130. });
  4131. if (!this.data.url) {
  4132. if (this.data.action) {
  4133. this._bindNamedAction(link, this.data.action);
  4134. } else {
  4135. this._bindLink(link, (this.data.dest || null));
  4136. }
  4137. }
  4138. this.container.appendChild(link);
  4139. return this.container;
  4140. },
  4141. /**
  4142. * Bind internal links to the link element.
  4143. *
  4144. * @private
  4145. * @param {Object} link
  4146. * @param {Object} destination
  4147. * @memberof LinkAnnotationElement
  4148. */
  4149. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4150. var self = this;
  4151. link.href = this.linkService.getDestinationHash(destination);
  4152. link.onclick = function() {
  4153. if (destination) {
  4154. self.linkService.navigateTo(destination);
  4155. }
  4156. return false;
  4157. };
  4158. if (destination) {
  4159. link.className = 'internalLink';
  4160. }
  4161. },
  4162. /**
  4163. * Bind named actions to the link element.
  4164. *
  4165. * @private
  4166. * @param {Object} link
  4167. * @param {Object} action
  4168. * @memberof LinkAnnotationElement
  4169. */
  4170. _bindNamedAction:
  4171. function LinkAnnotationElement_bindNamedAction(link, action) {
  4172. var self = this;
  4173. link.href = this.linkService.getAnchorUrl('');
  4174. link.onclick = function() {
  4175. self.linkService.executeNamedAction(action);
  4176. return false;
  4177. };
  4178. link.className = 'internalLink';
  4179. }
  4180. });
  4181. return LinkAnnotationElement;
  4182. })();
  4183. /**
  4184. * @class
  4185. * @alias TextAnnotationElement
  4186. */
  4187. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4188. function TextAnnotationElement(parameters) {
  4189. var isRenderable = !!(parameters.data.hasPopup ||
  4190. parameters.data.title || parameters.data.contents);
  4191. AnnotationElement.call(this, parameters, isRenderable);
  4192. }
  4193. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4194. /**
  4195. * Render the text annotation's HTML element in the empty container.
  4196. *
  4197. * @public
  4198. * @memberof TextAnnotationElement
  4199. * @returns {HTMLSectionElement}
  4200. */
  4201. render: function TextAnnotationElement_render() {
  4202. this.container.className = 'textAnnotation';
  4203. var image = document.createElement('img');
  4204. image.style.height = this.container.style.height;
  4205. image.style.width = this.container.style.width;
  4206. image.src = this.imageResourcesPath + 'annotation-' +
  4207. this.data.name.toLowerCase() + '.svg';
  4208. image.alt = '[{{type}} Annotation]';
  4209. image.dataset.l10nId = 'text_annotation_type';
  4210. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4211. if (!this.data.hasPopup) {
  4212. this._createPopup(this.container, image, this.data);
  4213. }
  4214. this.container.appendChild(image);
  4215. return this.container;
  4216. }
  4217. });
  4218. return TextAnnotationElement;
  4219. })();
  4220. /**
  4221. * @class
  4222. * @alias WidgetAnnotationElement
  4223. */
  4224. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4225. function WidgetAnnotationElement(parameters) {
  4226. var isRenderable = parameters.renderInteractiveForms ||
  4227. (!parameters.data.hasAppearance && !!parameters.data.fieldValue);
  4228. AnnotationElement.call(this, parameters, isRenderable);
  4229. }
  4230. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4231. /**
  4232. * Render the widget annotation's HTML element in the empty container.
  4233. *
  4234. * @public
  4235. * @memberof WidgetAnnotationElement
  4236. * @returns {HTMLSectionElement}
  4237. */
  4238. render: function WidgetAnnotationElement_render() {
  4239. // Show only the container for unsupported field types.
  4240. return this.container;
  4241. }
  4242. });
  4243. return WidgetAnnotationElement;
  4244. })();
  4245. /**
  4246. * @class
  4247. * @alias TextWidgetAnnotationElement
  4248. */
  4249. var TextWidgetAnnotationElement = (
  4250. function TextWidgetAnnotationElementClosure() {
  4251. var TEXT_ALIGNMENT = ['left', 'center', 'right'];
  4252. function TextWidgetAnnotationElement(parameters) {
  4253. WidgetAnnotationElement.call(this, parameters);
  4254. }
  4255. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4256. /**
  4257. * Render the text widget annotation's HTML element in the empty container.
  4258. *
  4259. * @public
  4260. * @memberof TextWidgetAnnotationElement
  4261. * @returns {HTMLSectionElement}
  4262. */
  4263. render: function TextWidgetAnnotationElement_render() {
  4264. this.container.className = 'textWidgetAnnotation';
  4265. var element = null;
  4266. if (this.renderInteractiveForms) {
  4267. // NOTE: We cannot set the values using `element.value` below, since it
  4268. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4269. // from parsing the elements correctly for the reference tests.
  4270. if (this.data.multiLine) {
  4271. element = document.createElement('textarea');
  4272. element.textContent = this.data.fieldValue;
  4273. } else {
  4274. element = document.createElement('input');
  4275. element.type = 'text';
  4276. element.setAttribute('value', this.data.fieldValue);
  4277. }
  4278. element.disabled = this.data.readOnly;
  4279. if (this.data.maxLen !== null) {
  4280. element.maxLength = this.data.maxLen;
  4281. }
  4282. if (this.data.comb) {
  4283. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4284. var combWidth = fieldWidth / this.data.maxLen;
  4285. element.classList.add('comb');
  4286. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4287. }
  4288. } else {
  4289. element = document.createElement('div');
  4290. element.textContent = this.data.fieldValue;
  4291. element.style.verticalAlign = 'middle';
  4292. element.style.display = 'table-cell';
  4293. var font = null;
  4294. if (this.data.fontRefName) {
  4295. font = this.page.commonObjs.getData(this.data.fontRefName);
  4296. }
  4297. this._setTextStyle(element, font);
  4298. }
  4299. if (this.data.textAlignment !== null) {
  4300. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4301. }
  4302. this.container.appendChild(element);
  4303. return this.container;
  4304. },
  4305. /**
  4306. * Apply text styles to the text in the element.
  4307. *
  4308. * @private
  4309. * @param {HTMLDivElement} element
  4310. * @param {Object} font
  4311. * @memberof TextWidgetAnnotationElement
  4312. */
  4313. _setTextStyle:
  4314. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4315. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4316. var style = element.style;
  4317. style.fontSize = this.data.fontSize + 'px';
  4318. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4319. if (!font) {
  4320. return;
  4321. }
  4322. style.fontWeight = (font.black ?
  4323. (font.bold ? '900' : 'bold') :
  4324. (font.bold ? 'bold' : 'normal'));
  4325. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4326. // Use a reasonable default font if the font doesn't specify a fallback.
  4327. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4328. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4329. style.fontFamily = fontFamily + fallbackName;
  4330. }
  4331. });
  4332. return TextWidgetAnnotationElement;
  4333. })();
  4334. /**
  4335. * @class
  4336. * @alias PopupAnnotationElement
  4337. */
  4338. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4339. function PopupAnnotationElement(parameters) {
  4340. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4341. AnnotationElement.call(this, parameters, isRenderable);
  4342. }
  4343. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4344. /**
  4345. * Render the popup annotation's HTML element in the empty container.
  4346. *
  4347. * @public
  4348. * @memberof PopupAnnotationElement
  4349. * @returns {HTMLSectionElement}
  4350. */
  4351. render: function PopupAnnotationElement_render() {
  4352. this.container.className = 'popupAnnotation';
  4353. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4354. var parentElement = this.layer.querySelector(selector);
  4355. if (!parentElement) {
  4356. return this.container;
  4357. }
  4358. var popup = new PopupElement({
  4359. container: this.container,
  4360. trigger: parentElement,
  4361. color: this.data.color,
  4362. title: this.data.title,
  4363. contents: this.data.contents
  4364. });
  4365. // Position the popup next to the parent annotation's container.
  4366. // PDF viewers ignore a popup annotation's rectangle.
  4367. var parentLeft = parseFloat(parentElement.style.left);
  4368. var parentWidth = parseFloat(parentElement.style.width);
  4369. CustomStyle.setProp('transformOrigin', this.container,
  4370. -(parentLeft + parentWidth) + 'px -' +
  4371. parentElement.style.top);
  4372. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4373. this.container.appendChild(popup.render());
  4374. return this.container;
  4375. }
  4376. });
  4377. return PopupAnnotationElement;
  4378. })();
  4379. /**
  4380. * @class
  4381. * @alias PopupElement
  4382. */
  4383. var PopupElement = (function PopupElementClosure() {
  4384. var BACKGROUND_ENLIGHT = 0.7;
  4385. function PopupElement(parameters) {
  4386. this.container = parameters.container;
  4387. this.trigger = parameters.trigger;
  4388. this.color = parameters.color;
  4389. this.title = parameters.title;
  4390. this.contents = parameters.contents;
  4391. this.hideWrapper = parameters.hideWrapper || false;
  4392. this.pinned = false;
  4393. }
  4394. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4395. /**
  4396. * Render the popup's HTML element.
  4397. *
  4398. * @public
  4399. * @memberof PopupElement
  4400. * @returns {HTMLSectionElement}
  4401. */
  4402. render: function PopupElement_render() {
  4403. var wrapper = document.createElement('div');
  4404. wrapper.className = 'popupWrapper';
  4405. // For Popup annotations we hide the entire section because it contains
  4406. // only the popup. However, for Text annotations without a separate Popup
  4407. // annotation, we cannot hide the entire container as the image would
  4408. // disappear too. In that special case, hiding the wrapper suffices.
  4409. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4410. this.hideElement.setAttribute('hidden', true);
  4411. var popup = document.createElement('div');
  4412. popup.className = 'popup';
  4413. var color = this.color;
  4414. if (color) {
  4415. // Enlighten the color.
  4416. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4417. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4418. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4419. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4420. }
  4421. var contents = this._formatContents(this.contents);
  4422. var title = document.createElement('h1');
  4423. title.textContent = this.title;
  4424. // Attach the event listeners to the trigger element.
  4425. this.trigger.addEventListener('click', this._toggle.bind(this));
  4426. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4427. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4428. popup.addEventListener('click', this._hide.bind(this, true));
  4429. popup.appendChild(title);
  4430. popup.appendChild(contents);
  4431. wrapper.appendChild(popup);
  4432. return wrapper;
  4433. },
  4434. /**
  4435. * Format the contents of the popup by adding newlines where necessary.
  4436. *
  4437. * @private
  4438. * @param {string} contents
  4439. * @memberof PopupElement
  4440. * @returns {HTMLParagraphElement}
  4441. */
  4442. _formatContents: function PopupElement_formatContents(contents) {
  4443. var p = document.createElement('p');
  4444. var lines = contents.split(/(?:\r\n?|\n)/);
  4445. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4446. var line = lines[i];
  4447. p.appendChild(document.createTextNode(line));
  4448. if (i < (ii - 1)) {
  4449. p.appendChild(document.createElement('br'));
  4450. }
  4451. }
  4452. return p;
  4453. },
  4454. /**
  4455. * Toggle the visibility of the popup.
  4456. *
  4457. * @private
  4458. * @memberof PopupElement
  4459. */
  4460. _toggle: function PopupElement_toggle() {
  4461. if (this.pinned) {
  4462. this._hide(true);
  4463. } else {
  4464. this._show(true);
  4465. }
  4466. },
  4467. /**
  4468. * Show the popup.
  4469. *
  4470. * @private
  4471. * @param {boolean} pin
  4472. * @memberof PopupElement
  4473. */
  4474. _show: function PopupElement_show(pin) {
  4475. if (pin) {
  4476. this.pinned = true;
  4477. }
  4478. if (this.hideElement.hasAttribute('hidden')) {
  4479. this.hideElement.removeAttribute('hidden');
  4480. this.container.style.zIndex += 1;
  4481. }
  4482. },
  4483. /**
  4484. * Hide the popup.
  4485. *
  4486. * @private
  4487. * @param {boolean} unpin
  4488. * @memberof PopupElement
  4489. */
  4490. _hide: function PopupElement_hide(unpin) {
  4491. if (unpin) {
  4492. this.pinned = false;
  4493. }
  4494. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4495. this.hideElement.setAttribute('hidden', true);
  4496. this.container.style.zIndex -= 1;
  4497. }
  4498. }
  4499. };
  4500. return PopupElement;
  4501. })();
  4502. /**
  4503. * @class
  4504. * @alias HighlightAnnotationElement
  4505. */
  4506. var HighlightAnnotationElement = (
  4507. function HighlightAnnotationElementClosure() {
  4508. function HighlightAnnotationElement(parameters) {
  4509. var isRenderable = !!(parameters.data.hasPopup ||
  4510. parameters.data.title || parameters.data.contents);
  4511. AnnotationElement.call(this, parameters, isRenderable);
  4512. }
  4513. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4514. /**
  4515. * Render the highlight annotation's HTML element in the empty container.
  4516. *
  4517. * @public
  4518. * @memberof HighlightAnnotationElement
  4519. * @returns {HTMLSectionElement}
  4520. */
  4521. render: function HighlightAnnotationElement_render() {
  4522. this.container.className = 'highlightAnnotation';
  4523. if (!this.data.hasPopup) {
  4524. this._createPopup(this.container, null, this.data);
  4525. }
  4526. return this.container;
  4527. }
  4528. });
  4529. return HighlightAnnotationElement;
  4530. })();
  4531. /**
  4532. * @class
  4533. * @alias UnderlineAnnotationElement
  4534. */
  4535. var UnderlineAnnotationElement = (
  4536. function UnderlineAnnotationElementClosure() {
  4537. function UnderlineAnnotationElement(parameters) {
  4538. var isRenderable = !!(parameters.data.hasPopup ||
  4539. parameters.data.title || parameters.data.contents);
  4540. AnnotationElement.call(this, parameters, isRenderable);
  4541. }
  4542. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4543. /**
  4544. * Render the underline annotation's HTML element in the empty container.
  4545. *
  4546. * @public
  4547. * @memberof UnderlineAnnotationElement
  4548. * @returns {HTMLSectionElement}
  4549. */
  4550. render: function UnderlineAnnotationElement_render() {
  4551. this.container.className = 'underlineAnnotation';
  4552. if (!this.data.hasPopup) {
  4553. this._createPopup(this.container, null, this.data);
  4554. }
  4555. return this.container;
  4556. }
  4557. });
  4558. return UnderlineAnnotationElement;
  4559. })();
  4560. /**
  4561. * @class
  4562. * @alias SquigglyAnnotationElement
  4563. */
  4564. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4565. function SquigglyAnnotationElement(parameters) {
  4566. var isRenderable = !!(parameters.data.hasPopup ||
  4567. parameters.data.title || parameters.data.contents);
  4568. AnnotationElement.call(this, parameters, isRenderable);
  4569. }
  4570. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4571. /**
  4572. * Render the squiggly annotation's HTML element in the empty container.
  4573. *
  4574. * @public
  4575. * @memberof SquigglyAnnotationElement
  4576. * @returns {HTMLSectionElement}
  4577. */
  4578. render: function SquigglyAnnotationElement_render() {
  4579. this.container.className = 'squigglyAnnotation';
  4580. if (!this.data.hasPopup) {
  4581. this._createPopup(this.container, null, this.data);
  4582. }
  4583. return this.container;
  4584. }
  4585. });
  4586. return SquigglyAnnotationElement;
  4587. })();
  4588. /**
  4589. * @class
  4590. * @alias StrikeOutAnnotationElement
  4591. */
  4592. var StrikeOutAnnotationElement = (
  4593. function StrikeOutAnnotationElementClosure() {
  4594. function StrikeOutAnnotationElement(parameters) {
  4595. var isRenderable = !!(parameters.data.hasPopup ||
  4596. parameters.data.title || parameters.data.contents);
  4597. AnnotationElement.call(this, parameters, isRenderable);
  4598. }
  4599. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4600. /**
  4601. * Render the strikeout annotation's HTML element in the empty container.
  4602. *
  4603. * @public
  4604. * @memberof StrikeOutAnnotationElement
  4605. * @returns {HTMLSectionElement}
  4606. */
  4607. render: function StrikeOutAnnotationElement_render() {
  4608. this.container.className = 'strikeoutAnnotation';
  4609. if (!this.data.hasPopup) {
  4610. this._createPopup(this.container, null, this.data);
  4611. }
  4612. return this.container;
  4613. }
  4614. });
  4615. return StrikeOutAnnotationElement;
  4616. })();
  4617. /**
  4618. * @class
  4619. * @alias FileAttachmentAnnotationElement
  4620. */
  4621. var FileAttachmentAnnotationElement = (
  4622. function FileAttachmentAnnotationElementClosure() {
  4623. function FileAttachmentAnnotationElement(parameters) {
  4624. AnnotationElement.call(this, parameters, true);
  4625. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4626. this.content = parameters.data.file.content;
  4627. }
  4628. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4629. /**
  4630. * Render the file attachment annotation's HTML element in the empty
  4631. * container.
  4632. *
  4633. * @public
  4634. * @memberof FileAttachmentAnnotationElement
  4635. * @returns {HTMLSectionElement}
  4636. */
  4637. render: function FileAttachmentAnnotationElement_render() {
  4638. this.container.className = 'fileAttachmentAnnotation';
  4639. var trigger = document.createElement('div');
  4640. trigger.style.height = this.container.style.height;
  4641. trigger.style.width = this.container.style.width;
  4642. trigger.addEventListener('dblclick', this._download.bind(this));
  4643. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4644. this._createPopup(this.container, trigger, this.data);
  4645. }
  4646. this.container.appendChild(trigger);
  4647. return this.container;
  4648. },
  4649. /**
  4650. * Download the file attachment associated with this annotation.
  4651. *
  4652. * @private
  4653. * @memberof FileAttachmentAnnotationElement
  4654. */
  4655. _download: function FileAttachmentAnnotationElement_download() {
  4656. if (!this.downloadManager) {
  4657. warn('Download cannot be started due to unavailable download manager');
  4658. return;
  4659. }
  4660. this.downloadManager.downloadData(this.content, this.filename, '');
  4661. }
  4662. });
  4663. return FileAttachmentAnnotationElement;
  4664. })();
  4665. /**
  4666. * @typedef {Object} AnnotationLayerParameters
  4667. * @property {PageViewport} viewport
  4668. * @property {HTMLDivElement} div
  4669. * @property {Array} annotations
  4670. * @property {PDFPage} page
  4671. * @property {IPDFLinkService} linkService
  4672. * @property {string} imageResourcesPath
  4673. * @property {boolean} renderInteractiveForms
  4674. */
  4675. /**
  4676. * @class
  4677. * @alias AnnotationLayer
  4678. */
  4679. var AnnotationLayer = (function AnnotationLayerClosure() {
  4680. return {
  4681. /**
  4682. * Render a new annotation layer with all annotation elements.
  4683. *
  4684. * @public
  4685. * @param {AnnotationLayerParameters} parameters
  4686. * @memberof AnnotationLayer
  4687. */
  4688. render: function AnnotationLayer_render(parameters) {
  4689. var annotationElementFactory = new AnnotationElementFactory();
  4690. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4691. var data = parameters.annotations[i];
  4692. if (!data) {
  4693. continue;
  4694. }
  4695. var properties = {
  4696. data: data,
  4697. layer: parameters.div,
  4698. page: parameters.page,
  4699. viewport: parameters.viewport,
  4700. linkService: parameters.linkService,
  4701. downloadManager: parameters.downloadManager,
  4702. imageResourcesPath: parameters.imageResourcesPath ||
  4703. getDefaultSetting('imageResourcesPath'),
  4704. renderInteractiveForms: parameters.renderInteractiveForms || false,
  4705. };
  4706. var element = annotationElementFactory.create(properties);
  4707. if (element.isRenderable) {
  4708. parameters.div.appendChild(element.render());
  4709. }
  4710. }
  4711. },
  4712. /**
  4713. * Update the annotation elements on existing annotation layer.
  4714. *
  4715. * @public
  4716. * @param {AnnotationLayerParameters} parameters
  4717. * @memberof AnnotationLayer
  4718. */
  4719. update: function AnnotationLayer_update(parameters) {
  4720. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4721. var data = parameters.annotations[i];
  4722. var element = parameters.div.querySelector(
  4723. '[data-annotation-id="' + data.id + '"]');
  4724. if (element) {
  4725. CustomStyle.setProp('transform', element,
  4726. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4727. }
  4728. }
  4729. parameters.div.removeAttribute('hidden');
  4730. }
  4731. };
  4732. })();
  4733. exports.AnnotationLayer = AnnotationLayer;
  4734. }));
  4735. (function (root, factory) {
  4736. {
  4737. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4738. root.pdfjsDisplayDOMUtils);
  4739. }
  4740. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4741. var Util = sharedUtil.Util;
  4742. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4743. var CustomStyle = displayDOMUtils.CustomStyle;
  4744. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4745. /**
  4746. * Text layer render parameters.
  4747. *
  4748. * @typedef {Object} TextLayerRenderParameters
  4749. * @property {TextContent} textContent - Text content to render (the object is
  4750. * returned by the page's getTextContent() method).
  4751. * @property {HTMLElement} container - HTML element that will contain text runs.
  4752. * @property {PageViewport} viewport - The target viewport to properly
  4753. * layout the text runs.
  4754. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4755. * the text items of the textContent input. This is output and shall be
  4756. * initially be set to empty array.
  4757. * @property {number} timeout - (optional) Delay in milliseconds before
  4758. * rendering of the text runs occurs.
  4759. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4760. * text selection enhancement.
  4761. */
  4762. var renderTextLayer = (function renderTextLayerClosure() {
  4763. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4764. var NonWhitespaceRegexp = /\S/;
  4765. function isAllWhitespace(str) {
  4766. return !NonWhitespaceRegexp.test(str);
  4767. }
  4768. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  4769. // creating many intermediate strings when building their 'style' properties.
  4770. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0,
  4771. 'px; font-family: ', '', ';'];
  4772. function appendText(task, geom, styles) {
  4773. // Initialize all used properties to keep the caches monomorphic.
  4774. var textDiv = document.createElement('div');
  4775. var textDivProperties = {
  4776. style: null,
  4777. angle: 0,
  4778. canvasWidth: 0,
  4779. isWhitespace: false,
  4780. originalTransform: null,
  4781. paddingBottom: 0,
  4782. paddingLeft: 0,
  4783. paddingRight: 0,
  4784. paddingTop: 0,
  4785. scale: 1,
  4786. };
  4787. task._textDivs.push(textDiv);
  4788. if (isAllWhitespace(geom.str)) {
  4789. textDivProperties.isWhitespace = true;
  4790. task._textDivProperties.set(textDiv, textDivProperties);
  4791. return;
  4792. }
  4793. var tx = Util.transform(task._viewport.transform, geom.transform);
  4794. var angle = Math.atan2(tx[1], tx[0]);
  4795. var style = styles[geom.fontName];
  4796. if (style.vertical) {
  4797. angle += Math.PI / 2;
  4798. }
  4799. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4800. var fontAscent = fontHeight;
  4801. if (style.ascent) {
  4802. fontAscent = style.ascent * fontAscent;
  4803. } else if (style.descent) {
  4804. fontAscent = (1 + style.descent) * fontAscent;
  4805. }
  4806. var left;
  4807. var top;
  4808. if (angle === 0) {
  4809. left = tx[4];
  4810. top = tx[5] - fontAscent;
  4811. } else {
  4812. left = tx[4] + (fontAscent * Math.sin(angle));
  4813. top = tx[5] - (fontAscent * Math.cos(angle));
  4814. }
  4815. styleBuf[1] = left;
  4816. styleBuf[3] = top;
  4817. styleBuf[5] = fontHeight;
  4818. styleBuf[7] = style.fontFamily;
  4819. textDivProperties.style = styleBuf.join('');
  4820. textDiv.setAttribute('style', textDivProperties.style);
  4821. textDiv.textContent = geom.str;
  4822. // |fontName| is only used by the Font Inspector. This test will succeed
  4823. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4824. // not worth the effort to do a more accurate test. We only use `dataset`
  4825. // here to make the font name available for the debugger.
  4826. if (getDefaultSetting('pdfBug')) {
  4827. textDiv.dataset.fontName = geom.fontName;
  4828. }
  4829. if (angle !== 0) {
  4830. textDivProperties.angle = angle * (180 / Math.PI);
  4831. }
  4832. // We don't bother scaling single-char text divs, because it has very
  4833. // little effect on text highlighting. This makes scrolling on docs with
  4834. // lots of such divs a lot faster.
  4835. if (geom.str.length > 1) {
  4836. if (style.vertical) {
  4837. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4838. } else {
  4839. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4840. }
  4841. }
  4842. task._textDivProperties.set(textDiv, textDivProperties);
  4843. if (task._enhanceTextSelection) {
  4844. var angleCos = 1, angleSin = 0;
  4845. if (angle !== 0) {
  4846. angleCos = Math.cos(angle);
  4847. angleSin = Math.sin(angle);
  4848. }
  4849. var divWidth = (style.vertical ? geom.height : geom.width) *
  4850. task._viewport.scale;
  4851. var divHeight = fontHeight;
  4852. var m, b;
  4853. if (angle !== 0) {
  4854. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4855. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4856. } else {
  4857. b = [left, top, left + divWidth, top + divHeight];
  4858. }
  4859. task._bounds.push({
  4860. left: b[0],
  4861. top: b[1],
  4862. right: b[2],
  4863. bottom: b[3],
  4864. div: textDiv,
  4865. size: [divWidth, divHeight],
  4866. m: m
  4867. });
  4868. }
  4869. }
  4870. function render(task) {
  4871. if (task._canceled) {
  4872. return;
  4873. }
  4874. var textLayerFrag = task._container;
  4875. var textDivs = task._textDivs;
  4876. var capability = task._capability;
  4877. var textDivsLength = textDivs.length;
  4878. // No point in rendering many divs as it would make the browser
  4879. // unusable even after the divs are rendered.
  4880. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4881. task._renderingDone = true;
  4882. capability.resolve();
  4883. return;
  4884. }
  4885. var canvas = document.createElement('canvas');
  4886. canvas.mozOpaque = true;
  4887. var ctx = canvas.getContext('2d', {alpha: false});
  4888. var lastFontSize;
  4889. var lastFontFamily;
  4890. for (var i = 0; i < textDivsLength; i++) {
  4891. var textDiv = textDivs[i];
  4892. var textDivProperties = task._textDivProperties.get(textDiv);
  4893. if (textDivProperties.isWhitespace) {
  4894. continue;
  4895. }
  4896. var fontSize = textDiv.style.fontSize;
  4897. var fontFamily = textDiv.style.fontFamily;
  4898. // Only build font string and set to context if different from last.
  4899. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4900. ctx.font = fontSize + ' ' + fontFamily;
  4901. lastFontSize = fontSize;
  4902. lastFontFamily = fontFamily;
  4903. }
  4904. var width = ctx.measureText(textDiv.textContent).width;
  4905. textLayerFrag.appendChild(textDiv);
  4906. var transform = '';
  4907. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4908. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4909. transform = 'scaleX(' + textDivProperties.scale + ')';
  4910. }
  4911. if (textDivProperties.angle !== 0) {
  4912. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4913. }
  4914. if (transform !== '') {
  4915. textDivProperties.originalTransform = transform;
  4916. CustomStyle.setProp('transform', textDiv, transform);
  4917. }
  4918. task._textDivProperties.set(textDiv, textDivProperties);
  4919. }
  4920. task._renderingDone = true;
  4921. capability.resolve();
  4922. }
  4923. function expand(task) {
  4924. var bounds = task._bounds;
  4925. var viewport = task._viewport;
  4926. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4927. for (var i = 0; i < expanded.length; i++) {
  4928. var div = bounds[i].div;
  4929. var divProperties = task._textDivProperties.get(div);
  4930. if (divProperties.angle === 0) {
  4931. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4932. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4933. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4934. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4935. task._textDivProperties.set(div, divProperties);
  4936. continue;
  4937. }
  4938. // Box is rotated -- trying to find padding so rotated div will not
  4939. // exceed its expanded bounds.
  4940. var e = expanded[i], b = bounds[i];
  4941. var m = b.m, c = m[0], s = m[1];
  4942. // Finding intersections with expanded box.
  4943. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4944. var ts = new Float64Array(64);
  4945. points.forEach(function (p, i) {
  4946. var t = Util.applyTransform(p, m);
  4947. ts[i + 0] = c && (e.left - t[0]) / c;
  4948. ts[i + 4] = s && (e.top - t[1]) / s;
  4949. ts[i + 8] = c && (e.right - t[0]) / c;
  4950. ts[i + 12] = s && (e.bottom - t[1]) / s;
  4951. ts[i + 16] = s && (e.left - t[0]) / -s;
  4952. ts[i + 20] = c && (e.top - t[1]) / c;
  4953. ts[i + 24] = s && (e.right - t[0]) / -s;
  4954. ts[i + 28] = c && (e.bottom - t[1]) / c;
  4955. ts[i + 32] = c && (e.left - t[0]) / -c;
  4956. ts[i + 36] = s && (e.top - t[1]) / -s;
  4957. ts[i + 40] = c && (e.right - t[0]) / -c;
  4958. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  4959. ts[i + 48] = s && (e.left - t[0]) / s;
  4960. ts[i + 52] = c && (e.top - t[1]) / -c;
  4961. ts[i + 56] = s && (e.right - t[0]) / s;
  4962. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  4963. });
  4964. var findPositiveMin = function (ts, offset, count) {
  4965. var result = 0;
  4966. for (var i = 0; i < count; i++) {
  4967. var t = ts[offset++];
  4968. if (t > 0) {
  4969. result = result ? Math.min(t, result) : t;
  4970. }
  4971. }
  4972. return result;
  4973. };
  4974. // Not based on math, but to simplify calculations, using cos and sin
  4975. // absolute values to not exceed the box (it can but insignificantly).
  4976. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  4977. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  4978. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  4979. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  4980. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  4981. task._textDivProperties.set(div, divProperties);
  4982. }
  4983. }
  4984. function expandBounds(width, height, boxes) {
  4985. var bounds = boxes.map(function (box, i) {
  4986. return {
  4987. x1: box.left,
  4988. y1: box.top,
  4989. x2: box.right,
  4990. y2: box.bottom,
  4991. index: i,
  4992. x1New: undefined,
  4993. x2New: undefined
  4994. };
  4995. });
  4996. expandBoundsLTR(width, bounds);
  4997. var expanded = new Array(boxes.length);
  4998. bounds.forEach(function (b) {
  4999. var i = b.index;
  5000. expanded[i] = {
  5001. left: b.x1New,
  5002. top: 0,
  5003. right: b.x2New,
  5004. bottom: 0
  5005. };
  5006. });
  5007. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5008. // array and objects.
  5009. boxes.map(function (box, i) {
  5010. var e = expanded[i], b = bounds[i];
  5011. b.x1 = box.top;
  5012. b.y1 = width - e.right;
  5013. b.x2 = box.bottom;
  5014. b.y2 = width - e.left;
  5015. b.index = i;
  5016. b.x1New = undefined;
  5017. b.x2New = undefined;
  5018. });
  5019. expandBoundsLTR(height, bounds);
  5020. bounds.forEach(function (b) {
  5021. var i = b.index;
  5022. expanded[i].top = b.x1New;
  5023. expanded[i].bottom = b.x2New;
  5024. });
  5025. return expanded;
  5026. }
  5027. function expandBoundsLTR(width, bounds) {
  5028. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5029. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  5030. // First we see on the horizon is a fake boundary.
  5031. var fakeBoundary = {
  5032. x1: -Infinity,
  5033. y1: -Infinity,
  5034. x2: 0,
  5035. y2: Infinity,
  5036. index: -1,
  5037. x1New: 0,
  5038. x2New: 0
  5039. };
  5040. var horizon = [{
  5041. start: -Infinity,
  5042. end: Infinity,
  5043. boundary: fakeBoundary
  5044. }];
  5045. bounds.forEach(function (boundary) {
  5046. // Searching for the affected part of horizon.
  5047. // TODO red-black tree or simple binary search
  5048. var i = 0;
  5049. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5050. i++;
  5051. }
  5052. var j = horizon.length - 1;
  5053. while(j >= 0 && horizon[j].start >= boundary.y2) {
  5054. j--;
  5055. }
  5056. var horizonPart, affectedBoundary;
  5057. var q, k, maxXNew = -Infinity;
  5058. for (q = i; q <= j; q++) {
  5059. horizonPart = horizon[q];
  5060. affectedBoundary = horizonPart.boundary;
  5061. var xNew;
  5062. if (affectedBoundary.x2 > boundary.x1) {
  5063. // In the middle of the previous element, new x shall be at the
  5064. // boundary start. Extending if further if the affected bondary
  5065. // placed on top of the current one.
  5066. xNew = affectedBoundary.index > boundary.index ?
  5067. affectedBoundary.x1New : boundary.x1;
  5068. } else if (affectedBoundary.x2New === undefined) {
  5069. // We have some space in between, new x in middle will be a fair
  5070. // choice.
  5071. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5072. } else {
  5073. // Affected boundary has x2new set, using it as new x.
  5074. xNew = affectedBoundary.x2New;
  5075. }
  5076. if (xNew > maxXNew) {
  5077. maxXNew = xNew;
  5078. }
  5079. }
  5080. // Set new x1 for current boundary.
  5081. boundary.x1New = maxXNew;
  5082. // Adjusts new x2 for the affected boundaries.
  5083. for (q = i; q <= j; q++) {
  5084. horizonPart = horizon[q];
  5085. affectedBoundary = horizonPart.boundary;
  5086. if (affectedBoundary.x2New === undefined) {
  5087. // Was not set yet, choosing new x if possible.
  5088. if (affectedBoundary.x2 > boundary.x1) {
  5089. // Current and affected boundaries intersect. If affected boundary
  5090. // is placed on top of the current, shrinking the affected.
  5091. if (affectedBoundary.index > boundary.index) {
  5092. affectedBoundary.x2New = affectedBoundary.x2;
  5093. }
  5094. } else {
  5095. affectedBoundary.x2New = maxXNew;
  5096. }
  5097. } else if (affectedBoundary.x2New > maxXNew) {
  5098. // Affected boundary is touching new x, pushing it back.
  5099. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5100. }
  5101. }
  5102. // Fixing the horizon.
  5103. var changedHorizon = [], lastBoundary = null;
  5104. for (q = i; q <= j; q++) {
  5105. horizonPart = horizon[q];
  5106. affectedBoundary = horizonPart.boundary;
  5107. // Checking which boundary will be visible.
  5108. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5109. affectedBoundary : boundary;
  5110. if (lastBoundary === useBoundary) {
  5111. // Merging with previous.
  5112. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5113. } else {
  5114. changedHorizon.push({
  5115. start: horizonPart.start,
  5116. end: horizonPart.end,
  5117. boundary: useBoundary
  5118. });
  5119. lastBoundary = useBoundary;
  5120. }
  5121. }
  5122. if (horizon[i].start < boundary.y1) {
  5123. changedHorizon[0].start = boundary.y1;
  5124. changedHorizon.unshift({
  5125. start: horizon[i].start,
  5126. end: boundary.y1,
  5127. boundary: horizon[i].boundary
  5128. });
  5129. }
  5130. if (boundary.y2 < horizon[j].end) {
  5131. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5132. changedHorizon.push({
  5133. start: boundary.y2,
  5134. end: horizon[j].end,
  5135. boundary: horizon[j].boundary
  5136. });
  5137. }
  5138. // Set x2 new of boundary that is no longer visible (see overlapping case
  5139. // above).
  5140. // TODO more efficient, e.g. via reference counting.
  5141. for (q = i; q <= j; q++) {
  5142. horizonPart = horizon[q];
  5143. affectedBoundary = horizonPart.boundary;
  5144. if (affectedBoundary.x2New !== undefined) {
  5145. continue;
  5146. }
  5147. var used = false;
  5148. for (k = i - 1; !used && k >= 0 &&
  5149. horizon[k].start >= affectedBoundary.y1; k--) {
  5150. used = horizon[k].boundary === affectedBoundary;
  5151. }
  5152. for (k = j + 1; !used && k < horizon.length &&
  5153. horizon[k].end <= affectedBoundary.y2; k++) {
  5154. used = horizon[k].boundary === affectedBoundary;
  5155. }
  5156. for (k = 0; !used && k < changedHorizon.length; k++) {
  5157. used = changedHorizon[k].boundary === affectedBoundary;
  5158. }
  5159. if (!used) {
  5160. affectedBoundary.x2New = maxXNew;
  5161. }
  5162. }
  5163. Array.prototype.splice.apply(horizon,
  5164. [i, j - i + 1].concat(changedHorizon));
  5165. });
  5166. // Set new x2 for all unset boundaries.
  5167. horizon.forEach(function (horizonPart) {
  5168. var affectedBoundary = horizonPart.boundary;
  5169. if (affectedBoundary.x2New === undefined) {
  5170. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5171. }
  5172. });
  5173. }
  5174. /**
  5175. * Text layer rendering task.
  5176. *
  5177. * @param {TextContent} textContent
  5178. * @param {HTMLElement} container
  5179. * @param {PageViewport} viewport
  5180. * @param {Array} textDivs
  5181. * @param {boolean} enhanceTextSelection
  5182. * @private
  5183. */
  5184. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5185. enhanceTextSelection) {
  5186. this._textContent = textContent;
  5187. this._container = container;
  5188. this._viewport = viewport;
  5189. this._textDivs = textDivs || [];
  5190. this._textDivProperties = new WeakMap();
  5191. this._renderingDone = false;
  5192. this._canceled = false;
  5193. this._capability = createPromiseCapability();
  5194. this._renderTimer = null;
  5195. this._bounds = [];
  5196. this._enhanceTextSelection = !!enhanceTextSelection;
  5197. }
  5198. TextLayerRenderTask.prototype = {
  5199. get promise() {
  5200. return this._capability.promise;
  5201. },
  5202. cancel: function TextLayer_cancel() {
  5203. this._canceled = true;
  5204. if (this._renderTimer !== null) {
  5205. clearTimeout(this._renderTimer);
  5206. this._renderTimer = null;
  5207. }
  5208. this._capability.reject('canceled');
  5209. },
  5210. _render: function TextLayer_render(timeout) {
  5211. var textItems = this._textContent.items;
  5212. var textStyles = this._textContent.styles;
  5213. for (var i = 0, len = textItems.length; i < len; i++) {
  5214. appendText(this, textItems[i], textStyles);
  5215. }
  5216. if (!timeout) { // Render right away
  5217. render(this);
  5218. } else { // Schedule
  5219. var self = this;
  5220. this._renderTimer = setTimeout(function() {
  5221. render(self);
  5222. self._renderTimer = null;
  5223. }, timeout);
  5224. }
  5225. },
  5226. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5227. if (!this._enhanceTextSelection || !this._renderingDone) {
  5228. return;
  5229. }
  5230. if (this._bounds !== null) {
  5231. expand(this);
  5232. this._bounds = null;
  5233. }
  5234. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5235. var div = this._textDivs[i];
  5236. var divProperties = this._textDivProperties.get(div);
  5237. if (divProperties.isWhitespace) {
  5238. continue;
  5239. }
  5240. if (expandDivs) {
  5241. var transform = '', padding = '';
  5242. if (divProperties.scale !== 1) {
  5243. transform = 'scaleX(' + divProperties.scale + ')';
  5244. }
  5245. if (divProperties.angle !== 0) {
  5246. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5247. }
  5248. if (divProperties.paddingLeft !== 0) {
  5249. padding += ' padding-left: ' +
  5250. (divProperties.paddingLeft / divProperties.scale) + 'px;';
  5251. transform += ' translateX(' +
  5252. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5253. }
  5254. if (divProperties.paddingTop !== 0) {
  5255. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5256. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5257. }
  5258. if (divProperties.paddingRight !== 0) {
  5259. padding += ' padding-right: ' +
  5260. (divProperties.paddingRight / divProperties.scale) + 'px;';
  5261. }
  5262. if (divProperties.paddingBottom !== 0) {
  5263. padding += ' padding-bottom: ' +
  5264. divProperties.paddingBottom + 'px;';
  5265. }
  5266. if (padding !== '') {
  5267. div.setAttribute('style', divProperties.style + padding);
  5268. }
  5269. if (transform !== '') {
  5270. CustomStyle.setProp('transform', div, transform);
  5271. }
  5272. } else {
  5273. div.style.padding = 0;
  5274. CustomStyle.setProp('transform', div,
  5275. divProperties.originalTransform || '');
  5276. }
  5277. }
  5278. },
  5279. };
  5280. /**
  5281. * Starts rendering of the text layer.
  5282. *
  5283. * @param {TextLayerRenderParameters} renderParameters
  5284. * @returns {TextLayerRenderTask}
  5285. */
  5286. function renderTextLayer(renderParameters) {
  5287. var task = new TextLayerRenderTask(renderParameters.textContent,
  5288. renderParameters.container,
  5289. renderParameters.viewport,
  5290. renderParameters.textDivs,
  5291. renderParameters.enhanceTextSelection);
  5292. task._render(renderParameters.timeout);
  5293. return task;
  5294. }
  5295. return renderTextLayer;
  5296. })();
  5297. exports.renderTextLayer = renderTextLayer;
  5298. }));
  5299. (function (root, factory) {
  5300. {
  5301. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5302. root.pdfjsDisplayDOMUtils);
  5303. }
  5304. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5305. var shadow = sharedUtil.shadow;
  5306. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5307. var WebGLUtils = (function WebGLUtilsClosure() {
  5308. function loadShader(gl, code, shaderType) {
  5309. var shader = gl.createShader(shaderType);
  5310. gl.shaderSource(shader, code);
  5311. gl.compileShader(shader);
  5312. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5313. if (!compiled) {
  5314. var errorMsg = gl.getShaderInfoLog(shader);
  5315. throw new Error('Error during shader compilation: ' + errorMsg);
  5316. }
  5317. return shader;
  5318. }
  5319. function createVertexShader(gl, code) {
  5320. return loadShader(gl, code, gl.VERTEX_SHADER);
  5321. }
  5322. function createFragmentShader(gl, code) {
  5323. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5324. }
  5325. function createProgram(gl, shaders) {
  5326. var program = gl.createProgram();
  5327. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5328. gl.attachShader(program, shaders[i]);
  5329. }
  5330. gl.linkProgram(program);
  5331. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5332. if (!linked) {
  5333. var errorMsg = gl.getProgramInfoLog(program);
  5334. throw new Error('Error during program linking: ' + errorMsg);
  5335. }
  5336. return program;
  5337. }
  5338. function createTexture(gl, image, textureId) {
  5339. gl.activeTexture(textureId);
  5340. var texture = gl.createTexture();
  5341. gl.bindTexture(gl.TEXTURE_2D, texture);
  5342. // Set the parameters so we can render any size image.
  5343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5347. // Upload the image into the texture.
  5348. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5349. return texture;
  5350. }
  5351. var currentGL, currentCanvas;
  5352. function generateGL() {
  5353. if (currentGL) {
  5354. return;
  5355. }
  5356. currentCanvas = document.createElement('canvas');
  5357. currentGL = currentCanvas.getContext('webgl',
  5358. { premultipliedalpha: false });
  5359. }
  5360. var smaskVertexShaderCode = '\
  5361. attribute vec2 a_position; \
  5362. attribute vec2 a_texCoord; \
  5363. \
  5364. uniform vec2 u_resolution; \
  5365. \
  5366. varying vec2 v_texCoord; \
  5367. \
  5368. void main() { \
  5369. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5370. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5371. \
  5372. v_texCoord = a_texCoord; \
  5373. } ';
  5374. var smaskFragmentShaderCode = '\
  5375. precision mediump float; \
  5376. \
  5377. uniform vec4 u_backdrop; \
  5378. uniform int u_subtype; \
  5379. uniform sampler2D u_image; \
  5380. uniform sampler2D u_mask; \
  5381. \
  5382. varying vec2 v_texCoord; \
  5383. \
  5384. void main() { \
  5385. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5386. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5387. if (u_backdrop.a > 0.0) { \
  5388. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5389. u_backdrop.rgb * (1.0 - maskColor.a); \
  5390. } \
  5391. float lum; \
  5392. if (u_subtype == 0) { \
  5393. lum = maskColor.a; \
  5394. } else { \
  5395. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5396. maskColor.b * 0.11; \
  5397. } \
  5398. imageColor.a *= lum; \
  5399. imageColor.rgb *= imageColor.a; \
  5400. gl_FragColor = imageColor; \
  5401. } ';
  5402. var smaskCache = null;
  5403. function initSmaskGL() {
  5404. var canvas, gl;
  5405. generateGL();
  5406. canvas = currentCanvas;
  5407. currentCanvas = null;
  5408. gl = currentGL;
  5409. currentGL = null;
  5410. // setup a GLSL program
  5411. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5412. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5413. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5414. gl.useProgram(program);
  5415. var cache = {};
  5416. cache.gl = gl;
  5417. cache.canvas = canvas;
  5418. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5419. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5420. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5421. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5422. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5423. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5424. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5425. // provide texture coordinates for the rectangle.
  5426. var texCoordBuffer = gl.createBuffer();
  5427. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5428. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5429. 0.0, 0.0,
  5430. 1.0, 0.0,
  5431. 0.0, 1.0,
  5432. 0.0, 1.0,
  5433. 1.0, 0.0,
  5434. 1.0, 1.0]), gl.STATIC_DRAW);
  5435. gl.enableVertexAttribArray(texCoordLocation);
  5436. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5437. gl.uniform1i(texLayerLocation, 0);
  5438. gl.uniform1i(texMaskLocation, 1);
  5439. smaskCache = cache;
  5440. }
  5441. function composeSMask(layer, mask, properties) {
  5442. var width = layer.width, height = layer.height;
  5443. if (!smaskCache) {
  5444. initSmaskGL();
  5445. }
  5446. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5447. canvas.width = width;
  5448. canvas.height = height;
  5449. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5450. gl.uniform2f(cache.resolutionLocation, width, height);
  5451. if (properties.backdrop) {
  5452. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5453. properties.backdrop[1], properties.backdrop[2], 1);
  5454. } else {
  5455. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5456. }
  5457. gl.uniform1i(cache.subtypeLocation,
  5458. properties.subtype === 'Luminosity' ? 1 : 0);
  5459. // Create a textures
  5460. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5461. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5462. // Create a buffer and put a single clipspace rectangle in
  5463. // it (2 triangles)
  5464. var buffer = gl.createBuffer();
  5465. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5466. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5467. 0, 0,
  5468. width, 0,
  5469. 0, height,
  5470. 0, height,
  5471. width, 0,
  5472. width, height]), gl.STATIC_DRAW);
  5473. gl.enableVertexAttribArray(cache.positionLocation);
  5474. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5475. // draw
  5476. gl.clearColor(0, 0, 0, 0);
  5477. gl.enable(gl.BLEND);
  5478. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5479. gl.clear(gl.COLOR_BUFFER_BIT);
  5480. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5481. gl.flush();
  5482. gl.deleteTexture(texture);
  5483. gl.deleteTexture(maskTexture);
  5484. gl.deleteBuffer(buffer);
  5485. return canvas;
  5486. }
  5487. var figuresVertexShaderCode = '\
  5488. attribute vec2 a_position; \
  5489. attribute vec3 a_color; \
  5490. \
  5491. uniform vec2 u_resolution; \
  5492. uniform vec2 u_scale; \
  5493. uniform vec2 u_offset; \
  5494. \
  5495. varying vec4 v_color; \
  5496. \
  5497. void main() { \
  5498. vec2 position = (a_position + u_offset) * u_scale; \
  5499. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5500. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5501. \
  5502. v_color = vec4(a_color / 255.0, 1.0); \
  5503. } ';
  5504. var figuresFragmentShaderCode = '\
  5505. precision mediump float; \
  5506. \
  5507. varying vec4 v_color; \
  5508. \
  5509. void main() { \
  5510. gl_FragColor = v_color; \
  5511. } ';
  5512. var figuresCache = null;
  5513. function initFiguresGL() {
  5514. var canvas, gl;
  5515. generateGL();
  5516. canvas = currentCanvas;
  5517. currentCanvas = null;
  5518. gl = currentGL;
  5519. currentGL = null;
  5520. // setup a GLSL program
  5521. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5522. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5523. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5524. gl.useProgram(program);
  5525. var cache = {};
  5526. cache.gl = gl;
  5527. cache.canvas = canvas;
  5528. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5529. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5530. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5531. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5532. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5533. figuresCache = cache;
  5534. }
  5535. function drawFigures(width, height, backgroundColor, figures, context) {
  5536. if (!figuresCache) {
  5537. initFiguresGL();
  5538. }
  5539. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5540. canvas.width = width;
  5541. canvas.height = height;
  5542. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5543. gl.uniform2f(cache.resolutionLocation, width, height);
  5544. // count triangle points
  5545. var count = 0;
  5546. var i, ii, rows;
  5547. for (i = 0, ii = figures.length; i < ii; i++) {
  5548. switch (figures[i].type) {
  5549. case 'lattice':
  5550. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5551. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5552. break;
  5553. case 'triangles':
  5554. count += figures[i].coords.length;
  5555. break;
  5556. }
  5557. }
  5558. // transfer data
  5559. var coords = new Float32Array(count * 2);
  5560. var colors = new Uint8Array(count * 3);
  5561. var coordsMap = context.coords, colorsMap = context.colors;
  5562. var pIndex = 0, cIndex = 0;
  5563. for (i = 0, ii = figures.length; i < ii; i++) {
  5564. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5565. switch (figure.type) {
  5566. case 'lattice':
  5567. var cols = figure.verticesPerRow;
  5568. rows = (ps.length / cols) | 0;
  5569. for (var row = 1; row < rows; row++) {
  5570. var offset = row * cols + 1;
  5571. for (var col = 1; col < cols; col++, offset++) {
  5572. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5573. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5574. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5575. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5576. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5577. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5578. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5579. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5580. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5581. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5582. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5583. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5584. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5585. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5586. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5587. coords[pIndex + 6] = coords[pIndex + 2];
  5588. coords[pIndex + 7] = coords[pIndex + 3];
  5589. coords[pIndex + 8] = coords[pIndex + 4];
  5590. coords[pIndex + 9] = coords[pIndex + 5];
  5591. coords[pIndex + 10] = coordsMap[ps[offset]];
  5592. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5593. colors[cIndex + 9] = colors[cIndex + 3];
  5594. colors[cIndex + 10] = colors[cIndex + 4];
  5595. colors[cIndex + 11] = colors[cIndex + 5];
  5596. colors[cIndex + 12] = colors[cIndex + 6];
  5597. colors[cIndex + 13] = colors[cIndex + 7];
  5598. colors[cIndex + 14] = colors[cIndex + 8];
  5599. colors[cIndex + 15] = colorsMap[cs[offset]];
  5600. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5601. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5602. pIndex += 12;
  5603. cIndex += 18;
  5604. }
  5605. }
  5606. break;
  5607. case 'triangles':
  5608. for (var j = 0, jj = ps.length; j < jj; j++) {
  5609. coords[pIndex] = coordsMap[ps[j]];
  5610. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5611. colors[cIndex] = colorsMap[cs[j]];
  5612. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5613. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5614. pIndex += 2;
  5615. cIndex += 3;
  5616. }
  5617. break;
  5618. }
  5619. }
  5620. // draw
  5621. if (backgroundColor) {
  5622. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5623. backgroundColor[2] / 255, 1.0);
  5624. } else {
  5625. gl.clearColor(0, 0, 0, 0);
  5626. }
  5627. gl.clear(gl.COLOR_BUFFER_BIT);
  5628. var coordsBuffer = gl.createBuffer();
  5629. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5630. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5631. gl.enableVertexAttribArray(cache.positionLocation);
  5632. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5633. var colorsBuffer = gl.createBuffer();
  5634. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5635. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5636. gl.enableVertexAttribArray(cache.colorLocation);
  5637. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5638. 0, 0);
  5639. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5640. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5641. gl.drawArrays(gl.TRIANGLES, 0, count);
  5642. gl.flush();
  5643. gl.deleteBuffer(coordsBuffer);
  5644. gl.deleteBuffer(colorsBuffer);
  5645. return canvas;
  5646. }
  5647. function cleanup() {
  5648. if (smaskCache && smaskCache.canvas) {
  5649. smaskCache.canvas.width = 0;
  5650. smaskCache.canvas.height = 0;
  5651. }
  5652. if (figuresCache && figuresCache.canvas) {
  5653. figuresCache.canvas.width = 0;
  5654. figuresCache.canvas.height = 0;
  5655. }
  5656. smaskCache = null;
  5657. figuresCache = null;
  5658. }
  5659. return {
  5660. get isEnabled() {
  5661. if (getDefaultSetting('disableWebGL')) {
  5662. return false;
  5663. }
  5664. var enabled = false;
  5665. try {
  5666. generateGL();
  5667. enabled = !!currentGL;
  5668. } catch (e) { }
  5669. return shadow(this, 'isEnabled', enabled);
  5670. },
  5671. composeSMask: composeSMask,
  5672. drawFigures: drawFigures,
  5673. clear: cleanup
  5674. };
  5675. })();
  5676. exports.WebGLUtils = WebGLUtils;
  5677. }));
  5678. (function (root, factory) {
  5679. {
  5680. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5681. root.pdfjsDisplayWebGL);
  5682. }
  5683. }(this, function (exports, sharedUtil, displayWebGL) {
  5684. var Util = sharedUtil.Util;
  5685. var info = sharedUtil.info;
  5686. var isArray = sharedUtil.isArray;
  5687. var error = sharedUtil.error;
  5688. var WebGLUtils = displayWebGL.WebGLUtils;
  5689. var ShadingIRs = {};
  5690. ShadingIRs.RadialAxial = {
  5691. fromIR: function RadialAxial_fromIR(raw) {
  5692. var type = raw[1];
  5693. var colorStops = raw[2];
  5694. var p0 = raw[3];
  5695. var p1 = raw[4];
  5696. var r0 = raw[5];
  5697. var r1 = raw[6];
  5698. return {
  5699. type: 'Pattern',
  5700. getPattern: function RadialAxial_getPattern(ctx) {
  5701. var grad;
  5702. if (type === 'axial') {
  5703. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5704. } else if (type === 'radial') {
  5705. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5706. }
  5707. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5708. var c = colorStops[i];
  5709. grad.addColorStop(c[0], c[1]);
  5710. }
  5711. return grad;
  5712. }
  5713. };
  5714. }
  5715. };
  5716. var createMeshCanvas = (function createMeshCanvasClosure() {
  5717. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5718. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5719. var coords = context.coords, colors = context.colors;
  5720. var bytes = data.data, rowSize = data.width * 4;
  5721. var tmp;
  5722. if (coords[p1 + 1] > coords[p2 + 1]) {
  5723. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5724. }
  5725. if (coords[p2 + 1] > coords[p3 + 1]) {
  5726. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5727. }
  5728. if (coords[p1 + 1] > coords[p2 + 1]) {
  5729. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5730. }
  5731. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5732. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5733. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5734. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5735. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5736. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5737. if (y1 >= y3) {
  5738. return;
  5739. }
  5740. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5741. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5742. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5743. var minY = Math.round(y1), maxY = Math.round(y3);
  5744. var xa, car, cag, cab;
  5745. var xb, cbr, cbg, cbb;
  5746. var k;
  5747. for (var y = minY; y <= maxY; y++) {
  5748. if (y < y2) {
  5749. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5750. xa = x1 - (x1 - x2) * k;
  5751. car = c1r - (c1r - c2r) * k;
  5752. cag = c1g - (c1g - c2g) * k;
  5753. cab = c1b - (c1b - c2b) * k;
  5754. } else {
  5755. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5756. xa = x2 - (x2 - x3) * k;
  5757. car = c2r - (c2r - c3r) * k;
  5758. cag = c2g - (c2g - c3g) * k;
  5759. cab = c2b - (c2b - c3b) * k;
  5760. }
  5761. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5762. xb = x1 - (x1 - x3) * k;
  5763. cbr = c1r - (c1r - c3r) * k;
  5764. cbg = c1g - (c1g - c3g) * k;
  5765. cbb = c1b - (c1b - c3b) * k;
  5766. var x1_ = Math.round(Math.min(xa, xb));
  5767. var x2_ = Math.round(Math.max(xa, xb));
  5768. var j = rowSize * y + x1_ * 4;
  5769. for (var x = x1_; x <= x2_; x++) {
  5770. k = (xa - x) / (xa - xb);
  5771. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5772. bytes[j++] = (car - (car - cbr) * k) | 0;
  5773. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5774. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5775. bytes[j++] = 255;
  5776. }
  5777. }
  5778. }
  5779. function drawFigure(data, figure, context) {
  5780. var ps = figure.coords;
  5781. var cs = figure.colors;
  5782. var i, ii;
  5783. switch (figure.type) {
  5784. case 'lattice':
  5785. var verticesPerRow = figure.verticesPerRow;
  5786. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5787. var cols = verticesPerRow - 1;
  5788. for (i = 0; i < rows; i++) {
  5789. var q = i * verticesPerRow;
  5790. for (var j = 0; j < cols; j++, q++) {
  5791. drawTriangle(data, context,
  5792. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5793. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5794. drawTriangle(data, context,
  5795. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5796. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5797. }
  5798. }
  5799. break;
  5800. case 'triangles':
  5801. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5802. drawTriangle(data, context,
  5803. ps[i], ps[i + 1], ps[i + 2],
  5804. cs[i], cs[i + 1], cs[i + 2]);
  5805. }
  5806. break;
  5807. default:
  5808. error('illigal figure');
  5809. break;
  5810. }
  5811. }
  5812. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5813. backgroundColor, cachedCanvases) {
  5814. // we will increase scale on some weird factor to let antialiasing take
  5815. // care of "rough" edges
  5816. var EXPECTED_SCALE = 1.1;
  5817. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5818. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5819. // We need to keep transparent border around our pattern for fill():
  5820. // createPattern with 'no-repeat' will bleed edges across entire area.
  5821. var BORDER_SIZE = 2;
  5822. var offsetX = Math.floor(bounds[0]);
  5823. var offsetY = Math.floor(bounds[1]);
  5824. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5825. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5826. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5827. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5828. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5829. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5830. var scaleX = boundsWidth / width;
  5831. var scaleY = boundsHeight / height;
  5832. var context = {
  5833. coords: coords,
  5834. colors: colors,
  5835. offsetX: -offsetX,
  5836. offsetY: -offsetY,
  5837. scaleX: 1 / scaleX,
  5838. scaleY: 1 / scaleY
  5839. };
  5840. var paddedWidth = width + BORDER_SIZE * 2;
  5841. var paddedHeight = height + BORDER_SIZE * 2;
  5842. var canvas, tmpCanvas, i, ii;
  5843. if (WebGLUtils.isEnabled) {
  5844. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5845. figures, context);
  5846. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5847. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5848. false);
  5849. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5850. canvas = tmpCanvas.canvas;
  5851. } else {
  5852. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5853. false);
  5854. var tmpCtx = tmpCanvas.context;
  5855. var data = tmpCtx.createImageData(width, height);
  5856. if (backgroundColor) {
  5857. var bytes = data.data;
  5858. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5859. bytes[i] = backgroundColor[0];
  5860. bytes[i + 1] = backgroundColor[1];
  5861. bytes[i + 2] = backgroundColor[2];
  5862. bytes[i + 3] = 255;
  5863. }
  5864. }
  5865. for (i = 0; i < figures.length; i++) {
  5866. drawFigure(data, figures[i], context);
  5867. }
  5868. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5869. canvas = tmpCanvas.canvas;
  5870. }
  5871. return {canvas: canvas,
  5872. offsetX: offsetX - BORDER_SIZE * scaleX,
  5873. offsetY: offsetY - BORDER_SIZE * scaleY,
  5874. scaleX: scaleX, scaleY: scaleY};
  5875. }
  5876. return createMeshCanvas;
  5877. })();
  5878. ShadingIRs.Mesh = {
  5879. fromIR: function Mesh_fromIR(raw) {
  5880. //var type = raw[1];
  5881. var coords = raw[2];
  5882. var colors = raw[3];
  5883. var figures = raw[4];
  5884. var bounds = raw[5];
  5885. var matrix = raw[6];
  5886. //var bbox = raw[7];
  5887. var background = raw[8];
  5888. return {
  5889. type: 'Pattern',
  5890. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5891. var scale;
  5892. if (shadingFill) {
  5893. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5894. } else {
  5895. // Obtain scale from matrix and current transformation matrix.
  5896. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5897. if (matrix) {
  5898. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5899. scale = [scale[0] * matrixScale[0],
  5900. scale[1] * matrixScale[1]];
  5901. }
  5902. }
  5903. // Rasterizing on the main thread since sending/queue large canvases
  5904. // might cause OOM.
  5905. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5906. colors, figures, shadingFill ? null : background,
  5907. owner.cachedCanvases);
  5908. if (!shadingFill) {
  5909. ctx.setTransform.apply(ctx, owner.baseTransform);
  5910. if (matrix) {
  5911. ctx.transform.apply(ctx, matrix);
  5912. }
  5913. }
  5914. ctx.translate(temporaryPatternCanvas.offsetX,
  5915. temporaryPatternCanvas.offsetY);
  5916. ctx.scale(temporaryPatternCanvas.scaleX,
  5917. temporaryPatternCanvas.scaleY);
  5918. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5919. }
  5920. };
  5921. }
  5922. };
  5923. ShadingIRs.Dummy = {
  5924. fromIR: function Dummy_fromIR() {
  5925. return {
  5926. type: 'Pattern',
  5927. getPattern: function Dummy_fromIR_getPattern() {
  5928. return 'hotpink';
  5929. }
  5930. };
  5931. }
  5932. };
  5933. function getShadingPatternFromIR(raw) {
  5934. var shadingIR = ShadingIRs[raw[0]];
  5935. if (!shadingIR) {
  5936. error('Unknown IR type: ' + raw[0]);
  5937. }
  5938. return shadingIR.fromIR(raw);
  5939. }
  5940. var TilingPattern = (function TilingPatternClosure() {
  5941. var PaintType = {
  5942. COLORED: 1,
  5943. UNCOLORED: 2
  5944. };
  5945. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5946. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5947. this.operatorList = IR[2];
  5948. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5949. this.bbox = IR[4];
  5950. this.xstep = IR[5];
  5951. this.ystep = IR[6];
  5952. this.paintType = IR[7];
  5953. this.tilingType = IR[8];
  5954. this.color = color;
  5955. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5956. this.baseTransform = baseTransform;
  5957. this.type = 'Pattern';
  5958. this.ctx = ctx;
  5959. }
  5960. TilingPattern.prototype = {
  5961. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5962. var operatorList = this.operatorList;
  5963. var bbox = this.bbox;
  5964. var xstep = this.xstep;
  5965. var ystep = this.ystep;
  5966. var paintType = this.paintType;
  5967. var tilingType = this.tilingType;
  5968. var color = this.color;
  5969. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5970. info('TilingType: ' + tilingType);
  5971. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5972. var topLeft = [x0, y0];
  5973. // we want the canvas to be as large as the step size
  5974. var botRight = [x0 + xstep, y0 + ystep];
  5975. var width = botRight[0] - topLeft[0];
  5976. var height = botRight[1] - topLeft[1];
  5977. // Obtain scale from matrix and current transformation matrix.
  5978. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5979. var curMatrixScale = Util.singularValueDecompose2dScale(
  5980. this.baseTransform);
  5981. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5982. matrixScale[1] * curMatrixScale[1]];
  5983. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5984. // Use width and height values that are as close as possible to the end
  5985. // result when the pattern is used. Too low value makes the pattern look
  5986. // blurry. Too large value makes it look too crispy.
  5987. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5988. MAX_PATTERN_SIZE);
  5989. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5990. MAX_PATTERN_SIZE);
  5991. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5992. width, height, true);
  5993. var tmpCtx = tmpCanvas.context;
  5994. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5995. graphics.groupLevel = owner.groupLevel;
  5996. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5997. this.setScale(width, height, xstep, ystep);
  5998. this.transformToScale(graphics);
  5999. // transform coordinates to pattern space
  6000. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  6001. graphics.transform.apply(graphics, tmpTranslate);
  6002. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6003. graphics.executeOperatorList(operatorList);
  6004. return tmpCanvas.canvas;
  6005. },
  6006. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6007. this.scale = [width / xstep, height / ystep];
  6008. },
  6009. transformToScale: function TilingPattern_transformToScale(graphics) {
  6010. var scale = this.scale;
  6011. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  6012. graphics.transform.apply(graphics, tmpScale);
  6013. },
  6014. scaleToContext: function TilingPattern_scaleToContext() {
  6015. var scale = this.scale;
  6016. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6017. },
  6018. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6019. if (bbox && isArray(bbox) && bbox.length === 4) {
  6020. var bboxWidth = x1 - x0;
  6021. var bboxHeight = y1 - y0;
  6022. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6023. graphics.clip();
  6024. graphics.endPath();
  6025. }
  6026. },
  6027. setFillAndStrokeStyleToContext:
  6028. function setFillAndStrokeStyleToContext(context, paintType, color) {
  6029. switch (paintType) {
  6030. case PaintType.COLORED:
  6031. var ctx = this.ctx;
  6032. context.fillStyle = ctx.fillStyle;
  6033. context.strokeStyle = ctx.strokeStyle;
  6034. break;
  6035. case PaintType.UNCOLORED:
  6036. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6037. context.fillStyle = cssColor;
  6038. context.strokeStyle = cssColor;
  6039. break;
  6040. default:
  6041. error('Unsupported paint type: ' + paintType);
  6042. }
  6043. },
  6044. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6045. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6046. ctx = this.ctx;
  6047. ctx.setTransform.apply(ctx, this.baseTransform);
  6048. ctx.transform.apply(ctx, this.matrix);
  6049. this.scaleToContext();
  6050. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6051. }
  6052. };
  6053. return TilingPattern;
  6054. })();
  6055. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6056. exports.TilingPattern = TilingPattern;
  6057. }));
  6058. (function (root, factory) {
  6059. {
  6060. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  6061. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  6062. root.pdfjsDisplayWebGL);
  6063. }
  6064. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  6065. displayWebGL) {
  6066. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6067. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6068. var ImageKind = sharedUtil.ImageKind;
  6069. var OPS = sharedUtil.OPS;
  6070. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6071. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6072. var Util = sharedUtil.Util;
  6073. var assert = sharedUtil.assert;
  6074. var info = sharedUtil.info;
  6075. var isNum = sharedUtil.isNum;
  6076. var isArray = sharedUtil.isArray;
  6077. var isLittleEndian = sharedUtil.isLittleEndian;
  6078. var error = sharedUtil.error;
  6079. var shadow = sharedUtil.shadow;
  6080. var warn = sharedUtil.warn;
  6081. var TilingPattern = displayPatternHelper.TilingPattern;
  6082. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6083. var WebGLUtils = displayWebGL.WebGLUtils;
  6084. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6085. // <canvas> contexts store most of the state we need natively.
  6086. // However, PDF needs a bit more state, which we store here.
  6087. // Minimal font size that would be used during canvas fillText operations.
  6088. var MIN_FONT_SIZE = 16;
  6089. // Maximum font size that would be used during canvas fillText operations.
  6090. var MAX_FONT_SIZE = 100;
  6091. var MAX_GROUP_SIZE = 4096;
  6092. // Heuristic value used when enforcing minimum line widths.
  6093. var MIN_WIDTH_FACTOR = 0.65;
  6094. var COMPILE_TYPE3_GLYPHS = true;
  6095. var MAX_SIZE_TO_COMPILE = 1000;
  6096. var FULL_CHUNK_HEIGHT = 16;
  6097. var HasCanvasTypedArraysCached = {
  6098. get value() {
  6099. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6100. }
  6101. };
  6102. var IsLittleEndianCached = {
  6103. get value() {
  6104. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6105. }
  6106. };
  6107. function createScratchCanvas(width, height) {
  6108. var canvas = document.createElement('canvas');
  6109. canvas.width = width;
  6110. canvas.height = height;
  6111. return canvas;
  6112. }
  6113. function addContextCurrentTransform(ctx) {
  6114. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6115. if (!ctx.mozCurrentTransform) {
  6116. ctx._originalSave = ctx.save;
  6117. ctx._originalRestore = ctx.restore;
  6118. ctx._originalRotate = ctx.rotate;
  6119. ctx._originalScale = ctx.scale;
  6120. ctx._originalTranslate = ctx.translate;
  6121. ctx._originalTransform = ctx.transform;
  6122. ctx._originalSetTransform = ctx.setTransform;
  6123. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6124. ctx._transformStack = [];
  6125. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6126. get: function getCurrentTransform() {
  6127. return this._transformMatrix;
  6128. }
  6129. });
  6130. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6131. get: function getCurrentTransformInverse() {
  6132. // Calculation done using WolframAlpha:
  6133. // http://www.wolframalpha.com/input/?
  6134. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6135. var m = this._transformMatrix;
  6136. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6137. var ad_bc = a * d - b * c;
  6138. var bc_ad = b * c - a * d;
  6139. return [
  6140. d / ad_bc,
  6141. b / bc_ad,
  6142. c / bc_ad,
  6143. a / ad_bc,
  6144. (d * e - c * f) / bc_ad,
  6145. (b * e - a * f) / ad_bc
  6146. ];
  6147. }
  6148. });
  6149. ctx.save = function ctxSave() {
  6150. var old = this._transformMatrix;
  6151. this._transformStack.push(old);
  6152. this._transformMatrix = old.slice(0, 6);
  6153. this._originalSave();
  6154. };
  6155. ctx.restore = function ctxRestore() {
  6156. var prev = this._transformStack.pop();
  6157. if (prev) {
  6158. this._transformMatrix = prev;
  6159. this._originalRestore();
  6160. }
  6161. };
  6162. ctx.translate = function ctxTranslate(x, y) {
  6163. var m = this._transformMatrix;
  6164. m[4] = m[0] * x + m[2] * y + m[4];
  6165. m[5] = m[1] * x + m[3] * y + m[5];
  6166. this._originalTranslate(x, y);
  6167. };
  6168. ctx.scale = function ctxScale(x, y) {
  6169. var m = this._transformMatrix;
  6170. m[0] = m[0] * x;
  6171. m[1] = m[1] * x;
  6172. m[2] = m[2] * y;
  6173. m[3] = m[3] * y;
  6174. this._originalScale(x, y);
  6175. };
  6176. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6177. var m = this._transformMatrix;
  6178. this._transformMatrix = [
  6179. m[0] * a + m[2] * b,
  6180. m[1] * a + m[3] * b,
  6181. m[0] * c + m[2] * d,
  6182. m[1] * c + m[3] * d,
  6183. m[0] * e + m[2] * f + m[4],
  6184. m[1] * e + m[3] * f + m[5]
  6185. ];
  6186. ctx._originalTransform(a, b, c, d, e, f);
  6187. };
  6188. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6189. this._transformMatrix = [a, b, c, d, e, f];
  6190. ctx._originalSetTransform(a, b, c, d, e, f);
  6191. };
  6192. ctx.rotate = function ctxRotate(angle) {
  6193. var cosValue = Math.cos(angle);
  6194. var sinValue = Math.sin(angle);
  6195. var m = this._transformMatrix;
  6196. this._transformMatrix = [
  6197. m[0] * cosValue + m[2] * sinValue,
  6198. m[1] * cosValue + m[3] * sinValue,
  6199. m[0] * (-sinValue) + m[2] * cosValue,
  6200. m[1] * (-sinValue) + m[3] * cosValue,
  6201. m[4],
  6202. m[5]
  6203. ];
  6204. this._originalRotate(angle);
  6205. };
  6206. }
  6207. }
  6208. var CachedCanvases = (function CachedCanvasesClosure() {
  6209. function CachedCanvases() {
  6210. this.cache = Object.create(null);
  6211. }
  6212. CachedCanvases.prototype = {
  6213. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6214. trackTransform) {
  6215. var canvasEntry;
  6216. if (this.cache[id] !== undefined) {
  6217. canvasEntry = this.cache[id];
  6218. canvasEntry.canvas.width = width;
  6219. canvasEntry.canvas.height = height;
  6220. // reset canvas transform for emulated mozCurrentTransform, if needed
  6221. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6222. } else {
  6223. var canvas = createScratchCanvas(width, height);
  6224. var ctx = canvas.getContext('2d');
  6225. if (trackTransform) {
  6226. addContextCurrentTransform(ctx);
  6227. }
  6228. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6229. }
  6230. return canvasEntry;
  6231. },
  6232. clear: function () {
  6233. for (var id in this.cache) {
  6234. var canvasEntry = this.cache[id];
  6235. // Zeroing the width and height causes Firefox to release graphics
  6236. // resources immediately, which can greatly reduce memory consumption.
  6237. canvasEntry.canvas.width = 0;
  6238. canvasEntry.canvas.height = 0;
  6239. delete this.cache[id];
  6240. }
  6241. }
  6242. };
  6243. return CachedCanvases;
  6244. })();
  6245. function compileType3Glyph(imgData) {
  6246. var POINT_TO_PROCESS_LIMIT = 1000;
  6247. var width = imgData.width, height = imgData.height;
  6248. var i, j, j0, width1 = width + 1;
  6249. var points = new Uint8Array(width1 * (height + 1));
  6250. var POINT_TYPES =
  6251. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6252. // decodes bit-packed mask data
  6253. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6254. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6255. for (i = 0, ii = data0.length; i < ii; i++) {
  6256. var mask = 128, elem = data0[i];
  6257. while (mask > 0) {
  6258. data[pos++] = (elem & mask) ? 0 : 255;
  6259. mask >>= 1;
  6260. }
  6261. }
  6262. // finding iteresting points: every point is located between mask pixels,
  6263. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6264. // will have flags assigned based on neighboring mask pixels:
  6265. // 4 | 8
  6266. // --P--
  6267. // 2 | 1
  6268. // We are interested only in points with the flags:
  6269. // - outside corners: 1, 2, 4, 8;
  6270. // - inside corners: 7, 11, 13, 14;
  6271. // - and, intersections: 5, 10.
  6272. var count = 0;
  6273. pos = 0;
  6274. if (data[pos] !== 0) {
  6275. points[0] = 1;
  6276. ++count;
  6277. }
  6278. for (j = 1; j < width; j++) {
  6279. if (data[pos] !== data[pos + 1]) {
  6280. points[j] = data[pos] ? 2 : 1;
  6281. ++count;
  6282. }
  6283. pos++;
  6284. }
  6285. if (data[pos] !== 0) {
  6286. points[j] = 2;
  6287. ++count;
  6288. }
  6289. for (i = 1; i < height; i++) {
  6290. pos = i * lineSize;
  6291. j0 = i * width1;
  6292. if (data[pos - lineSize] !== data[pos]) {
  6293. points[j0] = data[pos] ? 1 : 8;
  6294. ++count;
  6295. }
  6296. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6297. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6298. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6299. for (j = 1; j < width; j++) {
  6300. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6301. (data[pos - lineSize + 1] ? 8 : 0);
  6302. if (POINT_TYPES[sum]) {
  6303. points[j0 + j] = POINT_TYPES[sum];
  6304. ++count;
  6305. }
  6306. pos++;
  6307. }
  6308. if (data[pos - lineSize] !== data[pos]) {
  6309. points[j0 + j] = data[pos] ? 2 : 4;
  6310. ++count;
  6311. }
  6312. if (count > POINT_TO_PROCESS_LIMIT) {
  6313. return null;
  6314. }
  6315. }
  6316. pos = lineSize * (height - 1);
  6317. j0 = i * width1;
  6318. if (data[pos] !== 0) {
  6319. points[j0] = 8;
  6320. ++count;
  6321. }
  6322. for (j = 1; j < width; j++) {
  6323. if (data[pos] !== data[pos + 1]) {
  6324. points[j0 + j] = data[pos] ? 4 : 8;
  6325. ++count;
  6326. }
  6327. pos++;
  6328. }
  6329. if (data[pos] !== 0) {
  6330. points[j0 + j] = 4;
  6331. ++count;
  6332. }
  6333. if (count > POINT_TO_PROCESS_LIMIT) {
  6334. return null;
  6335. }
  6336. // building outlines
  6337. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6338. var outlines = [];
  6339. for (i = 0; count && i <= height; i++) {
  6340. var p = i * width1;
  6341. var end = p + width;
  6342. while (p < end && !points[p]) {
  6343. p++;
  6344. }
  6345. if (p === end) {
  6346. continue;
  6347. }
  6348. var coords = [p % width1, i];
  6349. var type = points[p], p0 = p, pp;
  6350. do {
  6351. var step = steps[type];
  6352. do {
  6353. p += step;
  6354. } while (!points[p]);
  6355. pp = points[p];
  6356. if (pp !== 5 && pp !== 10) {
  6357. // set new direction
  6358. type = pp;
  6359. // delete mark
  6360. points[p] = 0;
  6361. } else { // type is 5 or 10, ie, a crossing
  6362. // set new direction
  6363. type = pp & ((0x33 * type) >> 4);
  6364. // set new type for "future hit"
  6365. points[p] &= (type >> 2 | type << 2);
  6366. }
  6367. coords.push(p % width1);
  6368. coords.push((p / width1) | 0);
  6369. --count;
  6370. } while (p0 !== p);
  6371. outlines.push(coords);
  6372. --i;
  6373. }
  6374. var drawOutline = function(c) {
  6375. c.save();
  6376. // the path shall be painted in [0..1]x[0..1] space
  6377. c.scale(1 / width, -1 / height);
  6378. c.translate(0, -height);
  6379. c.beginPath();
  6380. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6381. var o = outlines[i];
  6382. c.moveTo(o[0], o[1]);
  6383. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6384. c.lineTo(o[j], o[j+1]);
  6385. }
  6386. }
  6387. c.fill();
  6388. c.beginPath();
  6389. c.restore();
  6390. };
  6391. return drawOutline;
  6392. }
  6393. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6394. function CanvasExtraState(old) {
  6395. // Are soft masks and alpha values shapes or opacities?
  6396. this.alphaIsShape = false;
  6397. this.fontSize = 0;
  6398. this.fontSizeScale = 1;
  6399. this.textMatrix = IDENTITY_MATRIX;
  6400. this.textMatrixScale = 1;
  6401. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6402. this.leading = 0;
  6403. // Current point (in user coordinates)
  6404. this.x = 0;
  6405. this.y = 0;
  6406. // Start of text line (in text coordinates)
  6407. this.lineX = 0;
  6408. this.lineY = 0;
  6409. // Character and word spacing
  6410. this.charSpacing = 0;
  6411. this.wordSpacing = 0;
  6412. this.textHScale = 1;
  6413. this.textRenderingMode = TextRenderingMode.FILL;
  6414. this.textRise = 0;
  6415. // Default fore and background colors
  6416. this.fillColor = '#000000';
  6417. this.strokeColor = '#000000';
  6418. this.patternFill = false;
  6419. // Note: fill alpha applies to all non-stroking operations
  6420. this.fillAlpha = 1;
  6421. this.strokeAlpha = 1;
  6422. this.lineWidth = 1;
  6423. this.activeSMask = null;
  6424. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6425. this.old = old;
  6426. }
  6427. CanvasExtraState.prototype = {
  6428. clone: function CanvasExtraState_clone() {
  6429. return Object.create(this);
  6430. },
  6431. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6432. this.x = x;
  6433. this.y = y;
  6434. }
  6435. };
  6436. return CanvasExtraState;
  6437. })();
  6438. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6439. // Defines the time the executeOperatorList is going to be executing
  6440. // before it stops and shedules a continue of execution.
  6441. var EXECUTION_TIME = 15;
  6442. // Defines the number of steps before checking the execution time
  6443. var EXECUTION_STEPS = 10;
  6444. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6445. this.ctx = canvasCtx;
  6446. this.current = new CanvasExtraState();
  6447. this.stateStack = [];
  6448. this.pendingClip = null;
  6449. this.pendingEOFill = false;
  6450. this.res = null;
  6451. this.xobjs = null;
  6452. this.commonObjs = commonObjs;
  6453. this.objs = objs;
  6454. this.imageLayer = imageLayer;
  6455. this.groupStack = [];
  6456. this.processingType3 = null;
  6457. // Patterns are painted relative to the initial page/form transform, see pdf
  6458. // spec 8.7.2 NOTE 1.
  6459. this.baseTransform = null;
  6460. this.baseTransformStack = [];
  6461. this.groupLevel = 0;
  6462. this.smaskStack = [];
  6463. this.smaskCounter = 0;
  6464. this.tempSMask = null;
  6465. this.cachedCanvases = new CachedCanvases();
  6466. if (canvasCtx) {
  6467. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6468. // the transformation must already be set in canvasCtx._transformMatrix.
  6469. addContextCurrentTransform(canvasCtx);
  6470. }
  6471. this.cachedGetSinglePixelWidth = null;
  6472. }
  6473. function putBinaryImageData(ctx, imgData) {
  6474. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6475. ctx.putImageData(imgData, 0, 0);
  6476. return;
  6477. }
  6478. // Put the image data to the canvas in chunks, rather than putting the
  6479. // whole image at once. This saves JS memory, because the ImageData object
  6480. // is smaller. It also possibly saves C++ memory within the implementation
  6481. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6482. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6483. // because too many putImageData() calls will slow things down.
  6484. //
  6485. // Note: as written, if the last chunk is partial, the putImageData() call
  6486. // will (conceptually) put pixels past the bounds of the canvas. But
  6487. // that's ok; any such pixels are ignored.
  6488. var height = imgData.height, width = imgData.width;
  6489. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6490. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6491. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6492. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6493. var srcPos = 0, destPos;
  6494. var src = imgData.data;
  6495. var dest = chunkImgData.data;
  6496. var i, j, thisChunkHeight, elemsInThisChunk;
  6497. // There are multiple forms in which the pixel data can be passed, and
  6498. // imgData.kind tells us which one this is.
  6499. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6500. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6501. var srcLength = src.byteLength;
  6502. var dest32 = HasCanvasTypedArraysCached.value ?
  6503. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6504. var dest32DataLength = dest32.length;
  6505. var fullSrcDiff = (width + 7) >> 3;
  6506. var white = 0xFFFFFFFF;
  6507. var black = (IsLittleEndianCached.value ||
  6508. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6509. for (i = 0; i < totalChunks; i++) {
  6510. thisChunkHeight =
  6511. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6512. destPos = 0;
  6513. for (j = 0; j < thisChunkHeight; j++) {
  6514. var srcDiff = srcLength - srcPos;
  6515. var k = 0;
  6516. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6517. var kEndUnrolled = kEnd & ~7;
  6518. var mask = 0;
  6519. var srcByte = 0;
  6520. for (; k < kEndUnrolled; k += 8) {
  6521. srcByte = src[srcPos++];
  6522. dest32[destPos++] = (srcByte & 128) ? white : black;
  6523. dest32[destPos++] = (srcByte & 64) ? white : black;
  6524. dest32[destPos++] = (srcByte & 32) ? white : black;
  6525. dest32[destPos++] = (srcByte & 16) ? white : black;
  6526. dest32[destPos++] = (srcByte & 8) ? white : black;
  6527. dest32[destPos++] = (srcByte & 4) ? white : black;
  6528. dest32[destPos++] = (srcByte & 2) ? white : black;
  6529. dest32[destPos++] = (srcByte & 1) ? white : black;
  6530. }
  6531. for (; k < kEnd; k++) {
  6532. if (mask === 0) {
  6533. srcByte = src[srcPos++];
  6534. mask = 128;
  6535. }
  6536. dest32[destPos++] = (srcByte & mask) ? white : black;
  6537. mask >>= 1;
  6538. }
  6539. }
  6540. // We ran out of input. Make all remaining pixels transparent.
  6541. while (destPos < dest32DataLength) {
  6542. dest32[destPos++] = 0;
  6543. }
  6544. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6545. }
  6546. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6547. // RGBA, 32-bits per pixel.
  6548. j = 0;
  6549. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6550. for (i = 0; i < fullChunks; i++) {
  6551. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6552. srcPos += elemsInThisChunk;
  6553. ctx.putImageData(chunkImgData, 0, j);
  6554. j += FULL_CHUNK_HEIGHT;
  6555. }
  6556. if (i < totalChunks) {
  6557. elemsInThisChunk = width * partialChunkHeight * 4;
  6558. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6559. ctx.putImageData(chunkImgData, 0, j);
  6560. }
  6561. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6562. // RGB, 24-bits per pixel.
  6563. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6564. elemsInThisChunk = width * thisChunkHeight;
  6565. for (i = 0; i < totalChunks; i++) {
  6566. if (i >= fullChunks) {
  6567. thisChunkHeight = partialChunkHeight;
  6568. elemsInThisChunk = width * thisChunkHeight;
  6569. }
  6570. destPos = 0;
  6571. for (j = elemsInThisChunk; j--;) {
  6572. dest[destPos++] = src[srcPos++];
  6573. dest[destPos++] = src[srcPos++];
  6574. dest[destPos++] = src[srcPos++];
  6575. dest[destPos++] = 255;
  6576. }
  6577. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6578. }
  6579. } else {
  6580. error('bad image kind: ' + imgData.kind);
  6581. }
  6582. }
  6583. function putBinaryImageMask(ctx, imgData) {
  6584. var height = imgData.height, width = imgData.width;
  6585. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6586. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6587. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6588. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6589. var srcPos = 0;
  6590. var src = imgData.data;
  6591. var dest = chunkImgData.data;
  6592. for (var i = 0; i < totalChunks; i++) {
  6593. var thisChunkHeight =
  6594. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6595. // Expand the mask so it can be used by the canvas. Any required
  6596. // inversion has already been handled.
  6597. var destPos = 3; // alpha component offset
  6598. for (var j = 0; j < thisChunkHeight; j++) {
  6599. var mask = 0;
  6600. for (var k = 0; k < width; k++) {
  6601. if (!mask) {
  6602. var elem = src[srcPos++];
  6603. mask = 128;
  6604. }
  6605. dest[destPos] = (elem & mask) ? 0 : 255;
  6606. destPos += 4;
  6607. mask >>= 1;
  6608. }
  6609. }
  6610. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6611. }
  6612. }
  6613. function copyCtxState(sourceCtx, destCtx) {
  6614. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6615. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6616. 'globalCompositeOperation', 'font'];
  6617. for (var i = 0, ii = properties.length; i < ii; i++) {
  6618. var property = properties[i];
  6619. if (sourceCtx[property] !== undefined) {
  6620. destCtx[property] = sourceCtx[property];
  6621. }
  6622. }
  6623. if (sourceCtx.setLineDash !== undefined) {
  6624. destCtx.setLineDash(sourceCtx.getLineDash());
  6625. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6626. }
  6627. }
  6628. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6629. var length = bytes.length;
  6630. for (var i = 3; i < length; i += 4) {
  6631. var alpha = bytes[i];
  6632. if (alpha === 0) {
  6633. bytes[i - 3] = r0;
  6634. bytes[i - 2] = g0;
  6635. bytes[i - 1] = b0;
  6636. } else if (alpha < 255) {
  6637. var alpha_ = 255 - alpha;
  6638. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6639. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6640. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6641. }
  6642. }
  6643. }
  6644. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6645. var length = maskData.length;
  6646. var scale = 1 / 255;
  6647. for (var i = 3; i < length; i += 4) {
  6648. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6649. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6650. }
  6651. }
  6652. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6653. var length = maskData.length;
  6654. for (var i = 3; i < length; i += 4) {
  6655. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6656. (maskData[i - 2] * 152) + // * 0.59 ....
  6657. (maskData[i - 1] * 28); // * 0.11 ....
  6658. layerData[i] = transferMap ?
  6659. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6660. (layerData[i] * y) >> 16;
  6661. }
  6662. }
  6663. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6664. subtype, backdrop, transferMap) {
  6665. var hasBackdrop = !!backdrop;
  6666. var r0 = hasBackdrop ? backdrop[0] : 0;
  6667. var g0 = hasBackdrop ? backdrop[1] : 0;
  6668. var b0 = hasBackdrop ? backdrop[2] : 0;
  6669. var composeFn;
  6670. if (subtype === 'Luminosity') {
  6671. composeFn = composeSMaskLuminosity;
  6672. } else {
  6673. composeFn = composeSMaskAlpha;
  6674. }
  6675. // processing image in chunks to save memory
  6676. var PIXELS_TO_PROCESS = 1048576;
  6677. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6678. for (var row = 0; row < height; row += chunkSize) {
  6679. var chunkHeight = Math.min(chunkSize, height - row);
  6680. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6681. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6682. if (hasBackdrop) {
  6683. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6684. }
  6685. composeFn(maskData.data, layerData.data, transferMap);
  6686. maskCtx.putImageData(layerData, 0, row);
  6687. }
  6688. }
  6689. function composeSMask(ctx, smask, layerCtx) {
  6690. var mask = smask.canvas;
  6691. var maskCtx = smask.context;
  6692. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6693. smask.offsetX, smask.offsetY);
  6694. var backdrop = smask.backdrop || null;
  6695. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6696. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6697. {subtype: smask.subtype, backdrop: backdrop});
  6698. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6699. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6700. return;
  6701. }
  6702. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6703. smask.subtype, backdrop, smask.transferMap);
  6704. ctx.drawImage(mask, 0, 0);
  6705. }
  6706. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6707. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6708. var NORMAL_CLIP = {};
  6709. var EO_CLIP = {};
  6710. CanvasGraphics.prototype = {
  6711. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6712. transparency) {
  6713. // For pdfs that use blend modes we have to clear the canvas else certain
  6714. // blend modes can look wrong since we'd be blending with a white
  6715. // backdrop. The problem with a transparent backdrop though is we then
  6716. // don't get sub pixel anti aliasing on text, creating temporary
  6717. // transparent canvas when we have blend modes.
  6718. var width = this.ctx.canvas.width;
  6719. var height = this.ctx.canvas.height;
  6720. this.ctx.save();
  6721. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6722. this.ctx.fillRect(0, 0, width, height);
  6723. this.ctx.restore();
  6724. if (transparency) {
  6725. var transparentCanvas = this.cachedCanvases.getCanvas(
  6726. 'transparent', width, height, true);
  6727. this.compositeCtx = this.ctx;
  6728. this.transparentCanvas = transparentCanvas.canvas;
  6729. this.ctx = transparentCanvas.context;
  6730. this.ctx.save();
  6731. // The transform can be applied before rendering, transferring it to
  6732. // the new canvas.
  6733. this.ctx.transform.apply(this.ctx,
  6734. this.compositeCtx.mozCurrentTransform);
  6735. }
  6736. this.ctx.save();
  6737. if (transform) {
  6738. this.ctx.transform.apply(this.ctx, transform);
  6739. }
  6740. this.ctx.transform.apply(this.ctx, viewport.transform);
  6741. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6742. if (this.imageLayer) {
  6743. this.imageLayer.beginLayout();
  6744. }
  6745. },
  6746. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6747. operatorList,
  6748. executionStartIdx, continueCallback,
  6749. stepper) {
  6750. var argsArray = operatorList.argsArray;
  6751. var fnArray = operatorList.fnArray;
  6752. var i = executionStartIdx || 0;
  6753. var argsArrayLen = argsArray.length;
  6754. // Sometimes the OperatorList to execute is empty.
  6755. if (argsArrayLen === i) {
  6756. return i;
  6757. }
  6758. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6759. typeof continueCallback === 'function');
  6760. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6761. var steps = 0;
  6762. var commonObjs = this.commonObjs;
  6763. var objs = this.objs;
  6764. var fnId;
  6765. while (true) {
  6766. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6767. stepper.breakIt(i, continueCallback);
  6768. return i;
  6769. }
  6770. fnId = fnArray[i];
  6771. if (fnId !== OPS.dependency) {
  6772. this[fnId].apply(this, argsArray[i]);
  6773. } else {
  6774. var deps = argsArray[i];
  6775. for (var n = 0, nn = deps.length; n < nn; n++) {
  6776. var depObjId = deps[n];
  6777. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6778. var objsPool = common ? commonObjs : objs;
  6779. // If the promise isn't resolved yet, add the continueCallback
  6780. // to the promise and bail out.
  6781. if (!objsPool.isResolved(depObjId)) {
  6782. objsPool.get(depObjId, continueCallback);
  6783. return i;
  6784. }
  6785. }
  6786. }
  6787. i++;
  6788. // If the entire operatorList was executed, stop as were done.
  6789. if (i === argsArrayLen) {
  6790. return i;
  6791. }
  6792. // If the execution took longer then a certain amount of time and
  6793. // `continueCallback` is specified, interrupt the execution.
  6794. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6795. if (Date.now() > endTime) {
  6796. continueCallback();
  6797. return i;
  6798. }
  6799. steps = 0;
  6800. }
  6801. // If the operatorList isn't executed completely yet OR the execution
  6802. // time was short enough, do another execution round.
  6803. }
  6804. },
  6805. endDrawing: function CanvasGraphics_endDrawing() {
  6806. // Finishing all opened operations such as SMask group painting.
  6807. if (this.current.activeSMask !== null) {
  6808. this.endSMaskGroup();
  6809. }
  6810. this.ctx.restore();
  6811. if (this.transparentCanvas) {
  6812. this.ctx = this.compositeCtx;
  6813. this.ctx.save();
  6814. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6815. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6816. this.ctx.restore();
  6817. this.transparentCanvas = null;
  6818. }
  6819. this.cachedCanvases.clear();
  6820. WebGLUtils.clear();
  6821. if (this.imageLayer) {
  6822. this.imageLayer.endLayout();
  6823. }
  6824. },
  6825. // Graphics state
  6826. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6827. this.current.lineWidth = width;
  6828. this.ctx.lineWidth = width;
  6829. },
  6830. setLineCap: function CanvasGraphics_setLineCap(style) {
  6831. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6832. },
  6833. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6834. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6835. },
  6836. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6837. this.ctx.miterLimit = limit;
  6838. },
  6839. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6840. var ctx = this.ctx;
  6841. if (ctx.setLineDash !== undefined) {
  6842. ctx.setLineDash(dashArray);
  6843. ctx.lineDashOffset = dashPhase;
  6844. }
  6845. },
  6846. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6847. // Maybe if we one day fully support color spaces this will be important
  6848. // for now we can ignore.
  6849. // TODO set rendering intent?
  6850. },
  6851. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6852. // There's no way to control this with canvas, but we can safely ignore.
  6853. // TODO set flatness?
  6854. },
  6855. setGState: function CanvasGraphics_setGState(states) {
  6856. for (var i = 0, ii = states.length; i < ii; i++) {
  6857. var state = states[i];
  6858. var key = state[0];
  6859. var value = state[1];
  6860. switch (key) {
  6861. case 'LW':
  6862. this.setLineWidth(value);
  6863. break;
  6864. case 'LC':
  6865. this.setLineCap(value);
  6866. break;
  6867. case 'LJ':
  6868. this.setLineJoin(value);
  6869. break;
  6870. case 'ML':
  6871. this.setMiterLimit(value);
  6872. break;
  6873. case 'D':
  6874. this.setDash(value[0], value[1]);
  6875. break;
  6876. case 'RI':
  6877. this.setRenderingIntent(value);
  6878. break;
  6879. case 'FL':
  6880. this.setFlatness(value);
  6881. break;
  6882. case 'Font':
  6883. this.setFont(value[0], value[1]);
  6884. break;
  6885. case 'CA':
  6886. this.current.strokeAlpha = state[1];
  6887. break;
  6888. case 'ca':
  6889. this.current.fillAlpha = state[1];
  6890. this.ctx.globalAlpha = state[1];
  6891. break;
  6892. case 'BM':
  6893. if (value && value.name && (value.name !== 'Normal')) {
  6894. var mode = value.name.replace(/([A-Z])/g,
  6895. function(c) {
  6896. return '-' + c.toLowerCase();
  6897. }
  6898. ).substring(1);
  6899. this.ctx.globalCompositeOperation = mode;
  6900. if (this.ctx.globalCompositeOperation !== mode) {
  6901. warn('globalCompositeOperation "' + mode +
  6902. '" is not supported');
  6903. }
  6904. } else {
  6905. this.ctx.globalCompositeOperation = 'source-over';
  6906. }
  6907. break;
  6908. case 'SMask':
  6909. if (this.current.activeSMask) {
  6910. // If SMask is currrenly used, it needs to be suspended or
  6911. // finished. Suspend only makes sense when at least one save()
  6912. // was performed and state needs to be reverted on restore().
  6913. if (this.stateStack.length > 0 &&
  6914. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6915. this.current.activeSMask)) {
  6916. this.suspendSMaskGroup();
  6917. } else {
  6918. this.endSMaskGroup();
  6919. }
  6920. }
  6921. this.current.activeSMask = value ? this.tempSMask : null;
  6922. if (this.current.activeSMask) {
  6923. this.beginSMaskGroup();
  6924. }
  6925. this.tempSMask = null;
  6926. break;
  6927. }
  6928. }
  6929. },
  6930. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6931. var activeSMask = this.current.activeSMask;
  6932. var drawnWidth = activeSMask.canvas.width;
  6933. var drawnHeight = activeSMask.canvas.height;
  6934. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6935. var scratchCanvas = this.cachedCanvases.getCanvas(
  6936. cacheId, drawnWidth, drawnHeight, true);
  6937. var currentCtx = this.ctx;
  6938. var currentTransform = currentCtx.mozCurrentTransform;
  6939. this.ctx.save();
  6940. var groupCtx = scratchCanvas.context;
  6941. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6942. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6943. groupCtx.transform.apply(groupCtx, currentTransform);
  6944. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6945. copyCtxState(currentCtx, groupCtx);
  6946. this.ctx = groupCtx;
  6947. this.setGState([
  6948. ['BM', 'Normal'],
  6949. ['ca', 1],
  6950. ['CA', 1]
  6951. ]);
  6952. this.groupStack.push(currentCtx);
  6953. this.groupLevel++;
  6954. },
  6955. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6956. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  6957. // and future ctx state restored.
  6958. var groupCtx = this.ctx;
  6959. this.groupLevel--;
  6960. this.ctx = this.groupStack.pop();
  6961. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6962. this.ctx.restore();
  6963. this.ctx.save(); // save is needed since SMask will be resumed.
  6964. copyCtxState(groupCtx, this.ctx);
  6965. // Saving state for resuming.
  6966. this.current.resumeSMaskCtx = groupCtx;
  6967. // Transform was changed in the SMask canvas, reflecting this change on
  6968. // this.ctx.
  6969. var deltaTransform = Util.transform(
  6970. this.current.activeSMask.startTransformInverse,
  6971. groupCtx.mozCurrentTransform);
  6972. this.ctx.transform.apply(this.ctx, deltaTransform);
  6973. // SMask was composed, the results at the groupCtx can be cleared.
  6974. groupCtx.save();
  6975. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  6976. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  6977. groupCtx.restore();
  6978. },
  6979. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6980. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  6981. // any groupCtx state since restore() command (the only caller) will do
  6982. // that for us. See also beginSMaskGroup.
  6983. var groupCtx = this.current.resumeSMaskCtx;
  6984. var currentCtx = this.ctx;
  6985. this.ctx = groupCtx;
  6986. this.groupStack.push(currentCtx);
  6987. this.groupLevel++;
  6988. },
  6989. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6990. var groupCtx = this.ctx;
  6991. this.groupLevel--;
  6992. this.ctx = this.groupStack.pop();
  6993. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6994. this.ctx.restore();
  6995. copyCtxState(groupCtx, this.ctx);
  6996. // Transform was changed in the SMask canvas, reflecting this change on
  6997. // this.ctx.
  6998. var deltaTransform = Util.transform(
  6999. this.current.activeSMask.startTransformInverse,
  7000. groupCtx.mozCurrentTransform);
  7001. this.ctx.transform.apply(this.ctx, deltaTransform);
  7002. },
  7003. save: function CanvasGraphics_save() {
  7004. this.ctx.save();
  7005. var old = this.current;
  7006. this.stateStack.push(old);
  7007. this.current = old.clone();
  7008. this.current.resumeSMaskCtx = null;
  7009. },
  7010. restore: function CanvasGraphics_restore() {
  7011. // SMask was suspended, we just need to resume it.
  7012. if (this.current.resumeSMaskCtx) {
  7013. this.resumeSMaskGroup();
  7014. }
  7015. // SMask has to be finished once there is no states that are using the
  7016. // same SMask.
  7017. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  7018. this.stateStack[this.stateStack.length - 1].activeSMask !==
  7019. this.current.activeSMask)) {
  7020. this.endSMaskGroup();
  7021. }
  7022. if (this.stateStack.length !== 0) {
  7023. this.current = this.stateStack.pop();
  7024. this.ctx.restore();
  7025. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7026. this.pendingClip = null;
  7027. this.cachedGetSinglePixelWidth = null;
  7028. }
  7029. },
  7030. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7031. this.ctx.transform(a, b, c, d, e, f);
  7032. this.cachedGetSinglePixelWidth = null;
  7033. },
  7034. // Path
  7035. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7036. var ctx = this.ctx;
  7037. var current = this.current;
  7038. var x = current.x, y = current.y;
  7039. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7040. switch (ops[i] | 0) {
  7041. case OPS.rectangle:
  7042. x = args[j++];
  7043. y = args[j++];
  7044. var width = args[j++];
  7045. var height = args[j++];
  7046. if (width === 0) {
  7047. width = this.getSinglePixelWidth();
  7048. }
  7049. if (height === 0) {
  7050. height = this.getSinglePixelWidth();
  7051. }
  7052. var xw = x + width;
  7053. var yh = y + height;
  7054. this.ctx.moveTo(x, y);
  7055. this.ctx.lineTo(xw, y);
  7056. this.ctx.lineTo(xw, yh);
  7057. this.ctx.lineTo(x, yh);
  7058. this.ctx.lineTo(x, y);
  7059. this.ctx.closePath();
  7060. break;
  7061. case OPS.moveTo:
  7062. x = args[j++];
  7063. y = args[j++];
  7064. ctx.moveTo(x, y);
  7065. break;
  7066. case OPS.lineTo:
  7067. x = args[j++];
  7068. y = args[j++];
  7069. ctx.lineTo(x, y);
  7070. break;
  7071. case OPS.curveTo:
  7072. x = args[j + 4];
  7073. y = args[j + 5];
  7074. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  7075. x, y);
  7076. j += 6;
  7077. break;
  7078. case OPS.curveTo2:
  7079. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  7080. args[j + 2], args[j + 3]);
  7081. x = args[j + 2];
  7082. y = args[j + 3];
  7083. j += 4;
  7084. break;
  7085. case OPS.curveTo3:
  7086. x = args[j + 2];
  7087. y = args[j + 3];
  7088. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7089. j += 4;
  7090. break;
  7091. case OPS.closePath:
  7092. ctx.closePath();
  7093. break;
  7094. }
  7095. }
  7096. current.setCurrentPoint(x, y);
  7097. },
  7098. closePath: function CanvasGraphics_closePath() {
  7099. this.ctx.closePath();
  7100. },
  7101. stroke: function CanvasGraphics_stroke(consumePath) {
  7102. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7103. var ctx = this.ctx;
  7104. var strokeColor = this.current.strokeColor;
  7105. // Prevent drawing too thin lines by enforcing a minimum line width.
  7106. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7107. this.current.lineWidth);
  7108. // For stroke we want to temporarily change the global alpha to the
  7109. // stroking alpha.
  7110. ctx.globalAlpha = this.current.strokeAlpha;
  7111. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7112. strokeColor.type === 'Pattern') {
  7113. // for patterns, we transform to pattern space, calculate
  7114. // the pattern, call stroke, and restore to user space
  7115. ctx.save();
  7116. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7117. ctx.stroke();
  7118. ctx.restore();
  7119. } else {
  7120. ctx.stroke();
  7121. }
  7122. if (consumePath) {
  7123. this.consumePath();
  7124. }
  7125. // Restore the global alpha to the fill alpha
  7126. ctx.globalAlpha = this.current.fillAlpha;
  7127. },
  7128. closeStroke: function CanvasGraphics_closeStroke() {
  7129. this.closePath();
  7130. this.stroke();
  7131. },
  7132. fill: function CanvasGraphics_fill(consumePath) {
  7133. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7134. var ctx = this.ctx;
  7135. var fillColor = this.current.fillColor;
  7136. var isPatternFill = this.current.patternFill;
  7137. var needRestore = false;
  7138. if (isPatternFill) {
  7139. ctx.save();
  7140. if (this.baseTransform) {
  7141. ctx.setTransform.apply(ctx, this.baseTransform);
  7142. }
  7143. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7144. needRestore = true;
  7145. }
  7146. if (this.pendingEOFill) {
  7147. if (ctx.mozFillRule !== undefined) {
  7148. ctx.mozFillRule = 'evenodd';
  7149. ctx.fill();
  7150. ctx.mozFillRule = 'nonzero';
  7151. } else {
  7152. ctx.fill('evenodd');
  7153. }
  7154. this.pendingEOFill = false;
  7155. } else {
  7156. ctx.fill();
  7157. }
  7158. if (needRestore) {
  7159. ctx.restore();
  7160. }
  7161. if (consumePath) {
  7162. this.consumePath();
  7163. }
  7164. },
  7165. eoFill: function CanvasGraphics_eoFill() {
  7166. this.pendingEOFill = true;
  7167. this.fill();
  7168. },
  7169. fillStroke: function CanvasGraphics_fillStroke() {
  7170. this.fill(false);
  7171. this.stroke(false);
  7172. this.consumePath();
  7173. },
  7174. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7175. this.pendingEOFill = true;
  7176. this.fillStroke();
  7177. },
  7178. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7179. this.closePath();
  7180. this.fillStroke();
  7181. },
  7182. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7183. this.pendingEOFill = true;
  7184. this.closePath();
  7185. this.fillStroke();
  7186. },
  7187. endPath: function CanvasGraphics_endPath() {
  7188. this.consumePath();
  7189. },
  7190. // Clipping
  7191. clip: function CanvasGraphics_clip() {
  7192. this.pendingClip = NORMAL_CLIP;
  7193. },
  7194. eoClip: function CanvasGraphics_eoClip() {
  7195. this.pendingClip = EO_CLIP;
  7196. },
  7197. // Text
  7198. beginText: function CanvasGraphics_beginText() {
  7199. this.current.textMatrix = IDENTITY_MATRIX;
  7200. this.current.textMatrixScale = 1;
  7201. this.current.x = this.current.lineX = 0;
  7202. this.current.y = this.current.lineY = 0;
  7203. },
  7204. endText: function CanvasGraphics_endText() {
  7205. var paths = this.pendingTextPaths;
  7206. var ctx = this.ctx;
  7207. if (paths === undefined) {
  7208. ctx.beginPath();
  7209. return;
  7210. }
  7211. ctx.save();
  7212. ctx.beginPath();
  7213. for (var i = 0; i < paths.length; i++) {
  7214. var path = paths[i];
  7215. ctx.setTransform.apply(ctx, path.transform);
  7216. ctx.translate(path.x, path.y);
  7217. path.addToPath(ctx, path.fontSize);
  7218. }
  7219. ctx.restore();
  7220. ctx.clip();
  7221. ctx.beginPath();
  7222. delete this.pendingTextPaths;
  7223. },
  7224. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7225. this.current.charSpacing = spacing;
  7226. },
  7227. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7228. this.current.wordSpacing = spacing;
  7229. },
  7230. setHScale: function CanvasGraphics_setHScale(scale) {
  7231. this.current.textHScale = scale / 100;
  7232. },
  7233. setLeading: function CanvasGraphics_setLeading(leading) {
  7234. this.current.leading = -leading;
  7235. },
  7236. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7237. var fontObj = this.commonObjs.get(fontRefName);
  7238. var current = this.current;
  7239. if (!fontObj) {
  7240. error('Can\'t find font for ' + fontRefName);
  7241. }
  7242. current.fontMatrix = (fontObj.fontMatrix ?
  7243. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7244. // A valid matrix needs all main diagonal elements to be non-zero
  7245. // This also ensures we bypass FF bugzilla bug #719844.
  7246. if (current.fontMatrix[0] === 0 ||
  7247. current.fontMatrix[3] === 0) {
  7248. warn('Invalid font matrix for font ' + fontRefName);
  7249. }
  7250. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7251. // and in some docs this can be negative (inverted x-y axes).
  7252. if (size < 0) {
  7253. size = -size;
  7254. current.fontDirection = -1;
  7255. } else {
  7256. current.fontDirection = 1;
  7257. }
  7258. this.current.font = fontObj;
  7259. this.current.fontSize = size;
  7260. if (fontObj.isType3Font) {
  7261. return; // we don't need ctx.font for Type3 fonts
  7262. }
  7263. var name = fontObj.loadedName || 'sans-serif';
  7264. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7265. (fontObj.bold ? 'bold' : 'normal');
  7266. var italic = fontObj.italic ? 'italic' : 'normal';
  7267. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7268. // Some font backends cannot handle fonts below certain size.
  7269. // Keeping the font at minimal size and using the fontSizeScale to change
  7270. // the current transformation matrix before the fillText/strokeText.
  7271. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7272. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7273. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7274. this.current.fontSizeScale = size / browserFontSize;
  7275. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7276. this.ctx.font = rule;
  7277. },
  7278. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7279. this.current.textRenderingMode = mode;
  7280. },
  7281. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7282. this.current.textRise = rise;
  7283. },
  7284. moveText: function CanvasGraphics_moveText(x, y) {
  7285. this.current.x = this.current.lineX += x;
  7286. this.current.y = this.current.lineY += y;
  7287. },
  7288. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7289. this.setLeading(-y);
  7290. this.moveText(x, y);
  7291. },
  7292. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7293. this.current.textMatrix = [a, b, c, d, e, f];
  7294. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7295. this.current.x = this.current.lineX = 0;
  7296. this.current.y = this.current.lineY = 0;
  7297. },
  7298. nextLine: function CanvasGraphics_nextLine() {
  7299. this.moveText(0, this.current.leading);
  7300. },
  7301. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7302. var ctx = this.ctx;
  7303. var current = this.current;
  7304. var font = current.font;
  7305. var textRenderingMode = current.textRenderingMode;
  7306. var fontSize = current.fontSize / current.fontSizeScale;
  7307. var fillStrokeMode = textRenderingMode &
  7308. TextRenderingMode.FILL_STROKE_MASK;
  7309. var isAddToPathSet = !!(textRenderingMode &
  7310. TextRenderingMode.ADD_TO_PATH_FLAG);
  7311. var addToPath;
  7312. if (font.disableFontFace || isAddToPathSet) {
  7313. addToPath = font.getPathGenerator(this.commonObjs, character);
  7314. }
  7315. if (font.disableFontFace) {
  7316. ctx.save();
  7317. ctx.translate(x, y);
  7318. ctx.beginPath();
  7319. addToPath(ctx, fontSize);
  7320. if (fillStrokeMode === TextRenderingMode.FILL ||
  7321. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7322. ctx.fill();
  7323. }
  7324. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7325. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7326. ctx.stroke();
  7327. }
  7328. ctx.restore();
  7329. } else {
  7330. if (fillStrokeMode === TextRenderingMode.FILL ||
  7331. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7332. ctx.fillText(character, x, y);
  7333. }
  7334. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7335. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7336. ctx.strokeText(character, x, y);
  7337. }
  7338. }
  7339. if (isAddToPathSet) {
  7340. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7341. paths.push({
  7342. transform: ctx.mozCurrentTransform,
  7343. x: x,
  7344. y: y,
  7345. fontSize: fontSize,
  7346. addToPath: addToPath
  7347. });
  7348. }
  7349. },
  7350. get isFontSubpixelAAEnabled() {
  7351. // Checks if anti-aliasing is enabled when scaled text is painted.
  7352. // On Windows GDI scaled fonts looks bad.
  7353. var ctx = document.createElement('canvas').getContext('2d');
  7354. ctx.scale(1.5, 1);
  7355. ctx.fillText('I', 0, 10);
  7356. var data = ctx.getImageData(0, 0, 10, 10).data;
  7357. var enabled = false;
  7358. for (var i = 3; i < data.length; i += 4) {
  7359. if (data[i] > 0 && data[i] < 255) {
  7360. enabled = true;
  7361. break;
  7362. }
  7363. }
  7364. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7365. },
  7366. showText: function CanvasGraphics_showText(glyphs) {
  7367. var current = this.current;
  7368. var font = current.font;
  7369. if (font.isType3Font) {
  7370. return this.showType3Text(glyphs);
  7371. }
  7372. var fontSize = current.fontSize;
  7373. if (fontSize === 0) {
  7374. return;
  7375. }
  7376. var ctx = this.ctx;
  7377. var fontSizeScale = current.fontSizeScale;
  7378. var charSpacing = current.charSpacing;
  7379. var wordSpacing = current.wordSpacing;
  7380. var fontDirection = current.fontDirection;
  7381. var textHScale = current.textHScale * fontDirection;
  7382. var glyphsLength = glyphs.length;
  7383. var vertical = font.vertical;
  7384. var spacingDir = vertical ? 1 : -1;
  7385. var defaultVMetrics = font.defaultVMetrics;
  7386. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7387. var simpleFillText =
  7388. current.textRenderingMode === TextRenderingMode.FILL &&
  7389. !font.disableFontFace;
  7390. ctx.save();
  7391. ctx.transform.apply(ctx, current.textMatrix);
  7392. ctx.translate(current.x, current.y + current.textRise);
  7393. if (current.patternFill) {
  7394. // TODO: Some shading patterns are not applied correctly to text,
  7395. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7396. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7397. }
  7398. if (fontDirection > 0) {
  7399. ctx.scale(textHScale, -1);
  7400. } else {
  7401. ctx.scale(textHScale, 1);
  7402. }
  7403. var lineWidth = current.lineWidth;
  7404. var scale = current.textMatrixScale;
  7405. if (scale === 0 || lineWidth === 0) {
  7406. var fillStrokeMode = current.textRenderingMode &
  7407. TextRenderingMode.FILL_STROKE_MASK;
  7408. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7409. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7410. this.cachedGetSinglePixelWidth = null;
  7411. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7412. }
  7413. } else {
  7414. lineWidth /= scale;
  7415. }
  7416. if (fontSizeScale !== 1.0) {
  7417. ctx.scale(fontSizeScale, fontSizeScale);
  7418. lineWidth /= fontSizeScale;
  7419. }
  7420. ctx.lineWidth = lineWidth;
  7421. var x = 0, i;
  7422. for (i = 0; i < glyphsLength; ++i) {
  7423. var glyph = glyphs[i];
  7424. if (isNum(glyph)) {
  7425. x += spacingDir * glyph * fontSize / 1000;
  7426. continue;
  7427. }
  7428. var restoreNeeded = false;
  7429. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7430. var character = glyph.fontChar;
  7431. var accent = glyph.accent;
  7432. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7433. var width = glyph.width;
  7434. if (vertical) {
  7435. var vmetric, vx, vy;
  7436. vmetric = glyph.vmetric || defaultVMetrics;
  7437. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7438. vx = -vx * widthAdvanceScale;
  7439. vy = vmetric[2] * widthAdvanceScale;
  7440. width = vmetric ? -vmetric[0] : width;
  7441. scaledX = vx / fontSizeScale;
  7442. scaledY = (x + vy) / fontSizeScale;
  7443. } else {
  7444. scaledX = x / fontSizeScale;
  7445. scaledY = 0;
  7446. }
  7447. if (font.remeasure && width > 0) {
  7448. // Some standard fonts may not have the exact width: rescale per
  7449. // character if measured width is greater than expected glyph width
  7450. // and subpixel-aa is enabled, otherwise just center the glyph.
  7451. var measuredWidth = ctx.measureText(character).width * 1000 /
  7452. fontSize * fontSizeScale;
  7453. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7454. var characterScaleX = width / measuredWidth;
  7455. restoreNeeded = true;
  7456. ctx.save();
  7457. ctx.scale(characterScaleX, 1);
  7458. scaledX /= characterScaleX;
  7459. } else if (width !== measuredWidth) {
  7460. scaledX += (width - measuredWidth) / 2000 *
  7461. fontSize / fontSizeScale;
  7462. }
  7463. }
  7464. // Only attempt to draw the glyph if it is actually in the embedded font
  7465. // file or if there isn't a font file so the fallback font is shown.
  7466. if (glyph.isInFont || font.missingFile) {
  7467. if (simpleFillText && !accent) {
  7468. // common case
  7469. ctx.fillText(character, scaledX, scaledY);
  7470. } else {
  7471. this.paintChar(character, scaledX, scaledY);
  7472. if (accent) {
  7473. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7474. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7475. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7476. }
  7477. }
  7478. }
  7479. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7480. x += charWidth;
  7481. if (restoreNeeded) {
  7482. ctx.restore();
  7483. }
  7484. }
  7485. if (vertical) {
  7486. current.y -= x * textHScale;
  7487. } else {
  7488. current.x += x * textHScale;
  7489. }
  7490. ctx.restore();
  7491. },
  7492. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7493. // Type3 fonts - each glyph is a "mini-PDF"
  7494. var ctx = this.ctx;
  7495. var current = this.current;
  7496. var font = current.font;
  7497. var fontSize = current.fontSize;
  7498. var fontDirection = current.fontDirection;
  7499. var spacingDir = font.vertical ? 1 : -1;
  7500. var charSpacing = current.charSpacing;
  7501. var wordSpacing = current.wordSpacing;
  7502. var textHScale = current.textHScale * fontDirection;
  7503. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7504. var glyphsLength = glyphs.length;
  7505. var isTextInvisible =
  7506. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7507. var i, glyph, width, spacingLength;
  7508. if (isTextInvisible || fontSize === 0) {
  7509. return;
  7510. }
  7511. this.cachedGetSinglePixelWidth = null;
  7512. ctx.save();
  7513. ctx.transform.apply(ctx, current.textMatrix);
  7514. ctx.translate(current.x, current.y);
  7515. ctx.scale(textHScale, fontDirection);
  7516. for (i = 0; i < glyphsLength; ++i) {
  7517. glyph = glyphs[i];
  7518. if (isNum(glyph)) {
  7519. spacingLength = spacingDir * glyph * fontSize / 1000;
  7520. this.ctx.translate(spacingLength, 0);
  7521. current.x += spacingLength * textHScale;
  7522. continue;
  7523. }
  7524. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7525. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7526. if (!operatorList) {
  7527. warn('Type3 character \"' + glyph.operatorListId +
  7528. '\" is not available');
  7529. continue;
  7530. }
  7531. this.processingType3 = glyph;
  7532. this.save();
  7533. ctx.scale(fontSize, fontSize);
  7534. ctx.transform.apply(ctx, fontMatrix);
  7535. this.executeOperatorList(operatorList);
  7536. this.restore();
  7537. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7538. width = transformed[0] * fontSize + spacing;
  7539. ctx.translate(width, 0);
  7540. current.x += width * textHScale;
  7541. }
  7542. ctx.restore();
  7543. this.processingType3 = null;
  7544. },
  7545. // Type3 fonts
  7546. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7547. // We can safely ignore this since the width should be the same
  7548. // as the width in the Widths array.
  7549. },
  7550. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7551. yWidth,
  7552. llx,
  7553. lly,
  7554. urx,
  7555. ury) {
  7556. // TODO According to the spec we're also suppose to ignore any operators
  7557. // that set color or include images while processing this type3 font.
  7558. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7559. this.clip();
  7560. this.endPath();
  7561. },
  7562. // Color
  7563. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7564. var pattern;
  7565. if (IR[0] === 'TilingPattern') {
  7566. var color = IR[1];
  7567. var baseTransform = this.baseTransform ||
  7568. this.ctx.mozCurrentTransform.slice();
  7569. var self = this;
  7570. var canvasGraphicsFactory = {
  7571. createCanvasGraphics: function (ctx) {
  7572. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7573. }
  7574. };
  7575. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7576. baseTransform);
  7577. } else {
  7578. pattern = getShadingPatternFromIR(IR);
  7579. }
  7580. return pattern;
  7581. },
  7582. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7583. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7584. },
  7585. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7586. this.current.fillColor = this.getColorN_Pattern(arguments);
  7587. this.current.patternFill = true;
  7588. },
  7589. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7590. var color = Util.makeCssRgb(r, g, b);
  7591. this.ctx.strokeStyle = color;
  7592. this.current.strokeColor = color;
  7593. },
  7594. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7595. var color = Util.makeCssRgb(r, g, b);
  7596. this.ctx.fillStyle = color;
  7597. this.current.fillColor = color;
  7598. this.current.patternFill = false;
  7599. },
  7600. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7601. var ctx = this.ctx;
  7602. this.save();
  7603. var pattern = getShadingPatternFromIR(patternIR);
  7604. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7605. var inv = ctx.mozCurrentTransformInverse;
  7606. if (inv) {
  7607. var canvas = ctx.canvas;
  7608. var width = canvas.width;
  7609. var height = canvas.height;
  7610. var bl = Util.applyTransform([0, 0], inv);
  7611. var br = Util.applyTransform([0, height], inv);
  7612. var ul = Util.applyTransform([width, 0], inv);
  7613. var ur = Util.applyTransform([width, height], inv);
  7614. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7615. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7616. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7617. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7618. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7619. } else {
  7620. // HACK to draw the gradient onto an infinite rectangle.
  7621. // PDF gradients are drawn across the entire image while
  7622. // Canvas only allows gradients to be drawn in a rectangle
  7623. // The following bug should allow us to remove this.
  7624. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7625. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7626. }
  7627. this.restore();
  7628. },
  7629. // Images
  7630. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7631. error('Should not call beginInlineImage');
  7632. },
  7633. beginImageData: function CanvasGraphics_beginImageData() {
  7634. error('Should not call beginImageData');
  7635. },
  7636. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7637. bbox) {
  7638. this.save();
  7639. this.baseTransformStack.push(this.baseTransform);
  7640. if (isArray(matrix) && 6 === matrix.length) {
  7641. this.transform.apply(this, matrix);
  7642. }
  7643. this.baseTransform = this.ctx.mozCurrentTransform;
  7644. if (isArray(bbox) && 4 === bbox.length) {
  7645. var width = bbox[2] - bbox[0];
  7646. var height = bbox[3] - bbox[1];
  7647. this.ctx.rect(bbox[0], bbox[1], width, height);
  7648. this.clip();
  7649. this.endPath();
  7650. }
  7651. },
  7652. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7653. this.restore();
  7654. this.baseTransform = this.baseTransformStack.pop();
  7655. },
  7656. beginGroup: function CanvasGraphics_beginGroup(group) {
  7657. this.save();
  7658. var currentCtx = this.ctx;
  7659. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7660. // group results aren't usually that different and they even have tools
  7661. // that ignore this setting. Notes from Rik on implementing:
  7662. // - When you encounter an transparency group, create a new canvas with
  7663. // the dimensions of the bbox
  7664. // - copy the content from the previous canvas to the new canvas
  7665. // - draw as usual
  7666. // - remove the backdrop alpha:
  7667. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7668. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7669. // backdrop
  7670. // - remove background color:
  7671. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7672. if (!group.isolated) {
  7673. info('TODO: Support non-isolated groups.');
  7674. }
  7675. // TODO knockout - supposedly possible with the clever use of compositing
  7676. // modes.
  7677. if (group.knockout) {
  7678. warn('Knockout groups not supported.');
  7679. }
  7680. var currentTransform = currentCtx.mozCurrentTransform;
  7681. if (group.matrix) {
  7682. currentCtx.transform.apply(currentCtx, group.matrix);
  7683. }
  7684. assert(group.bbox, 'Bounding box is required.');
  7685. // Based on the current transform figure out how big the bounding box
  7686. // will actually be.
  7687. var bounds = Util.getAxialAlignedBoundingBox(
  7688. group.bbox,
  7689. currentCtx.mozCurrentTransform);
  7690. // Clip the bounding box to the current canvas.
  7691. var canvasBounds = [0,
  7692. 0,
  7693. currentCtx.canvas.width,
  7694. currentCtx.canvas.height];
  7695. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7696. // Use ceil in case we're between sizes so we don't create canvas that is
  7697. // too small and make the canvas at least 1x1 pixels.
  7698. var offsetX = Math.floor(bounds[0]);
  7699. var offsetY = Math.floor(bounds[1]);
  7700. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7701. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7702. var scaleX = 1, scaleY = 1;
  7703. if (drawnWidth > MAX_GROUP_SIZE) {
  7704. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7705. drawnWidth = MAX_GROUP_SIZE;
  7706. }
  7707. if (drawnHeight > MAX_GROUP_SIZE) {
  7708. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7709. drawnHeight = MAX_GROUP_SIZE;
  7710. }
  7711. var cacheId = 'groupAt' + this.groupLevel;
  7712. if (group.smask) {
  7713. // Using two cache entries is case if masks are used one after another.
  7714. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7715. }
  7716. var scratchCanvas = this.cachedCanvases.getCanvas(
  7717. cacheId, drawnWidth, drawnHeight, true);
  7718. var groupCtx = scratchCanvas.context;
  7719. // Since we created a new canvas that is just the size of the bounding box
  7720. // we have to translate the group ctx.
  7721. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7722. groupCtx.translate(-offsetX, -offsetY);
  7723. groupCtx.transform.apply(groupCtx, currentTransform);
  7724. if (group.smask) {
  7725. // Saving state and cached mask to be used in setGState.
  7726. this.smaskStack.push({
  7727. canvas: scratchCanvas.canvas,
  7728. context: groupCtx,
  7729. offsetX: offsetX,
  7730. offsetY: offsetY,
  7731. scaleX: scaleX,
  7732. scaleY: scaleY,
  7733. subtype: group.smask.subtype,
  7734. backdrop: group.smask.backdrop,
  7735. transferMap: group.smask.transferMap || null,
  7736. startTransformInverse: null, // used during suspend operation
  7737. });
  7738. } else {
  7739. // Setup the current ctx so when the group is popped we draw it at the
  7740. // right location.
  7741. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7742. currentCtx.translate(offsetX, offsetY);
  7743. currentCtx.scale(scaleX, scaleY);
  7744. }
  7745. // The transparency group inherits all off the current graphics state
  7746. // except the blend mode, soft mask, and alpha constants.
  7747. copyCtxState(currentCtx, groupCtx);
  7748. this.ctx = groupCtx;
  7749. this.setGState([
  7750. ['BM', 'Normal'],
  7751. ['ca', 1],
  7752. ['CA', 1]
  7753. ]);
  7754. this.groupStack.push(currentCtx);
  7755. this.groupLevel++;
  7756. // Reseting mask state, masks will be applied on restore of the group.
  7757. this.current.activeSMask = null;
  7758. },
  7759. endGroup: function CanvasGraphics_endGroup(group) {
  7760. this.groupLevel--;
  7761. var groupCtx = this.ctx;
  7762. this.ctx = this.groupStack.pop();
  7763. // Turn off image smoothing to avoid sub pixel interpolation which can
  7764. // look kind of blurry for some pdfs.
  7765. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7766. this.ctx.imageSmoothingEnabled = false;
  7767. } else {
  7768. this.ctx.mozImageSmoothingEnabled = false;
  7769. }
  7770. if (group.smask) {
  7771. this.tempSMask = this.smaskStack.pop();
  7772. } else {
  7773. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7774. }
  7775. this.restore();
  7776. },
  7777. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7778. this.save();
  7779. this.current = new CanvasExtraState();
  7780. if (this.baseTransform) {
  7781. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7782. }
  7783. },
  7784. endAnnotations: function CanvasGraphics_endAnnotations() {
  7785. this.restore();
  7786. },
  7787. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7788. matrix) {
  7789. this.save();
  7790. if (isArray(rect) && 4 === rect.length) {
  7791. var width = rect[2] - rect[0];
  7792. var height = rect[3] - rect[1];
  7793. this.ctx.rect(rect[0], rect[1], width, height);
  7794. this.clip();
  7795. this.endPath();
  7796. }
  7797. this.transform.apply(this, transform);
  7798. this.transform.apply(this, matrix);
  7799. },
  7800. endAnnotation: function CanvasGraphics_endAnnotation() {
  7801. this.restore();
  7802. },
  7803. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7804. var domImage = this.objs.get(objId);
  7805. if (!domImage) {
  7806. warn('Dependent image isn\'t ready yet');
  7807. return;
  7808. }
  7809. this.save();
  7810. var ctx = this.ctx;
  7811. // scale the image to the unit square
  7812. ctx.scale(1 / w, -1 / h);
  7813. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7814. 0, -h, w, h);
  7815. if (this.imageLayer) {
  7816. var currentTransform = ctx.mozCurrentTransformInverse;
  7817. var position = this.getCanvasPosition(0, 0);
  7818. this.imageLayer.appendImage({
  7819. objId: objId,
  7820. left: position[0],
  7821. top: position[1],
  7822. width: w / currentTransform[0],
  7823. height: h / currentTransform[3]
  7824. });
  7825. }
  7826. this.restore();
  7827. },
  7828. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7829. var ctx = this.ctx;
  7830. var width = img.width, height = img.height;
  7831. var fillColor = this.current.fillColor;
  7832. var isPatternFill = this.current.patternFill;
  7833. var glyph = this.processingType3;
  7834. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7835. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7836. glyph.compiled =
  7837. compileType3Glyph({data: img.data, width: width, height: height});
  7838. } else {
  7839. glyph.compiled = null;
  7840. }
  7841. }
  7842. if (glyph && glyph.compiled) {
  7843. glyph.compiled(ctx);
  7844. return;
  7845. }
  7846. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7847. width, height);
  7848. var maskCtx = maskCanvas.context;
  7849. maskCtx.save();
  7850. putBinaryImageMask(maskCtx, img);
  7851. maskCtx.globalCompositeOperation = 'source-in';
  7852. maskCtx.fillStyle = isPatternFill ?
  7853. fillColor.getPattern(maskCtx, this) : fillColor;
  7854. maskCtx.fillRect(0, 0, width, height);
  7855. maskCtx.restore();
  7856. this.paintInlineImageXObject(maskCanvas.canvas);
  7857. },
  7858. paintImageMaskXObjectRepeat:
  7859. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7860. scaleY, positions) {
  7861. var width = imgData.width;
  7862. var height = imgData.height;
  7863. var fillColor = this.current.fillColor;
  7864. var isPatternFill = this.current.patternFill;
  7865. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7866. width, height);
  7867. var maskCtx = maskCanvas.context;
  7868. maskCtx.save();
  7869. putBinaryImageMask(maskCtx, imgData);
  7870. maskCtx.globalCompositeOperation = 'source-in';
  7871. maskCtx.fillStyle = isPatternFill ?
  7872. fillColor.getPattern(maskCtx, this) : fillColor;
  7873. maskCtx.fillRect(0, 0, width, height);
  7874. maskCtx.restore();
  7875. var ctx = this.ctx;
  7876. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7877. ctx.save();
  7878. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7879. ctx.scale(1, -1);
  7880. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7881. 0, -1, 1, 1);
  7882. ctx.restore();
  7883. }
  7884. },
  7885. paintImageMaskXObjectGroup:
  7886. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7887. var ctx = this.ctx;
  7888. var fillColor = this.current.fillColor;
  7889. var isPatternFill = this.current.patternFill;
  7890. for (var i = 0, ii = images.length; i < ii; i++) {
  7891. var image = images[i];
  7892. var width = image.width, height = image.height;
  7893. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7894. width, height);
  7895. var maskCtx = maskCanvas.context;
  7896. maskCtx.save();
  7897. putBinaryImageMask(maskCtx, image);
  7898. maskCtx.globalCompositeOperation = 'source-in';
  7899. maskCtx.fillStyle = isPatternFill ?
  7900. fillColor.getPattern(maskCtx, this) : fillColor;
  7901. maskCtx.fillRect(0, 0, width, height);
  7902. maskCtx.restore();
  7903. ctx.save();
  7904. ctx.transform.apply(ctx, image.transform);
  7905. ctx.scale(1, -1);
  7906. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7907. 0, -1, 1, 1);
  7908. ctx.restore();
  7909. }
  7910. },
  7911. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7912. var imgData = this.objs.get(objId);
  7913. if (!imgData) {
  7914. warn('Dependent image isn\'t ready yet');
  7915. return;
  7916. }
  7917. this.paintInlineImageXObject(imgData);
  7918. },
  7919. paintImageXObjectRepeat:
  7920. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7921. positions) {
  7922. var imgData = this.objs.get(objId);
  7923. if (!imgData) {
  7924. warn('Dependent image isn\'t ready yet');
  7925. return;
  7926. }
  7927. var width = imgData.width;
  7928. var height = imgData.height;
  7929. var map = [];
  7930. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7931. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7932. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7933. }
  7934. this.paintInlineImageXObjectGroup(imgData, map);
  7935. },
  7936. paintInlineImageXObject:
  7937. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7938. var width = imgData.width;
  7939. var height = imgData.height;
  7940. var ctx = this.ctx;
  7941. this.save();
  7942. // scale the image to the unit square
  7943. ctx.scale(1 / width, -1 / height);
  7944. var currentTransform = ctx.mozCurrentTransformInverse;
  7945. var a = currentTransform[0], b = currentTransform[1];
  7946. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7947. var c = currentTransform[2], d = currentTransform[3];
  7948. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7949. var imgToPaint, tmpCanvas;
  7950. // instanceof HTMLElement does not work in jsdom node.js module
  7951. if (imgData instanceof HTMLElement || !imgData.data) {
  7952. imgToPaint = imgData;
  7953. } else {
  7954. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7955. width, height);
  7956. var tmpCtx = tmpCanvas.context;
  7957. putBinaryImageData(tmpCtx, imgData);
  7958. imgToPaint = tmpCanvas.canvas;
  7959. }
  7960. var paintWidth = width, paintHeight = height;
  7961. var tmpCanvasId = 'prescale1';
  7962. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7963. // pixels during drawImage operation, painting on the temporary canvas(es)
  7964. // that are twice smaller in size
  7965. while ((widthScale > 2 && paintWidth > 1) ||
  7966. (heightScale > 2 && paintHeight > 1)) {
  7967. var newWidth = paintWidth, newHeight = paintHeight;
  7968. if (widthScale > 2 && paintWidth > 1) {
  7969. newWidth = Math.ceil(paintWidth / 2);
  7970. widthScale /= paintWidth / newWidth;
  7971. }
  7972. if (heightScale > 2 && paintHeight > 1) {
  7973. newHeight = Math.ceil(paintHeight / 2);
  7974. heightScale /= paintHeight / newHeight;
  7975. }
  7976. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7977. newWidth, newHeight);
  7978. tmpCtx = tmpCanvas.context;
  7979. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7980. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7981. 0, 0, newWidth, newHeight);
  7982. imgToPaint = tmpCanvas.canvas;
  7983. paintWidth = newWidth;
  7984. paintHeight = newHeight;
  7985. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7986. }
  7987. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7988. 0, -height, width, height);
  7989. if (this.imageLayer) {
  7990. var position = this.getCanvasPosition(0, -height);
  7991. this.imageLayer.appendImage({
  7992. imgData: imgData,
  7993. left: position[0],
  7994. top: position[1],
  7995. width: width / currentTransform[0],
  7996. height: height / currentTransform[3]
  7997. });
  7998. }
  7999. this.restore();
  8000. },
  8001. paintInlineImageXObjectGroup:
  8002. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8003. var ctx = this.ctx;
  8004. var w = imgData.width;
  8005. var h = imgData.height;
  8006. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8007. var tmpCtx = tmpCanvas.context;
  8008. putBinaryImageData(tmpCtx, imgData);
  8009. for (var i = 0, ii = map.length; i < ii; i++) {
  8010. var entry = map[i];
  8011. ctx.save();
  8012. ctx.transform.apply(ctx, entry.transform);
  8013. ctx.scale(1, -1);
  8014. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  8015. 0, -1, 1, 1);
  8016. if (this.imageLayer) {
  8017. var position = this.getCanvasPosition(entry.x, entry.y);
  8018. this.imageLayer.appendImage({
  8019. imgData: imgData,
  8020. left: position[0],
  8021. top: position[1],
  8022. width: w,
  8023. height: h
  8024. });
  8025. }
  8026. ctx.restore();
  8027. }
  8028. },
  8029. paintSolidColorImageMask:
  8030. function CanvasGraphics_paintSolidColorImageMask() {
  8031. this.ctx.fillRect(0, 0, 1, 1);
  8032. },
  8033. paintXObject: function CanvasGraphics_paintXObject() {
  8034. warn('Unsupported \'paintXObject\' command.');
  8035. },
  8036. // Marked content
  8037. markPoint: function CanvasGraphics_markPoint(tag) {
  8038. // TODO Marked content.
  8039. },
  8040. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8041. // TODO Marked content.
  8042. },
  8043. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8044. // TODO Marked content.
  8045. },
  8046. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  8047. tag, properties) {
  8048. // TODO Marked content.
  8049. },
  8050. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8051. // TODO Marked content.
  8052. },
  8053. // Compatibility
  8054. beginCompat: function CanvasGraphics_beginCompat() {
  8055. // TODO ignore undefined operators (should we do that anyway?)
  8056. },
  8057. endCompat: function CanvasGraphics_endCompat() {
  8058. // TODO stop ignoring undefined operators
  8059. },
  8060. // Helper functions
  8061. consumePath: function CanvasGraphics_consumePath() {
  8062. var ctx = this.ctx;
  8063. if (this.pendingClip) {
  8064. if (this.pendingClip === EO_CLIP) {
  8065. if (ctx.mozFillRule !== undefined) {
  8066. ctx.mozFillRule = 'evenodd';
  8067. ctx.clip();
  8068. ctx.mozFillRule = 'nonzero';
  8069. } else {
  8070. ctx.clip('evenodd');
  8071. }
  8072. } else {
  8073. ctx.clip();
  8074. }
  8075. this.pendingClip = null;
  8076. }
  8077. ctx.beginPath();
  8078. },
  8079. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8080. if (this.cachedGetSinglePixelWidth === null) {
  8081. // NOTE: The `save` and `restore` commands used below is a workaround
  8082. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8083. // from intermittently returning incorrect values in Firefox, see:
  8084. // https://github.com/mozilla/pdf.js/issues/7188.
  8085. this.ctx.save();
  8086. var inverse = this.ctx.mozCurrentTransformInverse;
  8087. this.ctx.restore();
  8088. // max of the current horizontal and vertical scale
  8089. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8090. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8091. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8092. }
  8093. return this.cachedGetSinglePixelWidth;
  8094. },
  8095. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8096. var transform = this.ctx.mozCurrentTransform;
  8097. return [
  8098. transform[0] * x + transform[2] * y + transform[4],
  8099. transform[1] * x + transform[3] * y + transform[5]
  8100. ];
  8101. }
  8102. };
  8103. for (var op in OPS) {
  8104. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8105. }
  8106. return CanvasGraphics;
  8107. })();
  8108. exports.CanvasGraphics = CanvasGraphics;
  8109. exports.createScratchCanvas = createScratchCanvas;
  8110. }));
  8111. (function (root, factory) {
  8112. {
  8113. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8114. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8115. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8116. }
  8117. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8118. displayMetadata, displayDOMUtils, amdRequire) {
  8119. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8120. var MessageHandler = sharedUtil.MessageHandler;
  8121. var MissingPDFException = sharedUtil.MissingPDFException;
  8122. var PageViewport = sharedUtil.PageViewport;
  8123. var PasswordResponses = sharedUtil.PasswordResponses;
  8124. var PasswordException = sharedUtil.PasswordException;
  8125. var StatTimer = sharedUtil.StatTimer;
  8126. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8127. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8128. var Util = sharedUtil.Util;
  8129. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8130. var error = sharedUtil.error;
  8131. var deprecated = sharedUtil.deprecated;
  8132. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8133. var info = sharedUtil.info;
  8134. var isInt = sharedUtil.isInt;
  8135. var isArray = sharedUtil.isArray;
  8136. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8137. var isSameOrigin = sharedUtil.isSameOrigin;
  8138. var loadJpegStream = sharedUtil.loadJpegStream;
  8139. var stringToBytes = sharedUtil.stringToBytes;
  8140. var globalScope = sharedUtil.globalScope;
  8141. var warn = sharedUtil.warn;
  8142. var FontFaceObject = displayFontLoader.FontFaceObject;
  8143. var FontLoader = displayFontLoader.FontLoader;
  8144. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8145. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8146. var Metadata = displayMetadata.Metadata;
  8147. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8148. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8149. var isWorkerDisabled = false;
  8150. var workerSrc;
  8151. var isPostMessageTransfersDisabled = false;
  8152. var useRequireEnsure = false;
  8153. if (typeof window === 'undefined') {
  8154. // node.js - disable worker and set require.ensure.
  8155. isWorkerDisabled = true;
  8156. if (typeof require.ensure === 'undefined') {
  8157. require.ensure = require('node-ensure');
  8158. }
  8159. useRequireEnsure = true;
  8160. }
  8161. if (typeof __webpack_require__ !== 'undefined') {
  8162. useRequireEnsure = true;
  8163. }
  8164. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8165. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8166. }
  8167. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8168. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8169. require.ensure([], function () {
  8170. var worker = require('./pdf.worker.js');
  8171. callback(worker.WorkerMessageHandler);
  8172. });
  8173. }) : dynamicLoaderSupported ? (function (callback) {
  8174. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8175. callback(worker.WorkerMessageHandler);
  8176. });
  8177. }) : null;
  8178. /**
  8179. * Document initialization / loading parameters object.
  8180. *
  8181. * @typedef {Object} DocumentInitParameters
  8182. * @property {string} url - The URL of the PDF.
  8183. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8184. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8185. * use atob() to convert it to a binary string first.
  8186. * @property {Object} httpHeaders - Basic authentication headers.
  8187. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8188. * Access-Control requests should be made using credentials such as cookies
  8189. * or authorization headers. The default is false.
  8190. * @property {string} password - For decrypting password-protected PDFs.
  8191. * @property {TypedArray} initialData - A typed array with the first portion or
  8192. * all of the pdf data. Used by the extension since some data is already
  8193. * loaded before the switch to range requests.
  8194. * @property {number} length - The PDF file length. It's used for progress
  8195. * reports and range requests operations.
  8196. * @property {PDFDataRangeTransport} range
  8197. * @property {number} rangeChunkSize - Optional parameter to specify
  8198. * maximum number of bytes fetched per range request. The default value is
  8199. * 2^16 = 65536.
  8200. * @property {PDFWorker} worker - The worker that will be used for the loading
  8201. * and parsing of the PDF data.
  8202. */
  8203. /**
  8204. * @typedef {Object} PDFDocumentStats
  8205. * @property {Array} streamTypes - Used stream types in the document (an item
  8206. * is set to true if specific stream ID was used in the document).
  8207. * @property {Array} fontTypes - Used font type in the document (an item is set
  8208. * to true if specific font ID was used in the document).
  8209. */
  8210. /**
  8211. * This is the main entry point for loading a PDF and interacting with it.
  8212. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8213. * is used, which means it must follow the same origin rules that any XHR does
  8214. * e.g. No cross domain requests without CORS.
  8215. *
  8216. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8217. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8218. * already populated with data or parameter object.
  8219. *
  8220. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8221. * if you want to manually serve range requests for data in the PDF.
  8222. *
  8223. * @param {function} passwordCallback (deprecated) It is used to request a
  8224. * password if wrong or no password was provided. The callback receives two
  8225. * parameters: function that needs to be called with new password and reason
  8226. * (see {PasswordResponses}).
  8227. *
  8228. * @param {function} progressCallback (deprecated) It is used to be able to
  8229. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8230. * a loading bar). The callback receives an {Object} with the properties:
  8231. * {number} loaded and {number} total.
  8232. *
  8233. * @return {PDFDocumentLoadingTask}
  8234. */
  8235. function getDocument(src, pdfDataRangeTransport,
  8236. passwordCallback, progressCallback) {
  8237. var task = new PDFDocumentLoadingTask();
  8238. // Support of the obsolete arguments (for compatibility with API v1.0)
  8239. if (arguments.length > 1) {
  8240. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8241. 'passwordCallback or progressCallback argument');
  8242. }
  8243. if (pdfDataRangeTransport) {
  8244. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8245. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8246. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8247. pdfDataRangeTransport.length = src.length;
  8248. pdfDataRangeTransport.initialData = src.initialData;
  8249. if (!pdfDataRangeTransport.abort) {
  8250. pdfDataRangeTransport.abort = function () {};
  8251. }
  8252. }
  8253. src = Object.create(src);
  8254. src.range = pdfDataRangeTransport;
  8255. }
  8256. task.onPassword = passwordCallback || null;
  8257. task.onProgress = progressCallback || null;
  8258. var source;
  8259. if (typeof src === 'string') {
  8260. source = { url: src };
  8261. } else if (isArrayBuffer(src)) {
  8262. source = { data: src };
  8263. } else if (src instanceof PDFDataRangeTransport) {
  8264. source = { range: src };
  8265. } else {
  8266. if (typeof src !== 'object') {
  8267. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8268. 'string or a parameter object');
  8269. }
  8270. if (!src.url && !src.data && !src.range) {
  8271. error('Invalid parameter object: need either .data, .range or .url');
  8272. }
  8273. source = src;
  8274. }
  8275. var params = {};
  8276. var rangeTransport = null;
  8277. var worker = null;
  8278. for (var key in source) {
  8279. if (key === 'url' && typeof window !== 'undefined') {
  8280. // The full path is required in the 'url' field.
  8281. params[key] = new URL(source[key], window.location).href;
  8282. continue;
  8283. } else if (key === 'range') {
  8284. rangeTransport = source[key];
  8285. continue;
  8286. } else if (key === 'worker') {
  8287. worker = source[key];
  8288. continue;
  8289. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8290. // Converting string or array-like data to Uint8Array.
  8291. var pdfBytes = source[key];
  8292. if (typeof pdfBytes === 'string') {
  8293. params[key] = stringToBytes(pdfBytes);
  8294. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8295. !isNaN(pdfBytes.length)) {
  8296. params[key] = new Uint8Array(pdfBytes);
  8297. } else if (isArrayBuffer(pdfBytes)) {
  8298. params[key] = new Uint8Array(pdfBytes);
  8299. } else {
  8300. error('Invalid PDF binary data: either typed array, string or ' +
  8301. 'array-like object is expected in the data property.');
  8302. }
  8303. continue;
  8304. }
  8305. params[key] = source[key];
  8306. }
  8307. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8308. if (!worker) {
  8309. // Worker was not provided -- creating and owning our own.
  8310. worker = new PDFWorker();
  8311. task._worker = worker;
  8312. }
  8313. var docId = task.docId;
  8314. worker.promise.then(function () {
  8315. if (task.destroyed) {
  8316. throw new Error('Loading aborted');
  8317. }
  8318. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8319. function (workerId) {
  8320. if (task.destroyed) {
  8321. throw new Error('Loading aborted');
  8322. }
  8323. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8324. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8325. task._transport = transport;
  8326. messageHandler.send('Ready', null);
  8327. });
  8328. }).catch(task._capability.reject);
  8329. return task;
  8330. }
  8331. /**
  8332. * Starts fetching of specified PDF document/data.
  8333. * @param {PDFWorker} worker
  8334. * @param {Object} source
  8335. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8336. * @param {string} docId Unique document id, used as MessageHandler id.
  8337. * @returns {Promise} The promise, which is resolved when worker id of
  8338. * MessageHandler is known.
  8339. * @private
  8340. */
  8341. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8342. if (worker.destroyed) {
  8343. return Promise.reject(new Error('Worker was destroyed'));
  8344. }
  8345. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8346. source.disableStream = getDefaultSetting('disableStream');
  8347. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8348. if (pdfDataRangeTransport) {
  8349. source.length = pdfDataRangeTransport.length;
  8350. source.initialData = pdfDataRangeTransport.initialData;
  8351. }
  8352. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8353. docId: docId,
  8354. source: source,
  8355. disableRange: getDefaultSetting('disableRange'),
  8356. maxImageSize: getDefaultSetting('maxImageSize'),
  8357. cMapUrl: getDefaultSetting('cMapUrl'),
  8358. cMapPacked: getDefaultSetting('cMapPacked'),
  8359. disableFontFace: getDefaultSetting('disableFontFace'),
  8360. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8361. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8362. !isPostMessageTransfersDisabled,
  8363. }).then(function (workerId) {
  8364. if (worker.destroyed) {
  8365. throw new Error('Worker was destroyed');
  8366. }
  8367. return workerId;
  8368. });
  8369. }
  8370. /**
  8371. * PDF document loading operation.
  8372. * @class
  8373. * @alias PDFDocumentLoadingTask
  8374. */
  8375. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8376. var nextDocumentId = 0;
  8377. /** @constructs PDFDocumentLoadingTask */
  8378. function PDFDocumentLoadingTask() {
  8379. this._capability = createPromiseCapability();
  8380. this._transport = null;
  8381. this._worker = null;
  8382. /**
  8383. * Unique document loading task id -- used in MessageHandlers.
  8384. * @type {string}
  8385. */
  8386. this.docId = 'd' + (nextDocumentId++);
  8387. /**
  8388. * Shows if loading task is destroyed.
  8389. * @type {boolean}
  8390. */
  8391. this.destroyed = false;
  8392. /**
  8393. * Callback to request a password if wrong or no password was provided.
  8394. * The callback receives two parameters: function that needs to be called
  8395. * with new password and reason (see {PasswordResponses}).
  8396. */
  8397. this.onPassword = null;
  8398. /**
  8399. * Callback to be able to monitor the loading progress of the PDF file
  8400. * (necessary to implement e.g. a loading bar). The callback receives
  8401. * an {Object} with the properties: {number} loaded and {number} total.
  8402. */
  8403. this.onProgress = null;
  8404. /**
  8405. * Callback to when unsupported feature is used. The callback receives
  8406. * an {UNSUPPORTED_FEATURES} argument.
  8407. */
  8408. this.onUnsupportedFeature = null;
  8409. }
  8410. PDFDocumentLoadingTask.prototype =
  8411. /** @lends PDFDocumentLoadingTask.prototype */ {
  8412. /**
  8413. * @return {Promise}
  8414. */
  8415. get promise() {
  8416. return this._capability.promise;
  8417. },
  8418. /**
  8419. * Aborts all network requests and destroys worker.
  8420. * @return {Promise} A promise that is resolved after destruction activity
  8421. * is completed.
  8422. */
  8423. destroy: function () {
  8424. this.destroyed = true;
  8425. var transportDestroyed = !this._transport ? Promise.resolve() :
  8426. this._transport.destroy();
  8427. return transportDestroyed.then(function () {
  8428. this._transport = null;
  8429. if (this._worker) {
  8430. this._worker.destroy();
  8431. this._worker = null;
  8432. }
  8433. }.bind(this));
  8434. },
  8435. /**
  8436. * Registers callbacks to indicate the document loading completion.
  8437. *
  8438. * @param {function} onFulfilled The callback for the loading completion.
  8439. * @param {function} onRejected The callback for the loading failure.
  8440. * @return {Promise} A promise that is resolved after the onFulfilled or
  8441. * onRejected callback.
  8442. */
  8443. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8444. return this.promise.then.apply(this.promise, arguments);
  8445. }
  8446. };
  8447. return PDFDocumentLoadingTask;
  8448. })();
  8449. /**
  8450. * Abstract class to support range requests file loading.
  8451. * @class
  8452. * @alias PDFDataRangeTransport
  8453. * @param {number} length
  8454. * @param {Uint8Array} initialData
  8455. */
  8456. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8457. function PDFDataRangeTransport(length, initialData) {
  8458. this.length = length;
  8459. this.initialData = initialData;
  8460. this._rangeListeners = [];
  8461. this._progressListeners = [];
  8462. this._progressiveReadListeners = [];
  8463. this._readyCapability = createPromiseCapability();
  8464. }
  8465. PDFDataRangeTransport.prototype =
  8466. /** @lends PDFDataRangeTransport.prototype */ {
  8467. addRangeListener:
  8468. function PDFDataRangeTransport_addRangeListener(listener) {
  8469. this._rangeListeners.push(listener);
  8470. },
  8471. addProgressListener:
  8472. function PDFDataRangeTransport_addProgressListener(listener) {
  8473. this._progressListeners.push(listener);
  8474. },
  8475. addProgressiveReadListener:
  8476. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8477. this._progressiveReadListeners.push(listener);
  8478. },
  8479. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8480. var listeners = this._rangeListeners;
  8481. for (var i = 0, n = listeners.length; i < n; ++i) {
  8482. listeners[i](begin, chunk);
  8483. }
  8484. },
  8485. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8486. this._readyCapability.promise.then(function () {
  8487. var listeners = this._progressListeners;
  8488. for (var i = 0, n = listeners.length; i < n; ++i) {
  8489. listeners[i](loaded);
  8490. }
  8491. }.bind(this));
  8492. },
  8493. onDataProgressiveRead:
  8494. function PDFDataRangeTransport_onDataProgress(chunk) {
  8495. this._readyCapability.promise.then(function () {
  8496. var listeners = this._progressiveReadListeners;
  8497. for (var i = 0, n = listeners.length; i < n; ++i) {
  8498. listeners[i](chunk);
  8499. }
  8500. }.bind(this));
  8501. },
  8502. transportReady: function PDFDataRangeTransport_transportReady() {
  8503. this._readyCapability.resolve();
  8504. },
  8505. requestDataRange:
  8506. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8507. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8508. },
  8509. abort: function PDFDataRangeTransport_abort() {
  8510. }
  8511. };
  8512. return PDFDataRangeTransport;
  8513. })();
  8514. /**
  8515. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8516. * properties that can be read synchronously.
  8517. * @class
  8518. * @alias PDFDocumentProxy
  8519. */
  8520. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8521. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8522. this.pdfInfo = pdfInfo;
  8523. this.transport = transport;
  8524. this.loadingTask = loadingTask;
  8525. }
  8526. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8527. /**
  8528. * @return {number} Total number of pages the PDF contains.
  8529. */
  8530. get numPages() {
  8531. return this.pdfInfo.numPages;
  8532. },
  8533. /**
  8534. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8535. * unique.
  8536. */
  8537. get fingerprint() {
  8538. return this.pdfInfo.fingerprint;
  8539. },
  8540. /**
  8541. * @param {number} pageNumber The page number to get. The first page is 1.
  8542. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8543. * object.
  8544. */
  8545. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8546. return this.transport.getPage(pageNumber);
  8547. },
  8548. /**
  8549. * @param {{num: number, gen: number}} ref The page reference. Must have
  8550. * the 'num' and 'gen' properties.
  8551. * @return {Promise} A promise that is resolved with the page index that is
  8552. * associated with the reference.
  8553. */
  8554. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8555. return this.transport.getPageIndex(ref);
  8556. },
  8557. /**
  8558. * @return {Promise} A promise that is resolved with a lookup table for
  8559. * mapping named destinations to reference numbers.
  8560. *
  8561. * This can be slow for large documents: use getDestination instead
  8562. */
  8563. getDestinations: function PDFDocumentProxy_getDestinations() {
  8564. return this.transport.getDestinations();
  8565. },
  8566. /**
  8567. * @param {string} id The named destination to get.
  8568. * @return {Promise} A promise that is resolved with all information
  8569. * of the given named destination.
  8570. */
  8571. getDestination: function PDFDocumentProxy_getDestination(id) {
  8572. return this.transport.getDestination(id);
  8573. },
  8574. /**
  8575. * @return {Promise} A promise that is resolved with:
  8576. * an Array containing the pageLabels that correspond to the pageIndexes,
  8577. * or `null` when no pageLabels are present in the PDF file.
  8578. */
  8579. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8580. return this.transport.getPageLabels();
  8581. },
  8582. /**
  8583. * @return {Promise} A promise that is resolved with a lookup table for
  8584. * mapping named attachments to their content.
  8585. */
  8586. getAttachments: function PDFDocumentProxy_getAttachments() {
  8587. return this.transport.getAttachments();
  8588. },
  8589. /**
  8590. * @return {Promise} A promise that is resolved with an array of all the
  8591. * JavaScript strings in the name tree.
  8592. */
  8593. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8594. return this.transport.getJavaScript();
  8595. },
  8596. /**
  8597. * @return {Promise} A promise that is resolved with an {Array} that is a
  8598. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8599. * [
  8600. * {
  8601. * title: string,
  8602. * bold: boolean,
  8603. * italic: boolean,
  8604. * color: rgb Uint8Array,
  8605. * dest: dest obj,
  8606. * url: string,
  8607. * items: array of more items like this
  8608. * },
  8609. * ...
  8610. * ].
  8611. */
  8612. getOutline: function PDFDocumentProxy_getOutline() {
  8613. return this.transport.getOutline();
  8614. },
  8615. /**
  8616. * @return {Promise} A promise that is resolved with an {Object} that has
  8617. * info and metadata properties. Info is an {Object} filled with anything
  8618. * available in the information dictionary and similarly metadata is a
  8619. * {Metadata} object with information from the metadata section of the PDF.
  8620. */
  8621. getMetadata: function PDFDocumentProxy_getMetadata() {
  8622. return this.transport.getMetadata();
  8623. },
  8624. /**
  8625. * @return {Promise} A promise that is resolved with a TypedArray that has
  8626. * the raw data from the PDF.
  8627. */
  8628. getData: function PDFDocumentProxy_getData() {
  8629. return this.transport.getData();
  8630. },
  8631. /**
  8632. * @return {Promise} A promise that is resolved when the document's data
  8633. * is loaded. It is resolved with an {Object} that contains the length
  8634. * property that indicates size of the PDF data in bytes.
  8635. */
  8636. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8637. return this.transport.downloadInfoCapability.promise;
  8638. },
  8639. /**
  8640. * @return {Promise} A promise this is resolved with current stats about
  8641. * document structures (see {@link PDFDocumentStats}).
  8642. */
  8643. getStats: function PDFDocumentProxy_getStats() {
  8644. return this.transport.getStats();
  8645. },
  8646. /**
  8647. * Cleans up resources allocated by the document, e.g. created @font-face.
  8648. */
  8649. cleanup: function PDFDocumentProxy_cleanup() {
  8650. this.transport.startCleanup();
  8651. },
  8652. /**
  8653. * Destroys current document instance and terminates worker.
  8654. */
  8655. destroy: function PDFDocumentProxy_destroy() {
  8656. return this.loadingTask.destroy();
  8657. }
  8658. };
  8659. return PDFDocumentProxy;
  8660. })();
  8661. /**
  8662. * Page getTextContent parameters.
  8663. *
  8664. * @typedef {Object} getTextContentParameters
  8665. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8666. * whitespace with standard spaces (0x20). The default value is `false`.
  8667. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8668. * same line {@link TextItem}'s. The default value is `false`.
  8669. */
  8670. /**
  8671. * Page text content.
  8672. *
  8673. * @typedef {Object} TextContent
  8674. * @property {array} items - array of {@link TextItem}
  8675. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8676. * name.
  8677. */
  8678. /**
  8679. * Page text content part.
  8680. *
  8681. * @typedef {Object} TextItem
  8682. * @property {string} str - text content.
  8683. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8684. * @property {array} transform - transformation matrix.
  8685. * @property {number} width - width in device space.
  8686. * @property {number} height - height in device space.
  8687. * @property {string} fontName - font name used by pdf.js for converted font.
  8688. */
  8689. /**
  8690. * Text style.
  8691. *
  8692. * @typedef {Object} TextStyle
  8693. * @property {number} ascent - font ascent.
  8694. * @property {number} descent - font descent.
  8695. * @property {boolean} vertical - text is in vertical mode.
  8696. * @property {string} fontFamily - possible font family
  8697. */
  8698. /**
  8699. * Page annotation parameters.
  8700. *
  8701. * @typedef {Object} GetAnnotationsParameters
  8702. * @param {string} intent - Determines the annotations that will be fetched,
  8703. * can be either 'display' (viewable annotations) or 'print'
  8704. * (printable annotations).
  8705. * If the parameter is omitted, all annotations are fetched.
  8706. */
  8707. /**
  8708. * Page render parameters.
  8709. *
  8710. * @typedef {Object} RenderParameters
  8711. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8712. * @property {PageViewport} viewport - Rendering viewport obtained by
  8713. * calling of PDFPage.getViewport method.
  8714. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8715. * (default value is 'display').
  8716. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  8717. * interactive form elements are rendered in the display
  8718. * layer. If so, we do not render them on canvas as well.
  8719. * @property {Array} transform - (optional) Additional transform, applied
  8720. * just before viewport transform.
  8721. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8722. * endLayout and appendImage functions.
  8723. * @property {function} continueCallback - (deprecated) A function that will be
  8724. * called each time the rendering is paused. To continue
  8725. * rendering call the function that is the first argument
  8726. * to the callback.
  8727. */
  8728. /**
  8729. * PDF page operator list.
  8730. *
  8731. * @typedef {Object} PDFOperatorList
  8732. * @property {Array} fnArray - Array containing the operator functions.
  8733. * @property {Array} argsArray - Array containing the arguments of the
  8734. * functions.
  8735. */
  8736. /**
  8737. * Proxy to a PDFPage in the worker thread.
  8738. * @class
  8739. * @alias PDFPageProxy
  8740. */
  8741. var PDFPageProxy = (function PDFPageProxyClosure() {
  8742. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8743. this.pageIndex = pageIndex;
  8744. this.pageInfo = pageInfo;
  8745. this.transport = transport;
  8746. this.stats = new StatTimer();
  8747. this.stats.enabled = getDefaultSetting('enableStats');
  8748. this.commonObjs = transport.commonObjs;
  8749. this.objs = new PDFObjects();
  8750. this.cleanupAfterRender = false;
  8751. this.pendingCleanup = false;
  8752. this.intentStates = Object.create(null);
  8753. this.destroyed = false;
  8754. }
  8755. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8756. /**
  8757. * @return {number} Page number of the page. First page is 1.
  8758. */
  8759. get pageNumber() {
  8760. return this.pageIndex + 1;
  8761. },
  8762. /**
  8763. * @return {number} The number of degrees the page is rotated clockwise.
  8764. */
  8765. get rotate() {
  8766. return this.pageInfo.rotate;
  8767. },
  8768. /**
  8769. * @return {Object} The reference that points to this page. It has 'num' and
  8770. * 'gen' properties.
  8771. */
  8772. get ref() {
  8773. return this.pageInfo.ref;
  8774. },
  8775. /**
  8776. * @return {Array} An array of the visible portion of the PDF page in the
  8777. * user space units - [x1, y1, x2, y2].
  8778. */
  8779. get view() {
  8780. return this.pageInfo.view;
  8781. },
  8782. /**
  8783. * @param {number} scale The desired scale of the viewport.
  8784. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8785. * defaults to the page rotation.
  8786. * @return {PageViewport} Contains 'width' and 'height' properties
  8787. * along with transforms required for rendering.
  8788. */
  8789. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8790. if (arguments.length < 2) {
  8791. rotate = this.rotate;
  8792. }
  8793. return new PageViewport(this.view, scale, rotate, 0, 0);
  8794. },
  8795. /**
  8796. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8797. * @return {Promise} A promise that is resolved with an {Array} of the
  8798. * annotation objects.
  8799. */
  8800. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8801. var intent = (params && params.intent) || null;
  8802. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8803. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8804. intent);
  8805. this.annotationsIntent = intent;
  8806. }
  8807. return this.annotationsPromise;
  8808. },
  8809. /**
  8810. * Begins the process of rendering a page to the desired context.
  8811. * @param {RenderParameters} params Page render parameters.
  8812. * @return {RenderTask} An object that contains the promise, which
  8813. * is resolved when the page finishes rendering.
  8814. */
  8815. render: function PDFPageProxy_render(params) {
  8816. var stats = this.stats;
  8817. stats.time('Overall');
  8818. // If there was a pending destroy cancel it so no cleanup happens during
  8819. // this call to render.
  8820. this.pendingCleanup = false;
  8821. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8822. var renderInteractiveForms = (params.renderInteractiveForms === true ?
  8823. true : /* Default */ false);
  8824. if (!this.intentStates[renderingIntent]) {
  8825. this.intentStates[renderingIntent] = Object.create(null);
  8826. }
  8827. var intentState = this.intentStates[renderingIntent];
  8828. // If there's no displayReadyCapability yet, then the operatorList
  8829. // was never requested before. Make the request and create the promise.
  8830. if (!intentState.displayReadyCapability) {
  8831. intentState.receivingOperatorList = true;
  8832. intentState.displayReadyCapability = createPromiseCapability();
  8833. intentState.operatorList = {
  8834. fnArray: [],
  8835. argsArray: [],
  8836. lastChunk: false
  8837. };
  8838. this.stats.time('Page Request');
  8839. this.transport.messageHandler.send('RenderPageRequest', {
  8840. pageIndex: this.pageNumber - 1,
  8841. intent: renderingIntent,
  8842. renderInteractiveForms: renderInteractiveForms,
  8843. });
  8844. }
  8845. var internalRenderTask = new InternalRenderTask(complete, params,
  8846. this.objs,
  8847. this.commonObjs,
  8848. intentState.operatorList,
  8849. this.pageNumber);
  8850. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8851. if (!intentState.renderTasks) {
  8852. intentState.renderTasks = [];
  8853. }
  8854. intentState.renderTasks.push(internalRenderTask);
  8855. var renderTask = internalRenderTask.task;
  8856. // Obsolete parameter support
  8857. if (params.continueCallback) {
  8858. deprecated('render is used with continueCallback parameter');
  8859. renderTask.onContinue = params.continueCallback;
  8860. }
  8861. var self = this;
  8862. intentState.displayReadyCapability.promise.then(
  8863. function pageDisplayReadyPromise(transparency) {
  8864. if (self.pendingCleanup) {
  8865. complete();
  8866. return;
  8867. }
  8868. stats.time('Rendering');
  8869. internalRenderTask.initializeGraphics(transparency);
  8870. internalRenderTask.operatorListChanged();
  8871. },
  8872. function pageDisplayReadPromiseError(reason) {
  8873. complete(reason);
  8874. }
  8875. );
  8876. function complete(error) {
  8877. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8878. if (i >= 0) {
  8879. intentState.renderTasks.splice(i, 1);
  8880. }
  8881. if (self.cleanupAfterRender) {
  8882. self.pendingCleanup = true;
  8883. }
  8884. self._tryCleanup();
  8885. if (error) {
  8886. internalRenderTask.capability.reject(error);
  8887. } else {
  8888. internalRenderTask.capability.resolve();
  8889. }
  8890. stats.timeEnd('Rendering');
  8891. stats.timeEnd('Overall');
  8892. }
  8893. return renderTask;
  8894. },
  8895. /**
  8896. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8897. * object that represents page's operator list.
  8898. */
  8899. getOperatorList: function PDFPageProxy_getOperatorList() {
  8900. function operatorListChanged() {
  8901. if (intentState.operatorList.lastChunk) {
  8902. intentState.opListReadCapability.resolve(intentState.operatorList);
  8903. var i = intentState.renderTasks.indexOf(opListTask);
  8904. if (i >= 0) {
  8905. intentState.renderTasks.splice(i, 1);
  8906. }
  8907. }
  8908. }
  8909. var renderingIntent = 'oplist';
  8910. if (!this.intentStates[renderingIntent]) {
  8911. this.intentStates[renderingIntent] = Object.create(null);
  8912. }
  8913. var intentState = this.intentStates[renderingIntent];
  8914. var opListTask;
  8915. if (!intentState.opListReadCapability) {
  8916. opListTask = {};
  8917. opListTask.operatorListChanged = operatorListChanged;
  8918. intentState.receivingOperatorList = true;
  8919. intentState.opListReadCapability = createPromiseCapability();
  8920. intentState.renderTasks = [];
  8921. intentState.renderTasks.push(opListTask);
  8922. intentState.operatorList = {
  8923. fnArray: [],
  8924. argsArray: [],
  8925. lastChunk: false
  8926. };
  8927. this.transport.messageHandler.send('RenderPageRequest', {
  8928. pageIndex: this.pageIndex,
  8929. intent: renderingIntent
  8930. });
  8931. }
  8932. return intentState.opListReadCapability.promise;
  8933. },
  8934. /**
  8935. * @param {getTextContentParameters} params - getTextContent parameters.
  8936. * @return {Promise} That is resolved a {@link TextContent}
  8937. * object that represent the page text content.
  8938. */
  8939. getTextContent: function PDFPageProxy_getTextContent(params) {
  8940. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8941. pageIndex: this.pageNumber - 1,
  8942. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8943. true : /* Default */ false),
  8944. combineTextItems: (params && params.disableCombineTextItems === true ?
  8945. false : /* Default */ true),
  8946. });
  8947. },
  8948. /**
  8949. * Destroys page object.
  8950. */
  8951. _destroy: function PDFPageProxy_destroy() {
  8952. this.destroyed = true;
  8953. this.transport.pageCache[this.pageIndex] = null;
  8954. var waitOn = [];
  8955. Object.keys(this.intentStates).forEach(function(intent) {
  8956. if (intent === 'oplist') {
  8957. // Avoid errors below, since the renderTasks are just stubs.
  8958. return;
  8959. }
  8960. var intentState = this.intentStates[intent];
  8961. intentState.renderTasks.forEach(function(renderTask) {
  8962. var renderCompleted = renderTask.capability.promise.
  8963. catch(function () {}); // ignoring failures
  8964. waitOn.push(renderCompleted);
  8965. renderTask.cancel();
  8966. });
  8967. }, this);
  8968. this.objs.clear();
  8969. this.annotationsPromise = null;
  8970. this.pendingCleanup = false;
  8971. return Promise.all(waitOn);
  8972. },
  8973. /**
  8974. * Cleans up resources allocated by the page. (deprecated)
  8975. */
  8976. destroy: function() {
  8977. deprecated('page destroy method, use cleanup() instead');
  8978. this.cleanup();
  8979. },
  8980. /**
  8981. * Cleans up resources allocated by the page.
  8982. */
  8983. cleanup: function PDFPageProxy_cleanup() {
  8984. this.pendingCleanup = true;
  8985. this._tryCleanup();
  8986. },
  8987. /**
  8988. * For internal use only. Attempts to clean up if rendering is in a state
  8989. * where that's possible.
  8990. * @ignore
  8991. */
  8992. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8993. if (!this.pendingCleanup ||
  8994. Object.keys(this.intentStates).some(function(intent) {
  8995. var intentState = this.intentStates[intent];
  8996. return (intentState.renderTasks.length !== 0 ||
  8997. intentState.receivingOperatorList);
  8998. }, this)) {
  8999. return;
  9000. }
  9001. Object.keys(this.intentStates).forEach(function(intent) {
  9002. delete this.intentStates[intent];
  9003. }, this);
  9004. this.objs.clear();
  9005. this.annotationsPromise = null;
  9006. this.pendingCleanup = false;
  9007. },
  9008. /**
  9009. * For internal use only.
  9010. * @ignore
  9011. */
  9012. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  9013. intent) {
  9014. var intentState = this.intentStates[intent];
  9015. // TODO Refactor RenderPageRequest to separate rendering
  9016. // and operator list logic
  9017. if (intentState.displayReadyCapability) {
  9018. intentState.displayReadyCapability.resolve(transparency);
  9019. }
  9020. },
  9021. /**
  9022. * For internal use only.
  9023. * @ignore
  9024. */
  9025. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  9026. intent) {
  9027. var intentState = this.intentStates[intent];
  9028. var i, ii;
  9029. // Add the new chunk to the current operator list.
  9030. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9031. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9032. intentState.operatorList.argsArray.push(
  9033. operatorListChunk.argsArray[i]);
  9034. }
  9035. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9036. // Notify all the rendering tasks there are more operators to be consumed.
  9037. for (i = 0; i < intentState.renderTasks.length; i++) {
  9038. intentState.renderTasks[i].operatorListChanged();
  9039. }
  9040. if (operatorListChunk.lastChunk) {
  9041. intentState.receivingOperatorList = false;
  9042. this._tryCleanup();
  9043. }
  9044. }
  9045. };
  9046. return PDFPageProxy;
  9047. })();
  9048. /**
  9049. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9050. * WorkerTransport for them. If creation of a web worker is not possible,
  9051. * a "fake" worker will be used instead.
  9052. * @class
  9053. */
  9054. var PDFWorker = (function PDFWorkerClosure() {
  9055. var nextFakeWorkerId = 0;
  9056. function getWorkerSrc() {
  9057. if (typeof workerSrc !== 'undefined') {
  9058. return workerSrc;
  9059. }
  9060. if (getDefaultSetting('workerSrc')) {
  9061. return getDefaultSetting('workerSrc');
  9062. }
  9063. if (pdfjsFilePath) {
  9064. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9065. }
  9066. error('No PDFJS.workerSrc specified');
  9067. }
  9068. var fakeWorkerFilesLoadedCapability;
  9069. // Loads worker code into main thread.
  9070. function setupFakeWorkerGlobal() {
  9071. var WorkerMessageHandler;
  9072. if (!fakeWorkerFilesLoadedCapability) {
  9073. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9074. // In the developer build load worker_loader which in turn loads all the
  9075. // other files and resolves the promise. In production only the
  9076. // pdf.worker.js file is needed.
  9077. var loader = fakeWorkerFilesLoader || function (callback) {
  9078. Util.loadScript(getWorkerSrc(), function () {
  9079. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9080. });
  9081. };
  9082. loader(fakeWorkerFilesLoadedCapability.resolve);
  9083. }
  9084. return fakeWorkerFilesLoadedCapability.promise;
  9085. }
  9086. function FakeWorkerPort(defer) {
  9087. this._listeners = [];
  9088. this._defer = defer;
  9089. this._deferred = Promise.resolve(undefined);
  9090. }
  9091. FakeWorkerPort.prototype = {
  9092. postMessage: function (obj, transfers) {
  9093. function cloneValue(value) {
  9094. // Trying to perform a structured clone close to the spec, including
  9095. // transfers.
  9096. if (typeof value !== 'object' || value === null) {
  9097. return value;
  9098. }
  9099. if (cloned.has(value)) { // already cloned the object
  9100. return cloned.get(value);
  9101. }
  9102. var result;
  9103. var buffer;
  9104. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9105. // We found object with ArrayBuffer (typed array).
  9106. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9107. if (value === buffer) {
  9108. // Special case when we are faking typed arrays in compatibility.js.
  9109. result = value;
  9110. } else if (transferable) {
  9111. result = new value.constructor(buffer, value.byteOffset,
  9112. value.byteLength);
  9113. } else {
  9114. result = new value.constructor(value);
  9115. }
  9116. cloned.set(value, result);
  9117. return result;
  9118. }
  9119. result = isArray(value) ? [] : {};
  9120. cloned.set(value, result); // adding to cache now for cyclic references
  9121. // Cloning all value and object properties, however ignoring properties
  9122. // defined via getter.
  9123. for (var i in value) {
  9124. var desc, p = value;
  9125. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9126. p = Object.getPrototypeOf(p);
  9127. }
  9128. if (typeof desc.value === 'undefined' ||
  9129. typeof desc.value === 'function') {
  9130. continue;
  9131. }
  9132. result[i] = cloneValue(desc.value);
  9133. }
  9134. return result;
  9135. }
  9136. if (!this._defer) {
  9137. this._listeners.forEach(function (listener) {
  9138. listener.call(this, {data: obj});
  9139. }, this);
  9140. return;
  9141. }
  9142. var cloned = new WeakMap();
  9143. var e = {data: cloneValue(obj)};
  9144. this._deferred.then(function () {
  9145. this._listeners.forEach(function (listener) {
  9146. listener.call(this, e);
  9147. }, this);
  9148. }.bind(this));
  9149. },
  9150. addEventListener: function (name, listener) {
  9151. this._listeners.push(listener);
  9152. },
  9153. removeEventListener: function (name, listener) {
  9154. var i = this._listeners.indexOf(listener);
  9155. this._listeners.splice(i, 1);
  9156. },
  9157. terminate: function () {
  9158. this._listeners = [];
  9159. }
  9160. };
  9161. function createCDNWrapper(url) {
  9162. // We will rely on blob URL's property to specify origin.
  9163. // We want this function to fail in case if createObjectURL or Blob do not
  9164. // exist or fail for some reason -- our Worker creation will fail anyway.
  9165. var wrapper = 'importScripts(\'' + url + '\');';
  9166. return URL.createObjectURL(new Blob([wrapper]));
  9167. }
  9168. function PDFWorker(name) {
  9169. this.name = name;
  9170. this.destroyed = false;
  9171. this._readyCapability = createPromiseCapability();
  9172. this._port = null;
  9173. this._webWorker = null;
  9174. this._messageHandler = null;
  9175. this._initialize();
  9176. }
  9177. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9178. get promise() {
  9179. return this._readyCapability.promise;
  9180. },
  9181. get port() {
  9182. return this._port;
  9183. },
  9184. get messageHandler() {
  9185. return this._messageHandler;
  9186. },
  9187. _initialize: function PDFWorker_initialize() {
  9188. // If worker support isn't disabled explicit and the browser has worker
  9189. // support, create a new web worker and test if it/the browser fulfills
  9190. // all requirements to run parts of pdf.js in a web worker.
  9191. // Right now, the requirement is, that an Uint8Array is still an
  9192. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9193. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9194. typeof Worker !== 'undefined') {
  9195. var workerSrc = getWorkerSrc();
  9196. try {
  9197. // Wraps workerSrc path into blob URL, if the former does not belong
  9198. // to the same origin.
  9199. if (!isSameOrigin(window.location.href, workerSrc)) {
  9200. workerSrc = createCDNWrapper(
  9201. new URL(workerSrc, window.location).href);
  9202. }
  9203. // Some versions of FF can't create a worker on localhost, see:
  9204. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9205. var worker = new Worker(workerSrc);
  9206. var messageHandler = new MessageHandler('main', 'worker', worker);
  9207. var terminateEarly = function() {
  9208. worker.removeEventListener('error', onWorkerError);
  9209. messageHandler.destroy();
  9210. worker.terminate();
  9211. if (this.destroyed) {
  9212. this._readyCapability.reject(new Error('Worker was destroyed'));
  9213. } else {
  9214. // Fall back to fake worker if the termination is caused by an
  9215. // error (e.g. NetworkError / SecurityError).
  9216. this._setupFakeWorker();
  9217. }
  9218. }.bind(this);
  9219. var onWorkerError = function(event) {
  9220. if (!this._webWorker) {
  9221. // Worker failed to initialize due to an error. Clean up and fall
  9222. // back to the fake worker.
  9223. terminateEarly();
  9224. }
  9225. }.bind(this);
  9226. worker.addEventListener('error', onWorkerError);
  9227. messageHandler.on('test', function PDFWorker_test(data) {
  9228. worker.removeEventListener('error', onWorkerError);
  9229. if (this.destroyed) {
  9230. terminateEarly();
  9231. return; // worker was destroyed
  9232. }
  9233. var supportTypedArray = data && data.supportTypedArray;
  9234. if (supportTypedArray) {
  9235. this._messageHandler = messageHandler;
  9236. this._port = worker;
  9237. this._webWorker = worker;
  9238. if (!data.supportTransfers) {
  9239. isPostMessageTransfersDisabled = true;
  9240. }
  9241. this._readyCapability.resolve();
  9242. // Send global setting, e.g. verbosity level.
  9243. messageHandler.send('configure', {
  9244. verbosity: getVerbosityLevel()
  9245. });
  9246. } else {
  9247. this._setupFakeWorker();
  9248. messageHandler.destroy();
  9249. worker.terminate();
  9250. }
  9251. }.bind(this));
  9252. messageHandler.on('console_log', function (data) {
  9253. console.log.apply(console, data);
  9254. });
  9255. messageHandler.on('console_error', function (data) {
  9256. console.error.apply(console, data);
  9257. });
  9258. messageHandler.on('ready', function (data) {
  9259. worker.removeEventListener('error', onWorkerError);
  9260. if (this.destroyed) {
  9261. terminateEarly();
  9262. return; // worker was destroyed
  9263. }
  9264. try {
  9265. sendTest();
  9266. } catch (e) {
  9267. // We need fallback to a faked worker.
  9268. this._setupFakeWorker();
  9269. }
  9270. }.bind(this));
  9271. var sendTest = function () {
  9272. var postMessageTransfers =
  9273. getDefaultSetting('postMessageTransfers') &&
  9274. !isPostMessageTransfersDisabled;
  9275. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9276. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9277. // typed array. Also, checking if we can use transfers.
  9278. try {
  9279. messageHandler.send('test', testObj, [testObj.buffer]);
  9280. } catch (ex) {
  9281. info('Cannot use postMessage transfers');
  9282. testObj[0] = 0;
  9283. messageHandler.send('test', testObj);
  9284. }
  9285. };
  9286. // It might take time for worker to initialize (especially when AMD
  9287. // loader is used). We will try to send test immediately, and then
  9288. // when 'ready' message will arrive. The worker shall process only
  9289. // first received 'test'.
  9290. sendTest();
  9291. return;
  9292. } catch (e) {
  9293. info('The worker has been disabled.');
  9294. }
  9295. }
  9296. // Either workers are disabled, not supported or have thrown an exception.
  9297. // Thus, we fallback to a faked worker.
  9298. this._setupFakeWorker();
  9299. },
  9300. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9301. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9302. warn('Setting up fake worker.');
  9303. isWorkerDisabled = true;
  9304. }
  9305. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9306. if (this.destroyed) {
  9307. this._readyCapability.reject(new Error('Worker was destroyed'));
  9308. return;
  9309. }
  9310. // We cannot turn on proper fake port simulation (this includes
  9311. // structured cloning) when typed arrays are not supported. Relying
  9312. // on a chance that messages will be sent in proper order.
  9313. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9314. var port = new FakeWorkerPort(isTypedArraysPresent);
  9315. this._port = port;
  9316. // All fake workers use the same port, making id unique.
  9317. var id = 'fake' + (nextFakeWorkerId++);
  9318. // If the main thread is our worker, setup the handling for the
  9319. // messages -- the main thread sends to it self.
  9320. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9321. WorkerMessageHandler.setup(workerHandler, port);
  9322. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9323. this._messageHandler = messageHandler;
  9324. this._readyCapability.resolve();
  9325. }.bind(this));
  9326. },
  9327. /**
  9328. * Destroys the worker instance.
  9329. */
  9330. destroy: function PDFWorker_destroy() {
  9331. this.destroyed = true;
  9332. if (this._webWorker) {
  9333. // We need to terminate only web worker created resource.
  9334. this._webWorker.terminate();
  9335. this._webWorker = null;
  9336. }
  9337. this._port = null;
  9338. if (this._messageHandler) {
  9339. this._messageHandler.destroy();
  9340. this._messageHandler = null;
  9341. }
  9342. }
  9343. };
  9344. return PDFWorker;
  9345. })();
  9346. /**
  9347. * For internal use only.
  9348. * @ignore
  9349. */
  9350. var WorkerTransport = (function WorkerTransportClosure() {
  9351. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9352. this.messageHandler = messageHandler;
  9353. this.loadingTask = loadingTask;
  9354. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9355. this.commonObjs = new PDFObjects();
  9356. this.fontLoader = new FontLoader(loadingTask.docId);
  9357. this.destroyed = false;
  9358. this.destroyCapability = null;
  9359. this.pageCache = [];
  9360. this.pagePromises = [];
  9361. this.downloadInfoCapability = createPromiseCapability();
  9362. this.setupMessageHandler();
  9363. }
  9364. WorkerTransport.prototype = {
  9365. destroy: function WorkerTransport_destroy() {
  9366. if (this.destroyCapability) {
  9367. return this.destroyCapability.promise;
  9368. }
  9369. this.destroyed = true;
  9370. this.destroyCapability = createPromiseCapability();
  9371. var waitOn = [];
  9372. // We need to wait for all renderings to be completed, e.g.
  9373. // timeout/rAF can take a long time.
  9374. this.pageCache.forEach(function (page) {
  9375. if (page) {
  9376. waitOn.push(page._destroy());
  9377. }
  9378. });
  9379. this.pageCache = [];
  9380. this.pagePromises = [];
  9381. var self = this;
  9382. // We also need to wait for the worker to finish its long running tasks.
  9383. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9384. waitOn.push(terminated);
  9385. Promise.all(waitOn).then(function () {
  9386. self.fontLoader.clear();
  9387. if (self.pdfDataRangeTransport) {
  9388. self.pdfDataRangeTransport.abort();
  9389. self.pdfDataRangeTransport = null;
  9390. }
  9391. if (self.messageHandler) {
  9392. self.messageHandler.destroy();
  9393. self.messageHandler = null;
  9394. }
  9395. self.destroyCapability.resolve();
  9396. }, this.destroyCapability.reject);
  9397. return this.destroyCapability.promise;
  9398. },
  9399. setupMessageHandler:
  9400. function WorkerTransport_setupMessageHandler() {
  9401. var messageHandler = this.messageHandler;
  9402. function updatePassword(password) {
  9403. messageHandler.send('UpdatePassword', password);
  9404. }
  9405. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9406. if (pdfDataRangeTransport) {
  9407. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9408. messageHandler.send('OnDataRange', {
  9409. begin: begin,
  9410. chunk: chunk
  9411. });
  9412. });
  9413. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9414. messageHandler.send('OnDataProgress', {
  9415. loaded: loaded
  9416. });
  9417. });
  9418. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9419. messageHandler.send('OnDataRange', {
  9420. chunk: chunk
  9421. });
  9422. });
  9423. messageHandler.on('RequestDataRange',
  9424. function transportDataRange(data) {
  9425. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9426. }, this);
  9427. }
  9428. messageHandler.on('GetDoc', function transportDoc(data) {
  9429. var pdfInfo = data.pdfInfo;
  9430. this.numPages = data.pdfInfo.numPages;
  9431. var loadingTask = this.loadingTask;
  9432. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9433. this.pdfDocument = pdfDocument;
  9434. loadingTask._capability.resolve(pdfDocument);
  9435. }, this);
  9436. messageHandler.on('NeedPassword',
  9437. function transportNeedPassword(exception) {
  9438. var loadingTask = this.loadingTask;
  9439. if (loadingTask.onPassword) {
  9440. return loadingTask.onPassword(updatePassword,
  9441. PasswordResponses.NEED_PASSWORD);
  9442. }
  9443. loadingTask._capability.reject(
  9444. new PasswordException(exception.message, exception.code));
  9445. }, this);
  9446. messageHandler.on('IncorrectPassword',
  9447. function transportIncorrectPassword(exception) {
  9448. var loadingTask = this.loadingTask;
  9449. if (loadingTask.onPassword) {
  9450. return loadingTask.onPassword(updatePassword,
  9451. PasswordResponses.INCORRECT_PASSWORD);
  9452. }
  9453. loadingTask._capability.reject(
  9454. new PasswordException(exception.message, exception.code));
  9455. }, this);
  9456. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9457. this.loadingTask._capability.reject(
  9458. new InvalidPDFException(exception.message));
  9459. }, this);
  9460. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9461. this.loadingTask._capability.reject(
  9462. new MissingPDFException(exception.message));
  9463. }, this);
  9464. messageHandler.on('UnexpectedResponse',
  9465. function transportUnexpectedResponse(exception) {
  9466. this.loadingTask._capability.reject(
  9467. new UnexpectedResponseException(exception.message, exception.status));
  9468. }, this);
  9469. messageHandler.on('UnknownError',
  9470. function transportUnknownError(exception) {
  9471. this.loadingTask._capability.reject(
  9472. new UnknownErrorException(exception.message, exception.details));
  9473. }, this);
  9474. messageHandler.on('DataLoaded', function transportPage(data) {
  9475. this.downloadInfoCapability.resolve(data);
  9476. }, this);
  9477. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9478. if (this.pdfDataRangeTransport) {
  9479. this.pdfDataRangeTransport.transportReady();
  9480. }
  9481. }, this);
  9482. messageHandler.on('StartRenderPage', function transportRender(data) {
  9483. if (this.destroyed) {
  9484. return; // Ignore any pending requests if the worker was terminated.
  9485. }
  9486. var page = this.pageCache[data.pageIndex];
  9487. page.stats.timeEnd('Page Request');
  9488. page._startRenderPage(data.transparency, data.intent);
  9489. }, this);
  9490. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9491. if (this.destroyed) {
  9492. return; // Ignore any pending requests if the worker was terminated.
  9493. }
  9494. var page = this.pageCache[data.pageIndex];
  9495. page._renderPageChunk(data.operatorList, data.intent);
  9496. }, this);
  9497. messageHandler.on('commonobj', function transportObj(data) {
  9498. if (this.destroyed) {
  9499. return; // Ignore any pending requests if the worker was terminated.
  9500. }
  9501. var id = data[0];
  9502. var type = data[1];
  9503. if (this.commonObjs.hasData(id)) {
  9504. return;
  9505. }
  9506. switch (type) {
  9507. case 'Font':
  9508. var exportedData = data[2];
  9509. if ('error' in exportedData) {
  9510. var exportedError = exportedData.error;
  9511. warn('Error during font loading: ' + exportedError);
  9512. this.commonObjs.resolve(id, exportedError);
  9513. break;
  9514. }
  9515. var fontRegistry = null;
  9516. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9517. globalScope['FontInspector'].enabled) {
  9518. fontRegistry = {
  9519. registerFont: function (font, url) {
  9520. globalScope['FontInspector'].fontAdded(font, url);
  9521. }
  9522. };
  9523. }
  9524. var font = new FontFaceObject(exportedData, {
  9525. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9526. disableFontFace: getDefaultSetting('disableFontFace'),
  9527. fontRegistry: fontRegistry
  9528. });
  9529. this.fontLoader.bind(
  9530. [font],
  9531. function fontReady(fontObjs) {
  9532. this.commonObjs.resolve(id, font);
  9533. }.bind(this)
  9534. );
  9535. break;
  9536. case 'FontPath':
  9537. this.commonObjs.resolve(id, data[2]);
  9538. break;
  9539. default:
  9540. error('Got unknown common object type ' + type);
  9541. }
  9542. }, this);
  9543. messageHandler.on('obj', function transportObj(data) {
  9544. if (this.destroyed) {
  9545. return; // Ignore any pending requests if the worker was terminated.
  9546. }
  9547. var id = data[0];
  9548. var pageIndex = data[1];
  9549. var type = data[2];
  9550. var pageProxy = this.pageCache[pageIndex];
  9551. var imageData;
  9552. if (pageProxy.objs.hasData(id)) {
  9553. return;
  9554. }
  9555. switch (type) {
  9556. case 'JpegStream':
  9557. imageData = data[3];
  9558. loadJpegStream(id, imageData, pageProxy.objs);
  9559. break;
  9560. case 'Image':
  9561. imageData = data[3];
  9562. pageProxy.objs.resolve(id, imageData);
  9563. // heuristics that will allow not to store large data
  9564. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9565. if (imageData && 'data' in imageData &&
  9566. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9567. pageProxy.cleanupAfterRender = true;
  9568. }
  9569. break;
  9570. default:
  9571. error('Got unknown object type ' + type);
  9572. }
  9573. }, this);
  9574. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9575. if (this.destroyed) {
  9576. return; // Ignore any pending requests if the worker was terminated.
  9577. }
  9578. var loadingTask = this.loadingTask;
  9579. if (loadingTask.onProgress) {
  9580. loadingTask.onProgress({
  9581. loaded: data.loaded,
  9582. total: data.total
  9583. });
  9584. }
  9585. }, this);
  9586. messageHandler.on('PageError', function transportError(data) {
  9587. if (this.destroyed) {
  9588. return; // Ignore any pending requests if the worker was terminated.
  9589. }
  9590. var page = this.pageCache[data.pageNum - 1];
  9591. var intentState = page.intentStates[data.intent];
  9592. if (intentState.displayReadyCapability) {
  9593. intentState.displayReadyCapability.reject(data.error);
  9594. } else {
  9595. error(data.error);
  9596. }
  9597. if (intentState.operatorList) {
  9598. // Mark operator list as complete.
  9599. intentState.operatorList.lastChunk = true;
  9600. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9601. intentState.renderTasks[i].operatorListChanged();
  9602. }
  9603. }
  9604. }, this);
  9605. messageHandler.on('UnsupportedFeature',
  9606. function transportUnsupportedFeature(data) {
  9607. if (this.destroyed) {
  9608. return; // Ignore any pending requests if the worker was terminated.
  9609. }
  9610. var featureId = data.featureId;
  9611. var loadingTask = this.loadingTask;
  9612. if (loadingTask.onUnsupportedFeature) {
  9613. loadingTask.onUnsupportedFeature(featureId);
  9614. }
  9615. _UnsupportedManager.notify(featureId);
  9616. }, this);
  9617. messageHandler.on('JpegDecode', function(data) {
  9618. if (this.destroyed) {
  9619. return Promise.reject(new Error('Worker was destroyed'));
  9620. }
  9621. var imageUrl = data[0];
  9622. var components = data[1];
  9623. if (components !== 3 && components !== 1) {
  9624. return Promise.reject(
  9625. new Error('Only 3 components or 1 component can be returned'));
  9626. }
  9627. return new Promise(function (resolve, reject) {
  9628. var img = new Image();
  9629. img.onload = function () {
  9630. var width = img.width;
  9631. var height = img.height;
  9632. var size = width * height;
  9633. var rgbaLength = size * 4;
  9634. var buf = new Uint8Array(size * components);
  9635. var tmpCanvas = createScratchCanvas(width, height);
  9636. var tmpCtx = tmpCanvas.getContext('2d');
  9637. tmpCtx.drawImage(img, 0, 0);
  9638. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9639. var i, j;
  9640. if (components === 3) {
  9641. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9642. buf[j] = data[i];
  9643. buf[j + 1] = data[i + 1];
  9644. buf[j + 2] = data[i + 2];
  9645. }
  9646. } else if (components === 1) {
  9647. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9648. buf[j] = data[i];
  9649. }
  9650. }
  9651. resolve({ data: buf, width: width, height: height});
  9652. };
  9653. img.onerror = function () {
  9654. reject(new Error('JpegDecode failed to load image'));
  9655. };
  9656. img.src = imageUrl;
  9657. });
  9658. }, this);
  9659. },
  9660. getData: function WorkerTransport_getData() {
  9661. return this.messageHandler.sendWithPromise('GetData', null);
  9662. },
  9663. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9664. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9665. return Promise.reject(new Error('Invalid page request'));
  9666. }
  9667. var pageIndex = pageNumber - 1;
  9668. if (pageIndex in this.pagePromises) {
  9669. return this.pagePromises[pageIndex];
  9670. }
  9671. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9672. pageIndex: pageIndex
  9673. }).then(function (pageInfo) {
  9674. if (this.destroyed) {
  9675. throw new Error('Transport destroyed');
  9676. }
  9677. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9678. this.pageCache[pageIndex] = page;
  9679. return page;
  9680. }.bind(this));
  9681. this.pagePromises[pageIndex] = promise;
  9682. return promise;
  9683. },
  9684. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9685. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9686. ref: ref,
  9687. }).catch(function (reason) {
  9688. return Promise.reject(new Error(reason));
  9689. });
  9690. },
  9691. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9692. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9693. pageIndex: pageIndex,
  9694. intent: intent,
  9695. });
  9696. },
  9697. getDestinations: function WorkerTransport_getDestinations() {
  9698. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9699. },
  9700. getDestination: function WorkerTransport_getDestination(id) {
  9701. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9702. },
  9703. getPageLabels: function WorkerTransport_getPageLabels() {
  9704. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9705. },
  9706. getAttachments: function WorkerTransport_getAttachments() {
  9707. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9708. },
  9709. getJavaScript: function WorkerTransport_getJavaScript() {
  9710. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9711. },
  9712. getOutline: function WorkerTransport_getOutline() {
  9713. return this.messageHandler.sendWithPromise('GetOutline', null);
  9714. },
  9715. getMetadata: function WorkerTransport_getMetadata() {
  9716. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9717. then(function transportMetadata(results) {
  9718. return {
  9719. info: results[0],
  9720. metadata: (results[1] ? new Metadata(results[1]) : null)
  9721. };
  9722. });
  9723. },
  9724. getStats: function WorkerTransport_getStats() {
  9725. return this.messageHandler.sendWithPromise('GetStats', null);
  9726. },
  9727. startCleanup: function WorkerTransport_startCleanup() {
  9728. this.messageHandler.sendWithPromise('Cleanup', null).
  9729. then(function endCleanup() {
  9730. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9731. var page = this.pageCache[i];
  9732. if (page) {
  9733. page.cleanup();
  9734. }
  9735. }
  9736. this.commonObjs.clear();
  9737. this.fontLoader.clear();
  9738. }.bind(this));
  9739. }
  9740. };
  9741. return WorkerTransport;
  9742. })();
  9743. /**
  9744. * A PDF document and page is built of many objects. E.g. there are objects
  9745. * for fonts, images, rendering code and such. These objects might get processed
  9746. * inside of a worker. The `PDFObjects` implements some basic functions to
  9747. * manage these objects.
  9748. * @ignore
  9749. */
  9750. var PDFObjects = (function PDFObjectsClosure() {
  9751. function PDFObjects() {
  9752. this.objs = Object.create(null);
  9753. }
  9754. PDFObjects.prototype = {
  9755. /**
  9756. * Internal function.
  9757. * Ensures there is an object defined for `objId`.
  9758. */
  9759. ensureObj: function PDFObjects_ensureObj(objId) {
  9760. if (this.objs[objId]) {
  9761. return this.objs[objId];
  9762. }
  9763. var obj = {
  9764. capability: createPromiseCapability(),
  9765. data: null,
  9766. resolved: false
  9767. };
  9768. this.objs[objId] = obj;
  9769. return obj;
  9770. },
  9771. /**
  9772. * If called *without* callback, this returns the data of `objId` but the
  9773. * object needs to be resolved. If it isn't, this function throws.
  9774. *
  9775. * If called *with* a callback, the callback is called with the data of the
  9776. * object once the object is resolved. That means, if you call this
  9777. * function and the object is already resolved, the callback gets called
  9778. * right away.
  9779. */
  9780. get: function PDFObjects_get(objId, callback) {
  9781. // If there is a callback, then the get can be async and the object is
  9782. // not required to be resolved right now
  9783. if (callback) {
  9784. this.ensureObj(objId).capability.promise.then(callback);
  9785. return null;
  9786. }
  9787. // If there isn't a callback, the user expects to get the resolved data
  9788. // directly.
  9789. var obj = this.objs[objId];
  9790. // If there isn't an object yet or the object isn't resolved, then the
  9791. // data isn't ready yet!
  9792. if (!obj || !obj.resolved) {
  9793. error('Requesting object that isn\'t resolved yet ' + objId);
  9794. }
  9795. return obj.data;
  9796. },
  9797. /**
  9798. * Resolves the object `objId` with optional `data`.
  9799. */
  9800. resolve: function PDFObjects_resolve(objId, data) {
  9801. var obj = this.ensureObj(objId);
  9802. obj.resolved = true;
  9803. obj.data = data;
  9804. obj.capability.resolve(data);
  9805. },
  9806. isResolved: function PDFObjects_isResolved(objId) {
  9807. var objs = this.objs;
  9808. if (!objs[objId]) {
  9809. return false;
  9810. } else {
  9811. return objs[objId].resolved;
  9812. }
  9813. },
  9814. hasData: function PDFObjects_hasData(objId) {
  9815. return this.isResolved(objId);
  9816. },
  9817. /**
  9818. * Returns the data of `objId` if object exists, null otherwise.
  9819. */
  9820. getData: function PDFObjects_getData(objId) {
  9821. var objs = this.objs;
  9822. if (!objs[objId] || !objs[objId].resolved) {
  9823. return null;
  9824. } else {
  9825. return objs[objId].data;
  9826. }
  9827. },
  9828. clear: function PDFObjects_clear() {
  9829. this.objs = Object.create(null);
  9830. }
  9831. };
  9832. return PDFObjects;
  9833. })();
  9834. /**
  9835. * Allows controlling of the rendering tasks.
  9836. * @class
  9837. * @alias RenderTask
  9838. */
  9839. var RenderTask = (function RenderTaskClosure() {
  9840. function RenderTask(internalRenderTask) {
  9841. this._internalRenderTask = internalRenderTask;
  9842. /**
  9843. * Callback for incremental rendering -- a function that will be called
  9844. * each time the rendering is paused. To continue rendering call the
  9845. * function that is the first argument to the callback.
  9846. * @type {function}
  9847. */
  9848. this.onContinue = null;
  9849. }
  9850. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9851. /**
  9852. * Promise for rendering task completion.
  9853. * @return {Promise}
  9854. */
  9855. get promise() {
  9856. return this._internalRenderTask.capability.promise;
  9857. },
  9858. /**
  9859. * Cancels the rendering task. If the task is currently rendering it will
  9860. * not be cancelled until graphics pauses with a timeout. The promise that
  9861. * this object extends will resolved when cancelled.
  9862. */
  9863. cancel: function RenderTask_cancel() {
  9864. this._internalRenderTask.cancel();
  9865. },
  9866. /**
  9867. * Registers callbacks to indicate the rendering task completion.
  9868. *
  9869. * @param {function} onFulfilled The callback for the rendering completion.
  9870. * @param {function} onRejected The callback for the rendering failure.
  9871. * @return {Promise} A promise that is resolved after the onFulfilled or
  9872. * onRejected callback.
  9873. */
  9874. then: function RenderTask_then(onFulfilled, onRejected) {
  9875. return this.promise.then.apply(this.promise, arguments);
  9876. }
  9877. };
  9878. return RenderTask;
  9879. })();
  9880. /**
  9881. * For internal use only.
  9882. * @ignore
  9883. */
  9884. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9885. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9886. pageNumber) {
  9887. this.callback = callback;
  9888. this.params = params;
  9889. this.objs = objs;
  9890. this.commonObjs = commonObjs;
  9891. this.operatorListIdx = null;
  9892. this.operatorList = operatorList;
  9893. this.pageNumber = pageNumber;
  9894. this.running = false;
  9895. this.graphicsReadyCallback = null;
  9896. this.graphicsReady = false;
  9897. this.useRequestAnimationFrame = false;
  9898. this.cancelled = false;
  9899. this.capability = createPromiseCapability();
  9900. this.task = new RenderTask(this);
  9901. // caching this-bound methods
  9902. this._continueBound = this._continue.bind(this);
  9903. this._scheduleNextBound = this._scheduleNext.bind(this);
  9904. this._nextBound = this._next.bind(this);
  9905. }
  9906. InternalRenderTask.prototype = {
  9907. initializeGraphics:
  9908. function InternalRenderTask_initializeGraphics(transparency) {
  9909. if (this.cancelled) {
  9910. return;
  9911. }
  9912. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9913. globalScope.StepperManager.enabled) {
  9914. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9915. this.stepper.init(this.operatorList);
  9916. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9917. }
  9918. var params = this.params;
  9919. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9920. this.objs, params.imageLayer);
  9921. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9922. this.operatorListIdx = 0;
  9923. this.graphicsReady = true;
  9924. if (this.graphicsReadyCallback) {
  9925. this.graphicsReadyCallback();
  9926. }
  9927. },
  9928. cancel: function InternalRenderTask_cancel() {
  9929. this.running = false;
  9930. this.cancelled = true;
  9931. this.callback('cancelled');
  9932. },
  9933. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9934. if (!this.graphicsReady) {
  9935. if (!this.graphicsReadyCallback) {
  9936. this.graphicsReadyCallback = this._continueBound;
  9937. }
  9938. return;
  9939. }
  9940. if (this.stepper) {
  9941. this.stepper.updateOperatorList(this.operatorList);
  9942. }
  9943. if (this.running) {
  9944. return;
  9945. }
  9946. this._continue();
  9947. },
  9948. _continue: function InternalRenderTask__continue() {
  9949. this.running = true;
  9950. if (this.cancelled) {
  9951. return;
  9952. }
  9953. if (this.task.onContinue) {
  9954. this.task.onContinue.call(this.task, this._scheduleNextBound);
  9955. } else {
  9956. this._scheduleNext();
  9957. }
  9958. },
  9959. _scheduleNext: function InternalRenderTask__scheduleNext() {
  9960. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  9961. window.requestAnimationFrame(this._nextBound);
  9962. } else {
  9963. Promise.resolve(undefined).then(this._nextBound);
  9964. }
  9965. },
  9966. _next: function InternalRenderTask__next() {
  9967. if (this.cancelled) {
  9968. return;
  9969. }
  9970. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  9971. this.operatorListIdx,
  9972. this._continueBound,
  9973. this.stepper);
  9974. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  9975. this.running = false;
  9976. if (this.operatorList.lastChunk) {
  9977. this.gfx.endDrawing();
  9978. this.callback();
  9979. }
  9980. }
  9981. }
  9982. };
  9983. return InternalRenderTask;
  9984. })();
  9985. /**
  9986. * (Deprecated) Global observer of unsupported feature usages. Use
  9987. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  9988. */
  9989. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  9990. var listeners = [];
  9991. return {
  9992. listen: function (cb) {
  9993. deprecated('Global UnsupportedManager.listen is used: ' +
  9994. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  9995. listeners.push(cb);
  9996. },
  9997. notify: function (featureId) {
  9998. for (var i = 0, ii = listeners.length; i < ii; i++) {
  9999. listeners[i](featureId);
  10000. }
  10001. }
  10002. };
  10003. })();
  10004. if (typeof pdfjsVersion !== 'undefined') {
  10005. exports.version = pdfjsVersion;
  10006. }
  10007. if (typeof pdfjsBuild !== 'undefined') {
  10008. exports.build = pdfjsBuild;
  10009. }
  10010. exports.getDocument = getDocument;
  10011. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10012. exports.PDFWorker = PDFWorker;
  10013. exports.PDFDocumentProxy = PDFDocumentProxy;
  10014. exports.PDFPageProxy = PDFPageProxy;
  10015. exports._UnsupportedManager = _UnsupportedManager;
  10016. }));
  10017. (function (root, factory) {
  10018. {
  10019. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  10020. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  10021. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  10022. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10023. }
  10024. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  10025. displayAnnotationLayer, displayTextLayer, displayMetadata,
  10026. displaySVG) {
  10027. var globalScope = sharedUtil.globalScope;
  10028. var deprecated = sharedUtil.deprecated;
  10029. var warn = sharedUtil.warn;
  10030. var LinkTarget = displayDOMUtils.LinkTarget;
  10031. var isWorker = (typeof window === 'undefined');
  10032. // The global PDFJS object is now deprecated and will not be supported in
  10033. // the future. The members below are maintained for backward compatibility
  10034. // and shall not be extended or modified. If the global.js is included as
  10035. // a module, we will create a global PDFJS object instance or use existing.
  10036. if (!globalScope.PDFJS) {
  10037. globalScope.PDFJS = {};
  10038. }
  10039. var PDFJS = globalScope.PDFJS;
  10040. if (typeof pdfjsVersion !== 'undefined') {
  10041. PDFJS.version = pdfjsVersion;
  10042. }
  10043. if (typeof pdfjsBuild !== 'undefined') {
  10044. PDFJS.build = pdfjsBuild;
  10045. }
  10046. PDFJS.pdfBug = false;
  10047. if (PDFJS.verbosity !== undefined) {
  10048. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10049. }
  10050. delete PDFJS.verbosity;
  10051. Object.defineProperty(PDFJS, 'verbosity', {
  10052. get: function () { return sharedUtil.getVerbosityLevel(); },
  10053. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10058. PDFJS.OPS = sharedUtil.OPS;
  10059. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10060. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10061. PDFJS.shadow = sharedUtil.shadow;
  10062. PDFJS.createBlob = sharedUtil.createBlob;
  10063. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10064. return sharedUtil.createObjectURL(data, contentType,
  10065. PDFJS.disableCreateObjectURL);
  10066. };
  10067. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10068. configurable: true,
  10069. get: function PDFJS_isLittleEndian() {
  10070. var value = sharedUtil.isLittleEndian();
  10071. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10072. }
  10073. });
  10074. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10075. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10076. PDFJS.PasswordException = sharedUtil.PasswordException;
  10077. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10078. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10079. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10080. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10081. PDFJS.Util = sharedUtil.Util;
  10082. PDFJS.PageViewport = sharedUtil.PageViewport;
  10083. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10084. /**
  10085. * The maximum allowed image size in total pixels e.g. width * height. Images
  10086. * above this value will not be drawn. Use -1 for no limit.
  10087. * @var {number}
  10088. */
  10089. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  10090. -1 : PDFJS.maxImageSize);
  10091. /**
  10092. * The url of where the predefined Adobe CMaps are located. Include trailing
  10093. * slash.
  10094. * @var {string}
  10095. */
  10096. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  10097. /**
  10098. * Specifies if CMaps are binary packed.
  10099. * @var {boolean}
  10100. */
  10101. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10102. /**
  10103. * By default fonts are converted to OpenType fonts and loaded via font face
  10104. * rules. If disabled, the font will be rendered using a built in font
  10105. * renderer that constructs the glyphs with primitive path commands.
  10106. * @var {boolean}
  10107. */
  10108. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  10109. false : PDFJS.disableFontFace);
  10110. /**
  10111. * Path for image resources, mainly for annotation icons. Include trailing
  10112. * slash.
  10113. * @var {string}
  10114. */
  10115. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  10116. '' : PDFJS.imageResourcesPath);
  10117. /**
  10118. * Disable the web worker and run all code on the main thread. This will
  10119. * happen automatically if the browser doesn't support workers or sending
  10120. * typed arrays to workers.
  10121. * @var {boolean}
  10122. */
  10123. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  10124. false : PDFJS.disableWorker);
  10125. /**
  10126. * Path and filename of the worker file. Required when the worker is enabled
  10127. * in development mode. If unspecified in the production build, the worker
  10128. * will be loaded based on the location of the pdf.js file. It is recommended
  10129. * that the workerSrc is set in a custom application to prevent issues caused
  10130. * by third-party frameworks and libraries.
  10131. * @var {string}
  10132. */
  10133. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  10134. /**
  10135. * Disable range request loading of PDF files. When enabled and if the server
  10136. * supports partial content requests then the PDF will be fetched in chunks.
  10137. * Enabled (false) by default.
  10138. * @var {boolean}
  10139. */
  10140. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  10141. false : PDFJS.disableRange);
  10142. /**
  10143. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10144. * in chunks. This default behavior can be disabled.
  10145. * @var {boolean}
  10146. */
  10147. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  10148. false : PDFJS.disableStream);
  10149. /**
  10150. * Disable pre-fetching of PDF file data. When range requests are enabled
  10151. * PDF.js will automatically keep fetching more data even if it isn't needed
  10152. * to display the current page. This default behavior can be disabled.
  10153. *
  10154. * NOTE: It is also necessary to disable streaming, see above,
  10155. * in order for disabling of pre-fetching to work correctly.
  10156. * @var {boolean}
  10157. */
  10158. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10159. false : PDFJS.disableAutoFetch);
  10160. /**
  10161. * Enables special hooks for debugging PDF.js.
  10162. * @var {boolean}
  10163. */
  10164. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10165. /**
  10166. * Enables transfer usage in postMessage for ArrayBuffers.
  10167. * @var {boolean}
  10168. */
  10169. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10170. true : PDFJS.postMessageTransfers);
  10171. /**
  10172. * Disables URL.createObjectURL usage.
  10173. * @var {boolean}
  10174. */
  10175. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10176. false : PDFJS.disableCreateObjectURL);
  10177. /**
  10178. * Disables WebGL usage.
  10179. * @var {boolean}
  10180. */
  10181. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10182. true : PDFJS.disableWebGL);
  10183. /**
  10184. * Specifies the |target| attribute for external links.
  10185. * The constants from PDFJS.LinkTarget should be used:
  10186. * - NONE [default]
  10187. * - SELF
  10188. * - BLANK
  10189. * - PARENT
  10190. * - TOP
  10191. * @var {number}
  10192. */
  10193. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10194. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10195. /**
  10196. * Specifies the |rel| attribute for external links. Defaults to stripping
  10197. * the referrer.
  10198. * @var {string}
  10199. */
  10200. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10201. 'noreferrer' : PDFJS.externalLinkRel);
  10202. /**
  10203. * Determines if we can eval strings as JS. Primarily used to improve
  10204. * performance for font rendering.
  10205. * @var {boolean}
  10206. */
  10207. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10208. true : PDFJS.isEvalSupported);
  10209. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10210. delete PDFJS.openExternalLinksInNewWindow;
  10211. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10212. get: function () {
  10213. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10214. },
  10215. set: function (value) {
  10216. if (value) {
  10217. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10218. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10219. }
  10220. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10221. warn('PDFJS.externalLinkTarget is already initialized');
  10222. return;
  10223. }
  10224. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. if (savedOpenExternalLinksInNewWindow) {
  10230. /**
  10231. * (Deprecated) Opens external links in a new window if enabled.
  10232. * The default behavior opens external links in the PDF.js window.
  10233. *
  10234. * NOTE: This property has been deprecated, please use
  10235. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10236. * @var {boolean}
  10237. */
  10238. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10239. }
  10240. PDFJS.getDocument = displayAPI.getDocument;
  10241. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10242. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10243. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10244. configurable: true,
  10245. get: function PDFJS_hasCanvasTypedArrays() {
  10246. var value = displayDOMUtils.hasCanvasTypedArrays();
  10247. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10248. }
  10249. });
  10250. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10251. PDFJS.LinkTarget = LinkTarget;
  10252. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10253. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10254. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10255. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10256. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10257. PDFJS.Metadata = displayMetadata.Metadata;
  10258. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10259. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10260. exports.globalScope = globalScope;
  10261. exports.isWorker = isWorker;
  10262. exports.PDFJS = globalScope.PDFJS;
  10263. }));
  10264. }).call(pdfjsLibs);
  10265. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10266. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10267. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10268. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10269. exports.PDFDataRangeTransport =
  10270. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10271. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10272. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10273. exports.AnnotationLayer =
  10274. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10275. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10276. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10277. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10278. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10279. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10280. exports.UnexpectedResponseException =
  10281. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10282. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10283. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10284. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10285. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10286. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10287. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10288. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10289. exports.getFilenameFromUrl =
  10290. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10291. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10292. }));