pdf.js 368 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575
  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.6.217';
  30. var pdfjsBuild = '9b3a91f';
  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 =
  787. function Util_getInheritableProperty(dict, name, getArray) {
  788. while (dict && !dict.has(name)) {
  789. dict = dict.get('Parent');
  790. }
  791. if (!dict) {
  792. return null;
  793. }
  794. return getArray ? dict.getArray(name) : 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. case 'Ch':
  3950. return new ChoiceWidgetAnnotationElement(parameters);
  3951. }
  3952. return new WidgetAnnotationElement(parameters);
  3953. case AnnotationType.POPUP:
  3954. return new PopupAnnotationElement(parameters);
  3955. case AnnotationType.HIGHLIGHT:
  3956. return new HighlightAnnotationElement(parameters);
  3957. case AnnotationType.UNDERLINE:
  3958. return new UnderlineAnnotationElement(parameters);
  3959. case AnnotationType.SQUIGGLY:
  3960. return new SquigglyAnnotationElement(parameters);
  3961. case AnnotationType.STRIKEOUT:
  3962. return new StrikeOutAnnotationElement(parameters);
  3963. case AnnotationType.FILEATTACHMENT:
  3964. return new FileAttachmentAnnotationElement(parameters);
  3965. default:
  3966. return new AnnotationElement(parameters);
  3967. }
  3968. }
  3969. };
  3970. /**
  3971. * @class
  3972. * @alias AnnotationElement
  3973. */
  3974. var AnnotationElement = (function AnnotationElementClosure() {
  3975. function AnnotationElement(parameters, isRenderable) {
  3976. this.isRenderable = isRenderable || false;
  3977. this.data = parameters.data;
  3978. this.layer = parameters.layer;
  3979. this.page = parameters.page;
  3980. this.viewport = parameters.viewport;
  3981. this.linkService = parameters.linkService;
  3982. this.downloadManager = parameters.downloadManager;
  3983. this.imageResourcesPath = parameters.imageResourcesPath;
  3984. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3985. if (isRenderable) {
  3986. this.container = this._createContainer();
  3987. }
  3988. }
  3989. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3990. /**
  3991. * Create an empty container for the annotation's HTML element.
  3992. *
  3993. * @private
  3994. * @memberof AnnotationElement
  3995. * @returns {HTMLSectionElement}
  3996. */
  3997. _createContainer: function AnnotationElement_createContainer() {
  3998. var data = this.data, page = this.page, viewport = this.viewport;
  3999. var container = document.createElement('section');
  4000. var width = data.rect[2] - data.rect[0];
  4001. var height = data.rect[3] - data.rect[1];
  4002. container.setAttribute('data-annotation-id', data.id);
  4003. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4004. // position on subsequent calls to `_createContainer` (see issue 6804).
  4005. var rect = Util.normalizeRect([
  4006. data.rect[0],
  4007. page.view[3] - data.rect[1] + page.view[1],
  4008. data.rect[2],
  4009. page.view[3] - data.rect[3] + page.view[1]
  4010. ]);
  4011. CustomStyle.setProp('transform', container,
  4012. 'matrix(' + viewport.transform.join(',') + ')');
  4013. CustomStyle.setProp('transformOrigin', container,
  4014. -rect[0] + 'px ' + -rect[1] + 'px');
  4015. if (data.borderStyle.width > 0) {
  4016. container.style.borderWidth = data.borderStyle.width + 'px';
  4017. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4018. // Underline styles only have a bottom border, so we do not need
  4019. // to adjust for all borders. This yields a similar result as
  4020. // Adobe Acrobat/Reader.
  4021. width = width - 2 * data.borderStyle.width;
  4022. height = height - 2 * data.borderStyle.width;
  4023. }
  4024. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4025. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4026. if (horizontalRadius > 0 || verticalRadius > 0) {
  4027. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4028. CustomStyle.setProp('borderRadius', container, radius);
  4029. }
  4030. switch (data.borderStyle.style) {
  4031. case AnnotationBorderStyleType.SOLID:
  4032. container.style.borderStyle = 'solid';
  4033. break;
  4034. case AnnotationBorderStyleType.DASHED:
  4035. container.style.borderStyle = 'dashed';
  4036. break;
  4037. case AnnotationBorderStyleType.BEVELED:
  4038. warn('Unimplemented border style: beveled');
  4039. break;
  4040. case AnnotationBorderStyleType.INSET:
  4041. warn('Unimplemented border style: inset');
  4042. break;
  4043. case AnnotationBorderStyleType.UNDERLINE:
  4044. container.style.borderBottomStyle = 'solid';
  4045. break;
  4046. default:
  4047. break;
  4048. }
  4049. if (data.color) {
  4050. container.style.borderColor =
  4051. Util.makeCssRgb(data.color[0] | 0,
  4052. data.color[1] | 0,
  4053. data.color[2] | 0);
  4054. } else {
  4055. // Transparent (invisible) border, so do not draw it at all.
  4056. container.style.borderWidth = 0;
  4057. }
  4058. }
  4059. container.style.left = rect[0] + 'px';
  4060. container.style.top = rect[1] + 'px';
  4061. container.style.width = width + 'px';
  4062. container.style.height = height + 'px';
  4063. return container;
  4064. },
  4065. /**
  4066. * Create a popup for the annotation's HTML element. This is used for
  4067. * annotations that do not have a Popup entry in the dictionary, but
  4068. * are of a type that works with popups (such as Highlight annotations).
  4069. *
  4070. * @private
  4071. * @param {HTMLSectionElement} container
  4072. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4073. * @param {Object} data
  4074. * @memberof AnnotationElement
  4075. */
  4076. _createPopup:
  4077. function AnnotationElement_createPopup(container, trigger, data) {
  4078. // If no trigger element is specified, create it.
  4079. if (!trigger) {
  4080. trigger = document.createElement('div');
  4081. trigger.style.height = container.style.height;
  4082. trigger.style.width = container.style.width;
  4083. container.appendChild(trigger);
  4084. }
  4085. var popupElement = new PopupElement({
  4086. container: container,
  4087. trigger: trigger,
  4088. color: data.color,
  4089. title: data.title,
  4090. contents: data.contents,
  4091. hideWrapper: true
  4092. });
  4093. var popup = popupElement.render();
  4094. // Position the popup next to the annotation's container.
  4095. popup.style.left = container.style.width;
  4096. container.appendChild(popup);
  4097. },
  4098. /**
  4099. * Render the annotation's HTML element in the empty container.
  4100. *
  4101. * @public
  4102. * @memberof AnnotationElement
  4103. */
  4104. render: function AnnotationElement_render() {
  4105. throw new Error('Abstract method AnnotationElement.render called');
  4106. }
  4107. };
  4108. return AnnotationElement;
  4109. })();
  4110. /**
  4111. * @class
  4112. * @alias LinkAnnotationElement
  4113. */
  4114. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4115. function LinkAnnotationElement(parameters) {
  4116. AnnotationElement.call(this, parameters, true);
  4117. }
  4118. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4119. /**
  4120. * Render the link annotation's HTML element in the empty container.
  4121. *
  4122. * @public
  4123. * @memberof LinkAnnotationElement
  4124. * @returns {HTMLSectionElement}
  4125. */
  4126. render: function LinkAnnotationElement_render() {
  4127. this.container.className = 'linkAnnotation';
  4128. var link = document.createElement('a');
  4129. addLinkAttributes(link, {
  4130. url: this.data.url,
  4131. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4132. });
  4133. if (!this.data.url) {
  4134. if (this.data.action) {
  4135. this._bindNamedAction(link, this.data.action);
  4136. } else {
  4137. this._bindLink(link, (this.data.dest || null));
  4138. }
  4139. }
  4140. this.container.appendChild(link);
  4141. return this.container;
  4142. },
  4143. /**
  4144. * Bind internal links to the link element.
  4145. *
  4146. * @private
  4147. * @param {Object} link
  4148. * @param {Object} destination
  4149. * @memberof LinkAnnotationElement
  4150. */
  4151. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4152. var self = this;
  4153. link.href = this.linkService.getDestinationHash(destination);
  4154. link.onclick = function() {
  4155. if (destination) {
  4156. self.linkService.navigateTo(destination);
  4157. }
  4158. return false;
  4159. };
  4160. if (destination) {
  4161. link.className = 'internalLink';
  4162. }
  4163. },
  4164. /**
  4165. * Bind named actions to the link element.
  4166. *
  4167. * @private
  4168. * @param {Object} link
  4169. * @param {Object} action
  4170. * @memberof LinkAnnotationElement
  4171. */
  4172. _bindNamedAction:
  4173. function LinkAnnotationElement_bindNamedAction(link, action) {
  4174. var self = this;
  4175. link.href = this.linkService.getAnchorUrl('');
  4176. link.onclick = function() {
  4177. self.linkService.executeNamedAction(action);
  4178. return false;
  4179. };
  4180. link.className = 'internalLink';
  4181. }
  4182. });
  4183. return LinkAnnotationElement;
  4184. })();
  4185. /**
  4186. * @class
  4187. * @alias TextAnnotationElement
  4188. */
  4189. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4190. function TextAnnotationElement(parameters) {
  4191. var isRenderable = !!(parameters.data.hasPopup ||
  4192. parameters.data.title || parameters.data.contents);
  4193. AnnotationElement.call(this, parameters, isRenderable);
  4194. }
  4195. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4196. /**
  4197. * Render the text annotation's HTML element in the empty container.
  4198. *
  4199. * @public
  4200. * @memberof TextAnnotationElement
  4201. * @returns {HTMLSectionElement}
  4202. */
  4203. render: function TextAnnotationElement_render() {
  4204. this.container.className = 'textAnnotation';
  4205. var image = document.createElement('img');
  4206. image.style.height = this.container.style.height;
  4207. image.style.width = this.container.style.width;
  4208. image.src = this.imageResourcesPath + 'annotation-' +
  4209. this.data.name.toLowerCase() + '.svg';
  4210. image.alt = '[{{type}} Annotation]';
  4211. image.dataset.l10nId = 'text_annotation_type';
  4212. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4213. if (!this.data.hasPopup) {
  4214. this._createPopup(this.container, image, this.data);
  4215. }
  4216. this.container.appendChild(image);
  4217. return this.container;
  4218. }
  4219. });
  4220. return TextAnnotationElement;
  4221. })();
  4222. /**
  4223. * @class
  4224. * @alias WidgetAnnotationElement
  4225. */
  4226. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4227. function WidgetAnnotationElement(parameters, isRenderable) {
  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. var isRenderable = parameters.renderInteractiveForms ||
  4254. (!parameters.data.hasAppearance && !!parameters.data.fieldValue);
  4255. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4256. }
  4257. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4258. /**
  4259. * Render the text widget annotation's HTML element in the empty container.
  4260. *
  4261. * @public
  4262. * @memberof TextWidgetAnnotationElement
  4263. * @returns {HTMLSectionElement}
  4264. */
  4265. render: function TextWidgetAnnotationElement_render() {
  4266. this.container.className = 'textWidgetAnnotation';
  4267. var element = null;
  4268. if (this.renderInteractiveForms) {
  4269. // NOTE: We cannot set the values using `element.value` below, since it
  4270. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4271. // from parsing the elements correctly for the reference tests.
  4272. if (this.data.multiLine) {
  4273. element = document.createElement('textarea');
  4274. element.textContent = this.data.fieldValue;
  4275. } else {
  4276. element = document.createElement('input');
  4277. element.type = 'text';
  4278. element.setAttribute('value', this.data.fieldValue);
  4279. }
  4280. element.disabled = this.data.readOnly;
  4281. if (this.data.maxLen !== null) {
  4282. element.maxLength = this.data.maxLen;
  4283. }
  4284. if (this.data.comb) {
  4285. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4286. var combWidth = fieldWidth / this.data.maxLen;
  4287. element.classList.add('comb');
  4288. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4289. }
  4290. } else {
  4291. element = document.createElement('div');
  4292. element.textContent = this.data.fieldValue;
  4293. element.style.verticalAlign = 'middle';
  4294. element.style.display = 'table-cell';
  4295. var font = null;
  4296. if (this.data.fontRefName) {
  4297. font = this.page.commonObjs.getData(this.data.fontRefName);
  4298. }
  4299. this._setTextStyle(element, font);
  4300. }
  4301. if (this.data.textAlignment !== null) {
  4302. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4303. }
  4304. this.container.appendChild(element);
  4305. return this.container;
  4306. },
  4307. /**
  4308. * Apply text styles to the text in the element.
  4309. *
  4310. * @private
  4311. * @param {HTMLDivElement} element
  4312. * @param {Object} font
  4313. * @memberof TextWidgetAnnotationElement
  4314. */
  4315. _setTextStyle:
  4316. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4317. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4318. var style = element.style;
  4319. style.fontSize = this.data.fontSize + 'px';
  4320. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4321. if (!font) {
  4322. return;
  4323. }
  4324. style.fontWeight = (font.black ?
  4325. (font.bold ? '900' : 'bold') :
  4326. (font.bold ? 'bold' : 'normal'));
  4327. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4328. // Use a reasonable default font if the font doesn't specify a fallback.
  4329. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4330. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4331. style.fontFamily = fontFamily + fallbackName;
  4332. }
  4333. });
  4334. return TextWidgetAnnotationElement;
  4335. })();
  4336. /**
  4337. * @class
  4338. * @alias ChoiceWidgetAnnotationElement
  4339. */
  4340. var ChoiceWidgetAnnotationElement = (
  4341. function ChoiceWidgetAnnotationElementClosure() {
  4342. function ChoiceWidgetAnnotationElement(parameters) {
  4343. WidgetAnnotationElement.call(this, parameters,
  4344. parameters.renderInteractiveForms);
  4345. }
  4346. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4347. /**
  4348. * Render the choice widget annotation's HTML element in the empty
  4349. * container.
  4350. *
  4351. * @public
  4352. * @memberof ChoiceWidgetAnnotationElement
  4353. * @returns {HTMLSectionElement}
  4354. */
  4355. render: function ChoiceWidgetAnnotationElement_render() {
  4356. this.container.className = 'choiceWidgetAnnotation';
  4357. var selectElement = document.createElement('select');
  4358. selectElement.disabled = this.data.readOnly;
  4359. if (!this.data.combo) {
  4360. // List boxes have a size and (optionally) multiple selection.
  4361. selectElement.size = this.data.options.length;
  4362. if (this.data.multiSelect) {
  4363. selectElement.multiple = true;
  4364. }
  4365. }
  4366. // Insert the options into the choice field.
  4367. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4368. var option = this.data.options[i];
  4369. var optionElement = document.createElement('option');
  4370. optionElement.textContent = option.displayValue;
  4371. optionElement.value = option.exportValue;
  4372. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4373. optionElement.setAttribute('selected', true);
  4374. }
  4375. selectElement.appendChild(optionElement);
  4376. }
  4377. this.container.appendChild(selectElement);
  4378. return this.container;
  4379. }
  4380. });
  4381. return ChoiceWidgetAnnotationElement;
  4382. })();
  4383. /**
  4384. * @class
  4385. * @alias PopupAnnotationElement
  4386. */
  4387. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4388. function PopupAnnotationElement(parameters) {
  4389. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4390. AnnotationElement.call(this, parameters, isRenderable);
  4391. }
  4392. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4393. /**
  4394. * Render the popup annotation's HTML element in the empty container.
  4395. *
  4396. * @public
  4397. * @memberof PopupAnnotationElement
  4398. * @returns {HTMLSectionElement}
  4399. */
  4400. render: function PopupAnnotationElement_render() {
  4401. this.container.className = 'popupAnnotation';
  4402. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4403. var parentElement = this.layer.querySelector(selector);
  4404. if (!parentElement) {
  4405. return this.container;
  4406. }
  4407. var popup = new PopupElement({
  4408. container: this.container,
  4409. trigger: parentElement,
  4410. color: this.data.color,
  4411. title: this.data.title,
  4412. contents: this.data.contents
  4413. });
  4414. // Position the popup next to the parent annotation's container.
  4415. // PDF viewers ignore a popup annotation's rectangle.
  4416. var parentLeft = parseFloat(parentElement.style.left);
  4417. var parentWidth = parseFloat(parentElement.style.width);
  4418. CustomStyle.setProp('transformOrigin', this.container,
  4419. -(parentLeft + parentWidth) + 'px -' +
  4420. parentElement.style.top);
  4421. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4422. this.container.appendChild(popup.render());
  4423. return this.container;
  4424. }
  4425. });
  4426. return PopupAnnotationElement;
  4427. })();
  4428. /**
  4429. * @class
  4430. * @alias PopupElement
  4431. */
  4432. var PopupElement = (function PopupElementClosure() {
  4433. var BACKGROUND_ENLIGHT = 0.7;
  4434. function PopupElement(parameters) {
  4435. this.container = parameters.container;
  4436. this.trigger = parameters.trigger;
  4437. this.color = parameters.color;
  4438. this.title = parameters.title;
  4439. this.contents = parameters.contents;
  4440. this.hideWrapper = parameters.hideWrapper || false;
  4441. this.pinned = false;
  4442. }
  4443. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4444. /**
  4445. * Render the popup's HTML element.
  4446. *
  4447. * @public
  4448. * @memberof PopupElement
  4449. * @returns {HTMLSectionElement}
  4450. */
  4451. render: function PopupElement_render() {
  4452. var wrapper = document.createElement('div');
  4453. wrapper.className = 'popupWrapper';
  4454. // For Popup annotations we hide the entire section because it contains
  4455. // only the popup. However, for Text annotations without a separate Popup
  4456. // annotation, we cannot hide the entire container as the image would
  4457. // disappear too. In that special case, hiding the wrapper suffices.
  4458. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4459. this.hideElement.setAttribute('hidden', true);
  4460. var popup = document.createElement('div');
  4461. popup.className = 'popup';
  4462. var color = this.color;
  4463. if (color) {
  4464. // Enlighten the color.
  4465. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4466. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4467. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4468. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4469. }
  4470. var contents = this._formatContents(this.contents);
  4471. var title = document.createElement('h1');
  4472. title.textContent = this.title;
  4473. // Attach the event listeners to the trigger element.
  4474. this.trigger.addEventListener('click', this._toggle.bind(this));
  4475. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4476. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4477. popup.addEventListener('click', this._hide.bind(this, true));
  4478. popup.appendChild(title);
  4479. popup.appendChild(contents);
  4480. wrapper.appendChild(popup);
  4481. return wrapper;
  4482. },
  4483. /**
  4484. * Format the contents of the popup by adding newlines where necessary.
  4485. *
  4486. * @private
  4487. * @param {string} contents
  4488. * @memberof PopupElement
  4489. * @returns {HTMLParagraphElement}
  4490. */
  4491. _formatContents: function PopupElement_formatContents(contents) {
  4492. var p = document.createElement('p');
  4493. var lines = contents.split(/(?:\r\n?|\n)/);
  4494. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4495. var line = lines[i];
  4496. p.appendChild(document.createTextNode(line));
  4497. if (i < (ii - 1)) {
  4498. p.appendChild(document.createElement('br'));
  4499. }
  4500. }
  4501. return p;
  4502. },
  4503. /**
  4504. * Toggle the visibility of the popup.
  4505. *
  4506. * @private
  4507. * @memberof PopupElement
  4508. */
  4509. _toggle: function PopupElement_toggle() {
  4510. if (this.pinned) {
  4511. this._hide(true);
  4512. } else {
  4513. this._show(true);
  4514. }
  4515. },
  4516. /**
  4517. * Show the popup.
  4518. *
  4519. * @private
  4520. * @param {boolean} pin
  4521. * @memberof PopupElement
  4522. */
  4523. _show: function PopupElement_show(pin) {
  4524. if (pin) {
  4525. this.pinned = true;
  4526. }
  4527. if (this.hideElement.hasAttribute('hidden')) {
  4528. this.hideElement.removeAttribute('hidden');
  4529. this.container.style.zIndex += 1;
  4530. }
  4531. },
  4532. /**
  4533. * Hide the popup.
  4534. *
  4535. * @private
  4536. * @param {boolean} unpin
  4537. * @memberof PopupElement
  4538. */
  4539. _hide: function PopupElement_hide(unpin) {
  4540. if (unpin) {
  4541. this.pinned = false;
  4542. }
  4543. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4544. this.hideElement.setAttribute('hidden', true);
  4545. this.container.style.zIndex -= 1;
  4546. }
  4547. }
  4548. };
  4549. return PopupElement;
  4550. })();
  4551. /**
  4552. * @class
  4553. * @alias HighlightAnnotationElement
  4554. */
  4555. var HighlightAnnotationElement = (
  4556. function HighlightAnnotationElementClosure() {
  4557. function HighlightAnnotationElement(parameters) {
  4558. var isRenderable = !!(parameters.data.hasPopup ||
  4559. parameters.data.title || parameters.data.contents);
  4560. AnnotationElement.call(this, parameters, isRenderable);
  4561. }
  4562. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4563. /**
  4564. * Render the highlight annotation's HTML element in the empty container.
  4565. *
  4566. * @public
  4567. * @memberof HighlightAnnotationElement
  4568. * @returns {HTMLSectionElement}
  4569. */
  4570. render: function HighlightAnnotationElement_render() {
  4571. this.container.className = 'highlightAnnotation';
  4572. if (!this.data.hasPopup) {
  4573. this._createPopup(this.container, null, this.data);
  4574. }
  4575. return this.container;
  4576. }
  4577. });
  4578. return HighlightAnnotationElement;
  4579. })();
  4580. /**
  4581. * @class
  4582. * @alias UnderlineAnnotationElement
  4583. */
  4584. var UnderlineAnnotationElement = (
  4585. function UnderlineAnnotationElementClosure() {
  4586. function UnderlineAnnotationElement(parameters) {
  4587. var isRenderable = !!(parameters.data.hasPopup ||
  4588. parameters.data.title || parameters.data.contents);
  4589. AnnotationElement.call(this, parameters, isRenderable);
  4590. }
  4591. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4592. /**
  4593. * Render the underline annotation's HTML element in the empty container.
  4594. *
  4595. * @public
  4596. * @memberof UnderlineAnnotationElement
  4597. * @returns {HTMLSectionElement}
  4598. */
  4599. render: function UnderlineAnnotationElement_render() {
  4600. this.container.className = 'underlineAnnotation';
  4601. if (!this.data.hasPopup) {
  4602. this._createPopup(this.container, null, this.data);
  4603. }
  4604. return this.container;
  4605. }
  4606. });
  4607. return UnderlineAnnotationElement;
  4608. })();
  4609. /**
  4610. * @class
  4611. * @alias SquigglyAnnotationElement
  4612. */
  4613. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4614. function SquigglyAnnotationElement(parameters) {
  4615. var isRenderable = !!(parameters.data.hasPopup ||
  4616. parameters.data.title || parameters.data.contents);
  4617. AnnotationElement.call(this, parameters, isRenderable);
  4618. }
  4619. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4620. /**
  4621. * Render the squiggly annotation's HTML element in the empty container.
  4622. *
  4623. * @public
  4624. * @memberof SquigglyAnnotationElement
  4625. * @returns {HTMLSectionElement}
  4626. */
  4627. render: function SquigglyAnnotationElement_render() {
  4628. this.container.className = 'squigglyAnnotation';
  4629. if (!this.data.hasPopup) {
  4630. this._createPopup(this.container, null, this.data);
  4631. }
  4632. return this.container;
  4633. }
  4634. });
  4635. return SquigglyAnnotationElement;
  4636. })();
  4637. /**
  4638. * @class
  4639. * @alias StrikeOutAnnotationElement
  4640. */
  4641. var StrikeOutAnnotationElement = (
  4642. function StrikeOutAnnotationElementClosure() {
  4643. function StrikeOutAnnotationElement(parameters) {
  4644. var isRenderable = !!(parameters.data.hasPopup ||
  4645. parameters.data.title || parameters.data.contents);
  4646. AnnotationElement.call(this, parameters, isRenderable);
  4647. }
  4648. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4649. /**
  4650. * Render the strikeout annotation's HTML element in the empty container.
  4651. *
  4652. * @public
  4653. * @memberof StrikeOutAnnotationElement
  4654. * @returns {HTMLSectionElement}
  4655. */
  4656. render: function StrikeOutAnnotationElement_render() {
  4657. this.container.className = 'strikeoutAnnotation';
  4658. if (!this.data.hasPopup) {
  4659. this._createPopup(this.container, null, this.data);
  4660. }
  4661. return this.container;
  4662. }
  4663. });
  4664. return StrikeOutAnnotationElement;
  4665. })();
  4666. /**
  4667. * @class
  4668. * @alias FileAttachmentAnnotationElement
  4669. */
  4670. var FileAttachmentAnnotationElement = (
  4671. function FileAttachmentAnnotationElementClosure() {
  4672. function FileAttachmentAnnotationElement(parameters) {
  4673. AnnotationElement.call(this, parameters, true);
  4674. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4675. this.content = parameters.data.file.content;
  4676. }
  4677. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4678. /**
  4679. * Render the file attachment annotation's HTML element in the empty
  4680. * container.
  4681. *
  4682. * @public
  4683. * @memberof FileAttachmentAnnotationElement
  4684. * @returns {HTMLSectionElement}
  4685. */
  4686. render: function FileAttachmentAnnotationElement_render() {
  4687. this.container.className = 'fileAttachmentAnnotation';
  4688. var trigger = document.createElement('div');
  4689. trigger.style.height = this.container.style.height;
  4690. trigger.style.width = this.container.style.width;
  4691. trigger.addEventListener('dblclick', this._download.bind(this));
  4692. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4693. this._createPopup(this.container, trigger, this.data);
  4694. }
  4695. this.container.appendChild(trigger);
  4696. return this.container;
  4697. },
  4698. /**
  4699. * Download the file attachment associated with this annotation.
  4700. *
  4701. * @private
  4702. * @memberof FileAttachmentAnnotationElement
  4703. */
  4704. _download: function FileAttachmentAnnotationElement_download() {
  4705. if (!this.downloadManager) {
  4706. warn('Download cannot be started due to unavailable download manager');
  4707. return;
  4708. }
  4709. this.downloadManager.downloadData(this.content, this.filename, '');
  4710. }
  4711. });
  4712. return FileAttachmentAnnotationElement;
  4713. })();
  4714. /**
  4715. * @typedef {Object} AnnotationLayerParameters
  4716. * @property {PageViewport} viewport
  4717. * @property {HTMLDivElement} div
  4718. * @property {Array} annotations
  4719. * @property {PDFPage} page
  4720. * @property {IPDFLinkService} linkService
  4721. * @property {string} imageResourcesPath
  4722. * @property {boolean} renderInteractiveForms
  4723. */
  4724. /**
  4725. * @class
  4726. * @alias AnnotationLayer
  4727. */
  4728. var AnnotationLayer = (function AnnotationLayerClosure() {
  4729. return {
  4730. /**
  4731. * Render a new annotation layer with all annotation elements.
  4732. *
  4733. * @public
  4734. * @param {AnnotationLayerParameters} parameters
  4735. * @memberof AnnotationLayer
  4736. */
  4737. render: function AnnotationLayer_render(parameters) {
  4738. var annotationElementFactory = new AnnotationElementFactory();
  4739. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4740. var data = parameters.annotations[i];
  4741. if (!data) {
  4742. continue;
  4743. }
  4744. var properties = {
  4745. data: data,
  4746. layer: parameters.div,
  4747. page: parameters.page,
  4748. viewport: parameters.viewport,
  4749. linkService: parameters.linkService,
  4750. downloadManager: parameters.downloadManager,
  4751. imageResourcesPath: parameters.imageResourcesPath ||
  4752. getDefaultSetting('imageResourcesPath'),
  4753. renderInteractiveForms: parameters.renderInteractiveForms || false,
  4754. };
  4755. var element = annotationElementFactory.create(properties);
  4756. if (element.isRenderable) {
  4757. parameters.div.appendChild(element.render());
  4758. }
  4759. }
  4760. },
  4761. /**
  4762. * Update the annotation elements on existing annotation layer.
  4763. *
  4764. * @public
  4765. * @param {AnnotationLayerParameters} parameters
  4766. * @memberof AnnotationLayer
  4767. */
  4768. update: function AnnotationLayer_update(parameters) {
  4769. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4770. var data = parameters.annotations[i];
  4771. var element = parameters.div.querySelector(
  4772. '[data-annotation-id="' + data.id + '"]');
  4773. if (element) {
  4774. CustomStyle.setProp('transform', element,
  4775. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4776. }
  4777. }
  4778. parameters.div.removeAttribute('hidden');
  4779. }
  4780. };
  4781. })();
  4782. exports.AnnotationLayer = AnnotationLayer;
  4783. }));
  4784. (function (root, factory) {
  4785. {
  4786. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4787. root.pdfjsDisplayDOMUtils);
  4788. }
  4789. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4790. var Util = sharedUtil.Util;
  4791. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4792. var CustomStyle = displayDOMUtils.CustomStyle;
  4793. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4794. /**
  4795. * Text layer render parameters.
  4796. *
  4797. * @typedef {Object} TextLayerRenderParameters
  4798. * @property {TextContent} textContent - Text content to render (the object is
  4799. * returned by the page's getTextContent() method).
  4800. * @property {HTMLElement} container - HTML element that will contain text runs.
  4801. * @property {PageViewport} viewport - The target viewport to properly
  4802. * layout the text runs.
  4803. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4804. * the text items of the textContent input. This is output and shall be
  4805. * initially be set to empty array.
  4806. * @property {number} timeout - (optional) Delay in milliseconds before
  4807. * rendering of the text runs occurs.
  4808. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4809. * text selection enhancement.
  4810. */
  4811. var renderTextLayer = (function renderTextLayerClosure() {
  4812. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4813. var NonWhitespaceRegexp = /\S/;
  4814. function isAllWhitespace(str) {
  4815. return !NonWhitespaceRegexp.test(str);
  4816. }
  4817. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  4818. // creating many intermediate strings when building their 'style' properties.
  4819. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0,
  4820. 'px; font-family: ', '', ';'];
  4821. function appendText(task, geom, styles) {
  4822. // Initialize all used properties to keep the caches monomorphic.
  4823. var textDiv = document.createElement('div');
  4824. var textDivProperties = {
  4825. style: null,
  4826. angle: 0,
  4827. canvasWidth: 0,
  4828. isWhitespace: false,
  4829. originalTransform: null,
  4830. paddingBottom: 0,
  4831. paddingLeft: 0,
  4832. paddingRight: 0,
  4833. paddingTop: 0,
  4834. scale: 1,
  4835. };
  4836. task._textDivs.push(textDiv);
  4837. if (isAllWhitespace(geom.str)) {
  4838. textDivProperties.isWhitespace = true;
  4839. task._textDivProperties.set(textDiv, textDivProperties);
  4840. return;
  4841. }
  4842. var tx = Util.transform(task._viewport.transform, geom.transform);
  4843. var angle = Math.atan2(tx[1], tx[0]);
  4844. var style = styles[geom.fontName];
  4845. if (style.vertical) {
  4846. angle += Math.PI / 2;
  4847. }
  4848. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4849. var fontAscent = fontHeight;
  4850. if (style.ascent) {
  4851. fontAscent = style.ascent * fontAscent;
  4852. } else if (style.descent) {
  4853. fontAscent = (1 + style.descent) * fontAscent;
  4854. }
  4855. var left;
  4856. var top;
  4857. if (angle === 0) {
  4858. left = tx[4];
  4859. top = tx[5] - fontAscent;
  4860. } else {
  4861. left = tx[4] + (fontAscent * Math.sin(angle));
  4862. top = tx[5] - (fontAscent * Math.cos(angle));
  4863. }
  4864. styleBuf[1] = left;
  4865. styleBuf[3] = top;
  4866. styleBuf[5] = fontHeight;
  4867. styleBuf[7] = style.fontFamily;
  4868. textDivProperties.style = styleBuf.join('');
  4869. textDiv.setAttribute('style', textDivProperties.style);
  4870. textDiv.textContent = geom.str;
  4871. // |fontName| is only used by the Font Inspector. This test will succeed
  4872. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4873. // not worth the effort to do a more accurate test. We only use `dataset`
  4874. // here to make the font name available for the debugger.
  4875. if (getDefaultSetting('pdfBug')) {
  4876. textDiv.dataset.fontName = geom.fontName;
  4877. }
  4878. if (angle !== 0) {
  4879. textDivProperties.angle = angle * (180 / Math.PI);
  4880. }
  4881. // We don't bother scaling single-char text divs, because it has very
  4882. // little effect on text highlighting. This makes scrolling on docs with
  4883. // lots of such divs a lot faster.
  4884. if (geom.str.length > 1) {
  4885. if (style.vertical) {
  4886. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4887. } else {
  4888. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4889. }
  4890. }
  4891. task._textDivProperties.set(textDiv, textDivProperties);
  4892. if (task._enhanceTextSelection) {
  4893. var angleCos = 1, angleSin = 0;
  4894. if (angle !== 0) {
  4895. angleCos = Math.cos(angle);
  4896. angleSin = Math.sin(angle);
  4897. }
  4898. var divWidth = (style.vertical ? geom.height : geom.width) *
  4899. task._viewport.scale;
  4900. var divHeight = fontHeight;
  4901. var m, b;
  4902. if (angle !== 0) {
  4903. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4904. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4905. } else {
  4906. b = [left, top, left + divWidth, top + divHeight];
  4907. }
  4908. task._bounds.push({
  4909. left: b[0],
  4910. top: b[1],
  4911. right: b[2],
  4912. bottom: b[3],
  4913. div: textDiv,
  4914. size: [divWidth, divHeight],
  4915. m: m
  4916. });
  4917. }
  4918. }
  4919. function render(task) {
  4920. if (task._canceled) {
  4921. return;
  4922. }
  4923. var textLayerFrag = task._container;
  4924. var textDivs = task._textDivs;
  4925. var capability = task._capability;
  4926. var textDivsLength = textDivs.length;
  4927. // No point in rendering many divs as it would make the browser
  4928. // unusable even after the divs are rendered.
  4929. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4930. task._renderingDone = true;
  4931. capability.resolve();
  4932. return;
  4933. }
  4934. var canvas = document.createElement('canvas');
  4935. canvas.mozOpaque = true;
  4936. var ctx = canvas.getContext('2d', {alpha: false});
  4937. var lastFontSize;
  4938. var lastFontFamily;
  4939. for (var i = 0; i < textDivsLength; i++) {
  4940. var textDiv = textDivs[i];
  4941. var textDivProperties = task._textDivProperties.get(textDiv);
  4942. if (textDivProperties.isWhitespace) {
  4943. continue;
  4944. }
  4945. var fontSize = textDiv.style.fontSize;
  4946. var fontFamily = textDiv.style.fontFamily;
  4947. // Only build font string and set to context if different from last.
  4948. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4949. ctx.font = fontSize + ' ' + fontFamily;
  4950. lastFontSize = fontSize;
  4951. lastFontFamily = fontFamily;
  4952. }
  4953. var width = ctx.measureText(textDiv.textContent).width;
  4954. textLayerFrag.appendChild(textDiv);
  4955. var transform = '';
  4956. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4957. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4958. transform = 'scaleX(' + textDivProperties.scale + ')';
  4959. }
  4960. if (textDivProperties.angle !== 0) {
  4961. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4962. }
  4963. if (transform !== '') {
  4964. textDivProperties.originalTransform = transform;
  4965. CustomStyle.setProp('transform', textDiv, transform);
  4966. }
  4967. task._textDivProperties.set(textDiv, textDivProperties);
  4968. }
  4969. task._renderingDone = true;
  4970. capability.resolve();
  4971. }
  4972. function expand(task) {
  4973. var bounds = task._bounds;
  4974. var viewport = task._viewport;
  4975. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4976. for (var i = 0; i < expanded.length; i++) {
  4977. var div = bounds[i].div;
  4978. var divProperties = task._textDivProperties.get(div);
  4979. if (divProperties.angle === 0) {
  4980. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4981. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4982. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4983. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4984. task._textDivProperties.set(div, divProperties);
  4985. continue;
  4986. }
  4987. // Box is rotated -- trying to find padding so rotated div will not
  4988. // exceed its expanded bounds.
  4989. var e = expanded[i], b = bounds[i];
  4990. var m = b.m, c = m[0], s = m[1];
  4991. // Finding intersections with expanded box.
  4992. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4993. var ts = new Float64Array(64);
  4994. points.forEach(function (p, i) {
  4995. var t = Util.applyTransform(p, m);
  4996. ts[i + 0] = c && (e.left - t[0]) / c;
  4997. ts[i + 4] = s && (e.top - t[1]) / s;
  4998. ts[i + 8] = c && (e.right - t[0]) / c;
  4999. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5000. ts[i + 16] = s && (e.left - t[0]) / -s;
  5001. ts[i + 20] = c && (e.top - t[1]) / c;
  5002. ts[i + 24] = s && (e.right - t[0]) / -s;
  5003. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5004. ts[i + 32] = c && (e.left - t[0]) / -c;
  5005. ts[i + 36] = s && (e.top - t[1]) / -s;
  5006. ts[i + 40] = c && (e.right - t[0]) / -c;
  5007. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5008. ts[i + 48] = s && (e.left - t[0]) / s;
  5009. ts[i + 52] = c && (e.top - t[1]) / -c;
  5010. ts[i + 56] = s && (e.right - t[0]) / s;
  5011. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5012. });
  5013. var findPositiveMin = function (ts, offset, count) {
  5014. var result = 0;
  5015. for (var i = 0; i < count; i++) {
  5016. var t = ts[offset++];
  5017. if (t > 0) {
  5018. result = result ? Math.min(t, result) : t;
  5019. }
  5020. }
  5021. return result;
  5022. };
  5023. // Not based on math, but to simplify calculations, using cos and sin
  5024. // absolute values to not exceed the box (it can but insignificantly).
  5025. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5026. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5027. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5028. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5029. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5030. task._textDivProperties.set(div, divProperties);
  5031. }
  5032. }
  5033. function expandBounds(width, height, boxes) {
  5034. var bounds = boxes.map(function (box, i) {
  5035. return {
  5036. x1: box.left,
  5037. y1: box.top,
  5038. x2: box.right,
  5039. y2: box.bottom,
  5040. index: i,
  5041. x1New: undefined,
  5042. x2New: undefined
  5043. };
  5044. });
  5045. expandBoundsLTR(width, bounds);
  5046. var expanded = new Array(boxes.length);
  5047. bounds.forEach(function (b) {
  5048. var i = b.index;
  5049. expanded[i] = {
  5050. left: b.x1New,
  5051. top: 0,
  5052. right: b.x2New,
  5053. bottom: 0
  5054. };
  5055. });
  5056. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5057. // array and objects.
  5058. boxes.map(function (box, i) {
  5059. var e = expanded[i], b = bounds[i];
  5060. b.x1 = box.top;
  5061. b.y1 = width - e.right;
  5062. b.x2 = box.bottom;
  5063. b.y2 = width - e.left;
  5064. b.index = i;
  5065. b.x1New = undefined;
  5066. b.x2New = undefined;
  5067. });
  5068. expandBoundsLTR(height, bounds);
  5069. bounds.forEach(function (b) {
  5070. var i = b.index;
  5071. expanded[i].top = b.x1New;
  5072. expanded[i].bottom = b.x2New;
  5073. });
  5074. return expanded;
  5075. }
  5076. function expandBoundsLTR(width, bounds) {
  5077. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5078. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  5079. // First we see on the horizon is a fake boundary.
  5080. var fakeBoundary = {
  5081. x1: -Infinity,
  5082. y1: -Infinity,
  5083. x2: 0,
  5084. y2: Infinity,
  5085. index: -1,
  5086. x1New: 0,
  5087. x2New: 0
  5088. };
  5089. var horizon = [{
  5090. start: -Infinity,
  5091. end: Infinity,
  5092. boundary: fakeBoundary
  5093. }];
  5094. bounds.forEach(function (boundary) {
  5095. // Searching for the affected part of horizon.
  5096. // TODO red-black tree or simple binary search
  5097. var i = 0;
  5098. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5099. i++;
  5100. }
  5101. var j = horizon.length - 1;
  5102. while(j >= 0 && horizon[j].start >= boundary.y2) {
  5103. j--;
  5104. }
  5105. var horizonPart, affectedBoundary;
  5106. var q, k, maxXNew = -Infinity;
  5107. for (q = i; q <= j; q++) {
  5108. horizonPart = horizon[q];
  5109. affectedBoundary = horizonPart.boundary;
  5110. var xNew;
  5111. if (affectedBoundary.x2 > boundary.x1) {
  5112. // In the middle of the previous element, new x shall be at the
  5113. // boundary start. Extending if further if the affected bondary
  5114. // placed on top of the current one.
  5115. xNew = affectedBoundary.index > boundary.index ?
  5116. affectedBoundary.x1New : boundary.x1;
  5117. } else if (affectedBoundary.x2New === undefined) {
  5118. // We have some space in between, new x in middle will be a fair
  5119. // choice.
  5120. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5121. } else {
  5122. // Affected boundary has x2new set, using it as new x.
  5123. xNew = affectedBoundary.x2New;
  5124. }
  5125. if (xNew > maxXNew) {
  5126. maxXNew = xNew;
  5127. }
  5128. }
  5129. // Set new x1 for current boundary.
  5130. boundary.x1New = maxXNew;
  5131. // Adjusts new x2 for the affected boundaries.
  5132. for (q = i; q <= j; q++) {
  5133. horizonPart = horizon[q];
  5134. affectedBoundary = horizonPart.boundary;
  5135. if (affectedBoundary.x2New === undefined) {
  5136. // Was not set yet, choosing new x if possible.
  5137. if (affectedBoundary.x2 > boundary.x1) {
  5138. // Current and affected boundaries intersect. If affected boundary
  5139. // is placed on top of the current, shrinking the affected.
  5140. if (affectedBoundary.index > boundary.index) {
  5141. affectedBoundary.x2New = affectedBoundary.x2;
  5142. }
  5143. } else {
  5144. affectedBoundary.x2New = maxXNew;
  5145. }
  5146. } else if (affectedBoundary.x2New > maxXNew) {
  5147. // Affected boundary is touching new x, pushing it back.
  5148. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5149. }
  5150. }
  5151. // Fixing the horizon.
  5152. var changedHorizon = [], lastBoundary = null;
  5153. for (q = i; q <= j; q++) {
  5154. horizonPart = horizon[q];
  5155. affectedBoundary = horizonPart.boundary;
  5156. // Checking which boundary will be visible.
  5157. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5158. affectedBoundary : boundary;
  5159. if (lastBoundary === useBoundary) {
  5160. // Merging with previous.
  5161. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5162. } else {
  5163. changedHorizon.push({
  5164. start: horizonPart.start,
  5165. end: horizonPart.end,
  5166. boundary: useBoundary
  5167. });
  5168. lastBoundary = useBoundary;
  5169. }
  5170. }
  5171. if (horizon[i].start < boundary.y1) {
  5172. changedHorizon[0].start = boundary.y1;
  5173. changedHorizon.unshift({
  5174. start: horizon[i].start,
  5175. end: boundary.y1,
  5176. boundary: horizon[i].boundary
  5177. });
  5178. }
  5179. if (boundary.y2 < horizon[j].end) {
  5180. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5181. changedHorizon.push({
  5182. start: boundary.y2,
  5183. end: horizon[j].end,
  5184. boundary: horizon[j].boundary
  5185. });
  5186. }
  5187. // Set x2 new of boundary that is no longer visible (see overlapping case
  5188. // above).
  5189. // TODO more efficient, e.g. via reference counting.
  5190. for (q = i; q <= j; q++) {
  5191. horizonPart = horizon[q];
  5192. affectedBoundary = horizonPart.boundary;
  5193. if (affectedBoundary.x2New !== undefined) {
  5194. continue;
  5195. }
  5196. var used = false;
  5197. for (k = i - 1; !used && k >= 0 &&
  5198. horizon[k].start >= affectedBoundary.y1; k--) {
  5199. used = horizon[k].boundary === affectedBoundary;
  5200. }
  5201. for (k = j + 1; !used && k < horizon.length &&
  5202. horizon[k].end <= affectedBoundary.y2; k++) {
  5203. used = horizon[k].boundary === affectedBoundary;
  5204. }
  5205. for (k = 0; !used && k < changedHorizon.length; k++) {
  5206. used = changedHorizon[k].boundary === affectedBoundary;
  5207. }
  5208. if (!used) {
  5209. affectedBoundary.x2New = maxXNew;
  5210. }
  5211. }
  5212. Array.prototype.splice.apply(horizon,
  5213. [i, j - i + 1].concat(changedHorizon));
  5214. });
  5215. // Set new x2 for all unset boundaries.
  5216. horizon.forEach(function (horizonPart) {
  5217. var affectedBoundary = horizonPart.boundary;
  5218. if (affectedBoundary.x2New === undefined) {
  5219. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5220. }
  5221. });
  5222. }
  5223. /**
  5224. * Text layer rendering task.
  5225. *
  5226. * @param {TextContent} textContent
  5227. * @param {HTMLElement} container
  5228. * @param {PageViewport} viewport
  5229. * @param {Array} textDivs
  5230. * @param {boolean} enhanceTextSelection
  5231. * @private
  5232. */
  5233. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5234. enhanceTextSelection) {
  5235. this._textContent = textContent;
  5236. this._container = container;
  5237. this._viewport = viewport;
  5238. this._textDivs = textDivs || [];
  5239. this._textDivProperties = new WeakMap();
  5240. this._renderingDone = false;
  5241. this._canceled = false;
  5242. this._capability = createPromiseCapability();
  5243. this._renderTimer = null;
  5244. this._bounds = [];
  5245. this._enhanceTextSelection = !!enhanceTextSelection;
  5246. }
  5247. TextLayerRenderTask.prototype = {
  5248. get promise() {
  5249. return this._capability.promise;
  5250. },
  5251. cancel: function TextLayer_cancel() {
  5252. this._canceled = true;
  5253. if (this._renderTimer !== null) {
  5254. clearTimeout(this._renderTimer);
  5255. this._renderTimer = null;
  5256. }
  5257. this._capability.reject('canceled');
  5258. },
  5259. _render: function TextLayer_render(timeout) {
  5260. var textItems = this._textContent.items;
  5261. var textStyles = this._textContent.styles;
  5262. for (var i = 0, len = textItems.length; i < len; i++) {
  5263. appendText(this, textItems[i], textStyles);
  5264. }
  5265. if (!timeout) { // Render right away
  5266. render(this);
  5267. } else { // Schedule
  5268. var self = this;
  5269. this._renderTimer = setTimeout(function() {
  5270. render(self);
  5271. self._renderTimer = null;
  5272. }, timeout);
  5273. }
  5274. },
  5275. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5276. if (!this._enhanceTextSelection || !this._renderingDone) {
  5277. return;
  5278. }
  5279. if (this._bounds !== null) {
  5280. expand(this);
  5281. this._bounds = null;
  5282. }
  5283. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5284. var div = this._textDivs[i];
  5285. var divProperties = this._textDivProperties.get(div);
  5286. if (divProperties.isWhitespace) {
  5287. continue;
  5288. }
  5289. if (expandDivs) {
  5290. var transform = '', padding = '';
  5291. if (divProperties.scale !== 1) {
  5292. transform = 'scaleX(' + divProperties.scale + ')';
  5293. }
  5294. if (divProperties.angle !== 0) {
  5295. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5296. }
  5297. if (divProperties.paddingLeft !== 0) {
  5298. padding += ' padding-left: ' +
  5299. (divProperties.paddingLeft / divProperties.scale) + 'px;';
  5300. transform += ' translateX(' +
  5301. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5302. }
  5303. if (divProperties.paddingTop !== 0) {
  5304. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5305. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5306. }
  5307. if (divProperties.paddingRight !== 0) {
  5308. padding += ' padding-right: ' +
  5309. (divProperties.paddingRight / divProperties.scale) + 'px;';
  5310. }
  5311. if (divProperties.paddingBottom !== 0) {
  5312. padding += ' padding-bottom: ' +
  5313. divProperties.paddingBottom + 'px;';
  5314. }
  5315. if (padding !== '') {
  5316. div.setAttribute('style', divProperties.style + padding);
  5317. }
  5318. if (transform !== '') {
  5319. CustomStyle.setProp('transform', div, transform);
  5320. }
  5321. } else {
  5322. div.style.padding = 0;
  5323. CustomStyle.setProp('transform', div,
  5324. divProperties.originalTransform || '');
  5325. }
  5326. }
  5327. },
  5328. };
  5329. /**
  5330. * Starts rendering of the text layer.
  5331. *
  5332. * @param {TextLayerRenderParameters} renderParameters
  5333. * @returns {TextLayerRenderTask}
  5334. */
  5335. function renderTextLayer(renderParameters) {
  5336. var task = new TextLayerRenderTask(renderParameters.textContent,
  5337. renderParameters.container,
  5338. renderParameters.viewport,
  5339. renderParameters.textDivs,
  5340. renderParameters.enhanceTextSelection);
  5341. task._render(renderParameters.timeout);
  5342. return task;
  5343. }
  5344. return renderTextLayer;
  5345. })();
  5346. exports.renderTextLayer = renderTextLayer;
  5347. }));
  5348. (function (root, factory) {
  5349. {
  5350. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5351. root.pdfjsDisplayDOMUtils);
  5352. }
  5353. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5354. var shadow = sharedUtil.shadow;
  5355. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5356. var WebGLUtils = (function WebGLUtilsClosure() {
  5357. function loadShader(gl, code, shaderType) {
  5358. var shader = gl.createShader(shaderType);
  5359. gl.shaderSource(shader, code);
  5360. gl.compileShader(shader);
  5361. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5362. if (!compiled) {
  5363. var errorMsg = gl.getShaderInfoLog(shader);
  5364. throw new Error('Error during shader compilation: ' + errorMsg);
  5365. }
  5366. return shader;
  5367. }
  5368. function createVertexShader(gl, code) {
  5369. return loadShader(gl, code, gl.VERTEX_SHADER);
  5370. }
  5371. function createFragmentShader(gl, code) {
  5372. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5373. }
  5374. function createProgram(gl, shaders) {
  5375. var program = gl.createProgram();
  5376. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5377. gl.attachShader(program, shaders[i]);
  5378. }
  5379. gl.linkProgram(program);
  5380. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5381. if (!linked) {
  5382. var errorMsg = gl.getProgramInfoLog(program);
  5383. throw new Error('Error during program linking: ' + errorMsg);
  5384. }
  5385. return program;
  5386. }
  5387. function createTexture(gl, image, textureId) {
  5388. gl.activeTexture(textureId);
  5389. var texture = gl.createTexture();
  5390. gl.bindTexture(gl.TEXTURE_2D, texture);
  5391. // Set the parameters so we can render any size image.
  5392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5396. // Upload the image into the texture.
  5397. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5398. return texture;
  5399. }
  5400. var currentGL, currentCanvas;
  5401. function generateGL() {
  5402. if (currentGL) {
  5403. return;
  5404. }
  5405. currentCanvas = document.createElement('canvas');
  5406. currentGL = currentCanvas.getContext('webgl',
  5407. { premultipliedalpha: false });
  5408. }
  5409. var smaskVertexShaderCode = '\
  5410. attribute vec2 a_position; \
  5411. attribute vec2 a_texCoord; \
  5412. \
  5413. uniform vec2 u_resolution; \
  5414. \
  5415. varying vec2 v_texCoord; \
  5416. \
  5417. void main() { \
  5418. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5419. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5420. \
  5421. v_texCoord = a_texCoord; \
  5422. } ';
  5423. var smaskFragmentShaderCode = '\
  5424. precision mediump float; \
  5425. \
  5426. uniform vec4 u_backdrop; \
  5427. uniform int u_subtype; \
  5428. uniform sampler2D u_image; \
  5429. uniform sampler2D u_mask; \
  5430. \
  5431. varying vec2 v_texCoord; \
  5432. \
  5433. void main() { \
  5434. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5435. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5436. if (u_backdrop.a > 0.0) { \
  5437. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5438. u_backdrop.rgb * (1.0 - maskColor.a); \
  5439. } \
  5440. float lum; \
  5441. if (u_subtype == 0) { \
  5442. lum = maskColor.a; \
  5443. } else { \
  5444. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5445. maskColor.b * 0.11; \
  5446. } \
  5447. imageColor.a *= lum; \
  5448. imageColor.rgb *= imageColor.a; \
  5449. gl_FragColor = imageColor; \
  5450. } ';
  5451. var smaskCache = null;
  5452. function initSmaskGL() {
  5453. var canvas, gl;
  5454. generateGL();
  5455. canvas = currentCanvas;
  5456. currentCanvas = null;
  5457. gl = currentGL;
  5458. currentGL = null;
  5459. // setup a GLSL program
  5460. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5461. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5462. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5463. gl.useProgram(program);
  5464. var cache = {};
  5465. cache.gl = gl;
  5466. cache.canvas = canvas;
  5467. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5468. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5469. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5470. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5471. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5472. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5473. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5474. // provide texture coordinates for the rectangle.
  5475. var texCoordBuffer = gl.createBuffer();
  5476. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5477. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5478. 0.0, 0.0,
  5479. 1.0, 0.0,
  5480. 0.0, 1.0,
  5481. 0.0, 1.0,
  5482. 1.0, 0.0,
  5483. 1.0, 1.0]), gl.STATIC_DRAW);
  5484. gl.enableVertexAttribArray(texCoordLocation);
  5485. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5486. gl.uniform1i(texLayerLocation, 0);
  5487. gl.uniform1i(texMaskLocation, 1);
  5488. smaskCache = cache;
  5489. }
  5490. function composeSMask(layer, mask, properties) {
  5491. var width = layer.width, height = layer.height;
  5492. if (!smaskCache) {
  5493. initSmaskGL();
  5494. }
  5495. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5496. canvas.width = width;
  5497. canvas.height = height;
  5498. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5499. gl.uniform2f(cache.resolutionLocation, width, height);
  5500. if (properties.backdrop) {
  5501. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5502. properties.backdrop[1], properties.backdrop[2], 1);
  5503. } else {
  5504. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5505. }
  5506. gl.uniform1i(cache.subtypeLocation,
  5507. properties.subtype === 'Luminosity' ? 1 : 0);
  5508. // Create a textures
  5509. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5510. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5511. // Create a buffer and put a single clipspace rectangle in
  5512. // it (2 triangles)
  5513. var buffer = gl.createBuffer();
  5514. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5515. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5516. 0, 0,
  5517. width, 0,
  5518. 0, height,
  5519. 0, height,
  5520. width, 0,
  5521. width, height]), gl.STATIC_DRAW);
  5522. gl.enableVertexAttribArray(cache.positionLocation);
  5523. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5524. // draw
  5525. gl.clearColor(0, 0, 0, 0);
  5526. gl.enable(gl.BLEND);
  5527. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5528. gl.clear(gl.COLOR_BUFFER_BIT);
  5529. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5530. gl.flush();
  5531. gl.deleteTexture(texture);
  5532. gl.deleteTexture(maskTexture);
  5533. gl.deleteBuffer(buffer);
  5534. return canvas;
  5535. }
  5536. var figuresVertexShaderCode = '\
  5537. attribute vec2 a_position; \
  5538. attribute vec3 a_color; \
  5539. \
  5540. uniform vec2 u_resolution; \
  5541. uniform vec2 u_scale; \
  5542. uniform vec2 u_offset; \
  5543. \
  5544. varying vec4 v_color; \
  5545. \
  5546. void main() { \
  5547. vec2 position = (a_position + u_offset) * u_scale; \
  5548. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5549. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5550. \
  5551. v_color = vec4(a_color / 255.0, 1.0); \
  5552. } ';
  5553. var figuresFragmentShaderCode = '\
  5554. precision mediump float; \
  5555. \
  5556. varying vec4 v_color; \
  5557. \
  5558. void main() { \
  5559. gl_FragColor = v_color; \
  5560. } ';
  5561. var figuresCache = null;
  5562. function initFiguresGL() {
  5563. var canvas, gl;
  5564. generateGL();
  5565. canvas = currentCanvas;
  5566. currentCanvas = null;
  5567. gl = currentGL;
  5568. currentGL = null;
  5569. // setup a GLSL program
  5570. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5571. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5572. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5573. gl.useProgram(program);
  5574. var cache = {};
  5575. cache.gl = gl;
  5576. cache.canvas = canvas;
  5577. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5578. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5579. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5580. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5581. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5582. figuresCache = cache;
  5583. }
  5584. function drawFigures(width, height, backgroundColor, figures, context) {
  5585. if (!figuresCache) {
  5586. initFiguresGL();
  5587. }
  5588. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5589. canvas.width = width;
  5590. canvas.height = height;
  5591. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5592. gl.uniform2f(cache.resolutionLocation, width, height);
  5593. // count triangle points
  5594. var count = 0;
  5595. var i, ii, rows;
  5596. for (i = 0, ii = figures.length; i < ii; i++) {
  5597. switch (figures[i].type) {
  5598. case 'lattice':
  5599. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5600. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5601. break;
  5602. case 'triangles':
  5603. count += figures[i].coords.length;
  5604. break;
  5605. }
  5606. }
  5607. // transfer data
  5608. var coords = new Float32Array(count * 2);
  5609. var colors = new Uint8Array(count * 3);
  5610. var coordsMap = context.coords, colorsMap = context.colors;
  5611. var pIndex = 0, cIndex = 0;
  5612. for (i = 0, ii = figures.length; i < ii; i++) {
  5613. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5614. switch (figure.type) {
  5615. case 'lattice':
  5616. var cols = figure.verticesPerRow;
  5617. rows = (ps.length / cols) | 0;
  5618. for (var row = 1; row < rows; row++) {
  5619. var offset = row * cols + 1;
  5620. for (var col = 1; col < cols; col++, offset++) {
  5621. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5622. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5623. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5624. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5625. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5626. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5627. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5628. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5629. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5630. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5631. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5632. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5633. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5634. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5635. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5636. coords[pIndex + 6] = coords[pIndex + 2];
  5637. coords[pIndex + 7] = coords[pIndex + 3];
  5638. coords[pIndex + 8] = coords[pIndex + 4];
  5639. coords[pIndex + 9] = coords[pIndex + 5];
  5640. coords[pIndex + 10] = coordsMap[ps[offset]];
  5641. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5642. colors[cIndex + 9] = colors[cIndex + 3];
  5643. colors[cIndex + 10] = colors[cIndex + 4];
  5644. colors[cIndex + 11] = colors[cIndex + 5];
  5645. colors[cIndex + 12] = colors[cIndex + 6];
  5646. colors[cIndex + 13] = colors[cIndex + 7];
  5647. colors[cIndex + 14] = colors[cIndex + 8];
  5648. colors[cIndex + 15] = colorsMap[cs[offset]];
  5649. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5650. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5651. pIndex += 12;
  5652. cIndex += 18;
  5653. }
  5654. }
  5655. break;
  5656. case 'triangles':
  5657. for (var j = 0, jj = ps.length; j < jj; j++) {
  5658. coords[pIndex] = coordsMap[ps[j]];
  5659. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5660. colors[cIndex] = colorsMap[cs[j]];
  5661. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5662. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5663. pIndex += 2;
  5664. cIndex += 3;
  5665. }
  5666. break;
  5667. }
  5668. }
  5669. // draw
  5670. if (backgroundColor) {
  5671. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5672. backgroundColor[2] / 255, 1.0);
  5673. } else {
  5674. gl.clearColor(0, 0, 0, 0);
  5675. }
  5676. gl.clear(gl.COLOR_BUFFER_BIT);
  5677. var coordsBuffer = gl.createBuffer();
  5678. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5679. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5680. gl.enableVertexAttribArray(cache.positionLocation);
  5681. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5682. var colorsBuffer = gl.createBuffer();
  5683. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5684. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5685. gl.enableVertexAttribArray(cache.colorLocation);
  5686. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5687. 0, 0);
  5688. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5689. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5690. gl.drawArrays(gl.TRIANGLES, 0, count);
  5691. gl.flush();
  5692. gl.deleteBuffer(coordsBuffer);
  5693. gl.deleteBuffer(colorsBuffer);
  5694. return canvas;
  5695. }
  5696. function cleanup() {
  5697. if (smaskCache && smaskCache.canvas) {
  5698. smaskCache.canvas.width = 0;
  5699. smaskCache.canvas.height = 0;
  5700. }
  5701. if (figuresCache && figuresCache.canvas) {
  5702. figuresCache.canvas.width = 0;
  5703. figuresCache.canvas.height = 0;
  5704. }
  5705. smaskCache = null;
  5706. figuresCache = null;
  5707. }
  5708. return {
  5709. get isEnabled() {
  5710. if (getDefaultSetting('disableWebGL')) {
  5711. return false;
  5712. }
  5713. var enabled = false;
  5714. try {
  5715. generateGL();
  5716. enabled = !!currentGL;
  5717. } catch (e) { }
  5718. return shadow(this, 'isEnabled', enabled);
  5719. },
  5720. composeSMask: composeSMask,
  5721. drawFigures: drawFigures,
  5722. clear: cleanup
  5723. };
  5724. })();
  5725. exports.WebGLUtils = WebGLUtils;
  5726. }));
  5727. (function (root, factory) {
  5728. {
  5729. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5730. root.pdfjsDisplayWebGL);
  5731. }
  5732. }(this, function (exports, sharedUtil, displayWebGL) {
  5733. var Util = sharedUtil.Util;
  5734. var info = sharedUtil.info;
  5735. var isArray = sharedUtil.isArray;
  5736. var error = sharedUtil.error;
  5737. var WebGLUtils = displayWebGL.WebGLUtils;
  5738. var ShadingIRs = {};
  5739. ShadingIRs.RadialAxial = {
  5740. fromIR: function RadialAxial_fromIR(raw) {
  5741. var type = raw[1];
  5742. var colorStops = raw[2];
  5743. var p0 = raw[3];
  5744. var p1 = raw[4];
  5745. var r0 = raw[5];
  5746. var r1 = raw[6];
  5747. return {
  5748. type: 'Pattern',
  5749. getPattern: function RadialAxial_getPattern(ctx) {
  5750. var grad;
  5751. if (type === 'axial') {
  5752. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5753. } else if (type === 'radial') {
  5754. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5755. }
  5756. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5757. var c = colorStops[i];
  5758. grad.addColorStop(c[0], c[1]);
  5759. }
  5760. return grad;
  5761. }
  5762. };
  5763. }
  5764. };
  5765. var createMeshCanvas = (function createMeshCanvasClosure() {
  5766. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5767. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5768. var coords = context.coords, colors = context.colors;
  5769. var bytes = data.data, rowSize = data.width * 4;
  5770. var tmp;
  5771. if (coords[p1 + 1] > coords[p2 + 1]) {
  5772. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5773. }
  5774. if (coords[p2 + 1] > coords[p3 + 1]) {
  5775. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5776. }
  5777. if (coords[p1 + 1] > coords[p2 + 1]) {
  5778. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5779. }
  5780. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5781. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5782. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5783. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5784. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5785. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5786. if (y1 >= y3) {
  5787. return;
  5788. }
  5789. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5790. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5791. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5792. var minY = Math.round(y1), maxY = Math.round(y3);
  5793. var xa, car, cag, cab;
  5794. var xb, cbr, cbg, cbb;
  5795. var k;
  5796. for (var y = minY; y <= maxY; y++) {
  5797. if (y < y2) {
  5798. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5799. xa = x1 - (x1 - x2) * k;
  5800. car = c1r - (c1r - c2r) * k;
  5801. cag = c1g - (c1g - c2g) * k;
  5802. cab = c1b - (c1b - c2b) * k;
  5803. } else {
  5804. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5805. xa = x2 - (x2 - x3) * k;
  5806. car = c2r - (c2r - c3r) * k;
  5807. cag = c2g - (c2g - c3g) * k;
  5808. cab = c2b - (c2b - c3b) * k;
  5809. }
  5810. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5811. xb = x1 - (x1 - x3) * k;
  5812. cbr = c1r - (c1r - c3r) * k;
  5813. cbg = c1g - (c1g - c3g) * k;
  5814. cbb = c1b - (c1b - c3b) * k;
  5815. var x1_ = Math.round(Math.min(xa, xb));
  5816. var x2_ = Math.round(Math.max(xa, xb));
  5817. var j = rowSize * y + x1_ * 4;
  5818. for (var x = x1_; x <= x2_; x++) {
  5819. k = (xa - x) / (xa - xb);
  5820. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5821. bytes[j++] = (car - (car - cbr) * k) | 0;
  5822. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5823. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5824. bytes[j++] = 255;
  5825. }
  5826. }
  5827. }
  5828. function drawFigure(data, figure, context) {
  5829. var ps = figure.coords;
  5830. var cs = figure.colors;
  5831. var i, ii;
  5832. switch (figure.type) {
  5833. case 'lattice':
  5834. var verticesPerRow = figure.verticesPerRow;
  5835. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5836. var cols = verticesPerRow - 1;
  5837. for (i = 0; i < rows; i++) {
  5838. var q = i * verticesPerRow;
  5839. for (var j = 0; j < cols; j++, q++) {
  5840. drawTriangle(data, context,
  5841. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5842. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5843. drawTriangle(data, context,
  5844. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5845. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5846. }
  5847. }
  5848. break;
  5849. case 'triangles':
  5850. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5851. drawTriangle(data, context,
  5852. ps[i], ps[i + 1], ps[i + 2],
  5853. cs[i], cs[i + 1], cs[i + 2]);
  5854. }
  5855. break;
  5856. default:
  5857. error('illigal figure');
  5858. break;
  5859. }
  5860. }
  5861. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5862. backgroundColor, cachedCanvases) {
  5863. // we will increase scale on some weird factor to let antialiasing take
  5864. // care of "rough" edges
  5865. var EXPECTED_SCALE = 1.1;
  5866. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5867. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5868. // We need to keep transparent border around our pattern for fill():
  5869. // createPattern with 'no-repeat' will bleed edges across entire area.
  5870. var BORDER_SIZE = 2;
  5871. var offsetX = Math.floor(bounds[0]);
  5872. var offsetY = Math.floor(bounds[1]);
  5873. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5874. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5875. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5876. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5877. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5878. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5879. var scaleX = boundsWidth / width;
  5880. var scaleY = boundsHeight / height;
  5881. var context = {
  5882. coords: coords,
  5883. colors: colors,
  5884. offsetX: -offsetX,
  5885. offsetY: -offsetY,
  5886. scaleX: 1 / scaleX,
  5887. scaleY: 1 / scaleY
  5888. };
  5889. var paddedWidth = width + BORDER_SIZE * 2;
  5890. var paddedHeight = height + BORDER_SIZE * 2;
  5891. var canvas, tmpCanvas, i, ii;
  5892. if (WebGLUtils.isEnabled) {
  5893. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5894. figures, context);
  5895. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5896. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5897. false);
  5898. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5899. canvas = tmpCanvas.canvas;
  5900. } else {
  5901. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5902. false);
  5903. var tmpCtx = tmpCanvas.context;
  5904. var data = tmpCtx.createImageData(width, height);
  5905. if (backgroundColor) {
  5906. var bytes = data.data;
  5907. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5908. bytes[i] = backgroundColor[0];
  5909. bytes[i + 1] = backgroundColor[1];
  5910. bytes[i + 2] = backgroundColor[2];
  5911. bytes[i + 3] = 255;
  5912. }
  5913. }
  5914. for (i = 0; i < figures.length; i++) {
  5915. drawFigure(data, figures[i], context);
  5916. }
  5917. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5918. canvas = tmpCanvas.canvas;
  5919. }
  5920. return {canvas: canvas,
  5921. offsetX: offsetX - BORDER_SIZE * scaleX,
  5922. offsetY: offsetY - BORDER_SIZE * scaleY,
  5923. scaleX: scaleX, scaleY: scaleY};
  5924. }
  5925. return createMeshCanvas;
  5926. })();
  5927. ShadingIRs.Mesh = {
  5928. fromIR: function Mesh_fromIR(raw) {
  5929. //var type = raw[1];
  5930. var coords = raw[2];
  5931. var colors = raw[3];
  5932. var figures = raw[4];
  5933. var bounds = raw[5];
  5934. var matrix = raw[6];
  5935. //var bbox = raw[7];
  5936. var background = raw[8];
  5937. return {
  5938. type: 'Pattern',
  5939. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5940. var scale;
  5941. if (shadingFill) {
  5942. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5943. } else {
  5944. // Obtain scale from matrix and current transformation matrix.
  5945. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5946. if (matrix) {
  5947. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5948. scale = [scale[0] * matrixScale[0],
  5949. scale[1] * matrixScale[1]];
  5950. }
  5951. }
  5952. // Rasterizing on the main thread since sending/queue large canvases
  5953. // might cause OOM.
  5954. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5955. colors, figures, shadingFill ? null : background,
  5956. owner.cachedCanvases);
  5957. if (!shadingFill) {
  5958. ctx.setTransform.apply(ctx, owner.baseTransform);
  5959. if (matrix) {
  5960. ctx.transform.apply(ctx, matrix);
  5961. }
  5962. }
  5963. ctx.translate(temporaryPatternCanvas.offsetX,
  5964. temporaryPatternCanvas.offsetY);
  5965. ctx.scale(temporaryPatternCanvas.scaleX,
  5966. temporaryPatternCanvas.scaleY);
  5967. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5968. }
  5969. };
  5970. }
  5971. };
  5972. ShadingIRs.Dummy = {
  5973. fromIR: function Dummy_fromIR() {
  5974. return {
  5975. type: 'Pattern',
  5976. getPattern: function Dummy_fromIR_getPattern() {
  5977. return 'hotpink';
  5978. }
  5979. };
  5980. }
  5981. };
  5982. function getShadingPatternFromIR(raw) {
  5983. var shadingIR = ShadingIRs[raw[0]];
  5984. if (!shadingIR) {
  5985. error('Unknown IR type: ' + raw[0]);
  5986. }
  5987. return shadingIR.fromIR(raw);
  5988. }
  5989. var TilingPattern = (function TilingPatternClosure() {
  5990. var PaintType = {
  5991. COLORED: 1,
  5992. UNCOLORED: 2
  5993. };
  5994. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5995. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5996. this.operatorList = IR[2];
  5997. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5998. this.bbox = IR[4];
  5999. this.xstep = IR[5];
  6000. this.ystep = IR[6];
  6001. this.paintType = IR[7];
  6002. this.tilingType = IR[8];
  6003. this.color = color;
  6004. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6005. this.baseTransform = baseTransform;
  6006. this.type = 'Pattern';
  6007. this.ctx = ctx;
  6008. }
  6009. TilingPattern.prototype = {
  6010. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6011. var operatorList = this.operatorList;
  6012. var bbox = this.bbox;
  6013. var xstep = this.xstep;
  6014. var ystep = this.ystep;
  6015. var paintType = this.paintType;
  6016. var tilingType = this.tilingType;
  6017. var color = this.color;
  6018. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6019. info('TilingType: ' + tilingType);
  6020. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6021. var topLeft = [x0, y0];
  6022. // we want the canvas to be as large as the step size
  6023. var botRight = [x0 + xstep, y0 + ystep];
  6024. var width = botRight[0] - topLeft[0];
  6025. var height = botRight[1] - topLeft[1];
  6026. // Obtain scale from matrix and current transformation matrix.
  6027. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6028. var curMatrixScale = Util.singularValueDecompose2dScale(
  6029. this.baseTransform);
  6030. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  6031. matrixScale[1] * curMatrixScale[1]];
  6032. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6033. // Use width and height values that are as close as possible to the end
  6034. // result when the pattern is used. Too low value makes the pattern look
  6035. // blurry. Too large value makes it look too crispy.
  6036. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  6037. MAX_PATTERN_SIZE);
  6038. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  6039. MAX_PATTERN_SIZE);
  6040. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  6041. width, height, true);
  6042. var tmpCtx = tmpCanvas.context;
  6043. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6044. graphics.groupLevel = owner.groupLevel;
  6045. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6046. this.setScale(width, height, xstep, ystep);
  6047. this.transformToScale(graphics);
  6048. // transform coordinates to pattern space
  6049. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  6050. graphics.transform.apply(graphics, tmpTranslate);
  6051. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6052. graphics.executeOperatorList(operatorList);
  6053. return tmpCanvas.canvas;
  6054. },
  6055. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6056. this.scale = [width / xstep, height / ystep];
  6057. },
  6058. transformToScale: function TilingPattern_transformToScale(graphics) {
  6059. var scale = this.scale;
  6060. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  6061. graphics.transform.apply(graphics, tmpScale);
  6062. },
  6063. scaleToContext: function TilingPattern_scaleToContext() {
  6064. var scale = this.scale;
  6065. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6066. },
  6067. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6068. if (bbox && isArray(bbox) && bbox.length === 4) {
  6069. var bboxWidth = x1 - x0;
  6070. var bboxHeight = y1 - y0;
  6071. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6072. graphics.clip();
  6073. graphics.endPath();
  6074. }
  6075. },
  6076. setFillAndStrokeStyleToContext:
  6077. function setFillAndStrokeStyleToContext(context, paintType, color) {
  6078. switch (paintType) {
  6079. case PaintType.COLORED:
  6080. var ctx = this.ctx;
  6081. context.fillStyle = ctx.fillStyle;
  6082. context.strokeStyle = ctx.strokeStyle;
  6083. break;
  6084. case PaintType.UNCOLORED:
  6085. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6086. context.fillStyle = cssColor;
  6087. context.strokeStyle = cssColor;
  6088. break;
  6089. default:
  6090. error('Unsupported paint type: ' + paintType);
  6091. }
  6092. },
  6093. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6094. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6095. ctx = this.ctx;
  6096. ctx.setTransform.apply(ctx, this.baseTransform);
  6097. ctx.transform.apply(ctx, this.matrix);
  6098. this.scaleToContext();
  6099. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6100. }
  6101. };
  6102. return TilingPattern;
  6103. })();
  6104. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6105. exports.TilingPattern = TilingPattern;
  6106. }));
  6107. (function (root, factory) {
  6108. {
  6109. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  6110. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  6111. root.pdfjsDisplayWebGL);
  6112. }
  6113. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  6114. displayWebGL) {
  6115. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6116. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6117. var ImageKind = sharedUtil.ImageKind;
  6118. var OPS = sharedUtil.OPS;
  6119. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6120. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6121. var Util = sharedUtil.Util;
  6122. var assert = sharedUtil.assert;
  6123. var info = sharedUtil.info;
  6124. var isNum = sharedUtil.isNum;
  6125. var isArray = sharedUtil.isArray;
  6126. var isLittleEndian = sharedUtil.isLittleEndian;
  6127. var error = sharedUtil.error;
  6128. var shadow = sharedUtil.shadow;
  6129. var warn = sharedUtil.warn;
  6130. var TilingPattern = displayPatternHelper.TilingPattern;
  6131. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6132. var WebGLUtils = displayWebGL.WebGLUtils;
  6133. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6134. // <canvas> contexts store most of the state we need natively.
  6135. // However, PDF needs a bit more state, which we store here.
  6136. // Minimal font size that would be used during canvas fillText operations.
  6137. var MIN_FONT_SIZE = 16;
  6138. // Maximum font size that would be used during canvas fillText operations.
  6139. var MAX_FONT_SIZE = 100;
  6140. var MAX_GROUP_SIZE = 4096;
  6141. // Heuristic value used when enforcing minimum line widths.
  6142. var MIN_WIDTH_FACTOR = 0.65;
  6143. var COMPILE_TYPE3_GLYPHS = true;
  6144. var MAX_SIZE_TO_COMPILE = 1000;
  6145. var FULL_CHUNK_HEIGHT = 16;
  6146. var HasCanvasTypedArraysCached = {
  6147. get value() {
  6148. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6149. }
  6150. };
  6151. var IsLittleEndianCached = {
  6152. get value() {
  6153. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6154. }
  6155. };
  6156. function createScratchCanvas(width, height) {
  6157. var canvas = document.createElement('canvas');
  6158. canvas.width = width;
  6159. canvas.height = height;
  6160. return canvas;
  6161. }
  6162. function addContextCurrentTransform(ctx) {
  6163. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6164. if (!ctx.mozCurrentTransform) {
  6165. ctx._originalSave = ctx.save;
  6166. ctx._originalRestore = ctx.restore;
  6167. ctx._originalRotate = ctx.rotate;
  6168. ctx._originalScale = ctx.scale;
  6169. ctx._originalTranslate = ctx.translate;
  6170. ctx._originalTransform = ctx.transform;
  6171. ctx._originalSetTransform = ctx.setTransform;
  6172. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6173. ctx._transformStack = [];
  6174. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6175. get: function getCurrentTransform() {
  6176. return this._transformMatrix;
  6177. }
  6178. });
  6179. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6180. get: function getCurrentTransformInverse() {
  6181. // Calculation done using WolframAlpha:
  6182. // http://www.wolframalpha.com/input/?
  6183. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6184. var m = this._transformMatrix;
  6185. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6186. var ad_bc = a * d - b * c;
  6187. var bc_ad = b * c - a * d;
  6188. return [
  6189. d / ad_bc,
  6190. b / bc_ad,
  6191. c / bc_ad,
  6192. a / ad_bc,
  6193. (d * e - c * f) / bc_ad,
  6194. (b * e - a * f) / ad_bc
  6195. ];
  6196. }
  6197. });
  6198. ctx.save = function ctxSave() {
  6199. var old = this._transformMatrix;
  6200. this._transformStack.push(old);
  6201. this._transformMatrix = old.slice(0, 6);
  6202. this._originalSave();
  6203. };
  6204. ctx.restore = function ctxRestore() {
  6205. var prev = this._transformStack.pop();
  6206. if (prev) {
  6207. this._transformMatrix = prev;
  6208. this._originalRestore();
  6209. }
  6210. };
  6211. ctx.translate = function ctxTranslate(x, y) {
  6212. var m = this._transformMatrix;
  6213. m[4] = m[0] * x + m[2] * y + m[4];
  6214. m[5] = m[1] * x + m[3] * y + m[5];
  6215. this._originalTranslate(x, y);
  6216. };
  6217. ctx.scale = function ctxScale(x, y) {
  6218. var m = this._transformMatrix;
  6219. m[0] = m[0] * x;
  6220. m[1] = m[1] * x;
  6221. m[2] = m[2] * y;
  6222. m[3] = m[3] * y;
  6223. this._originalScale(x, y);
  6224. };
  6225. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6226. var m = this._transformMatrix;
  6227. this._transformMatrix = [
  6228. m[0] * a + m[2] * b,
  6229. m[1] * a + m[3] * b,
  6230. m[0] * c + m[2] * d,
  6231. m[1] * c + m[3] * d,
  6232. m[0] * e + m[2] * f + m[4],
  6233. m[1] * e + m[3] * f + m[5]
  6234. ];
  6235. ctx._originalTransform(a, b, c, d, e, f);
  6236. };
  6237. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6238. this._transformMatrix = [a, b, c, d, e, f];
  6239. ctx._originalSetTransform(a, b, c, d, e, f);
  6240. };
  6241. ctx.rotate = function ctxRotate(angle) {
  6242. var cosValue = Math.cos(angle);
  6243. var sinValue = Math.sin(angle);
  6244. var m = this._transformMatrix;
  6245. this._transformMatrix = [
  6246. m[0] * cosValue + m[2] * sinValue,
  6247. m[1] * cosValue + m[3] * sinValue,
  6248. m[0] * (-sinValue) + m[2] * cosValue,
  6249. m[1] * (-sinValue) + m[3] * cosValue,
  6250. m[4],
  6251. m[5]
  6252. ];
  6253. this._originalRotate(angle);
  6254. };
  6255. }
  6256. }
  6257. var CachedCanvases = (function CachedCanvasesClosure() {
  6258. function CachedCanvases() {
  6259. this.cache = Object.create(null);
  6260. }
  6261. CachedCanvases.prototype = {
  6262. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6263. trackTransform) {
  6264. var canvasEntry;
  6265. if (this.cache[id] !== undefined) {
  6266. canvasEntry = this.cache[id];
  6267. canvasEntry.canvas.width = width;
  6268. canvasEntry.canvas.height = height;
  6269. // reset canvas transform for emulated mozCurrentTransform, if needed
  6270. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6271. } else {
  6272. var canvas = createScratchCanvas(width, height);
  6273. var ctx = canvas.getContext('2d');
  6274. if (trackTransform) {
  6275. addContextCurrentTransform(ctx);
  6276. }
  6277. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6278. }
  6279. return canvasEntry;
  6280. },
  6281. clear: function () {
  6282. for (var id in this.cache) {
  6283. var canvasEntry = this.cache[id];
  6284. // Zeroing the width and height causes Firefox to release graphics
  6285. // resources immediately, which can greatly reduce memory consumption.
  6286. canvasEntry.canvas.width = 0;
  6287. canvasEntry.canvas.height = 0;
  6288. delete this.cache[id];
  6289. }
  6290. }
  6291. };
  6292. return CachedCanvases;
  6293. })();
  6294. function compileType3Glyph(imgData) {
  6295. var POINT_TO_PROCESS_LIMIT = 1000;
  6296. var width = imgData.width, height = imgData.height;
  6297. var i, j, j0, width1 = width + 1;
  6298. var points = new Uint8Array(width1 * (height + 1));
  6299. var POINT_TYPES =
  6300. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6301. // decodes bit-packed mask data
  6302. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6303. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6304. for (i = 0, ii = data0.length; i < ii; i++) {
  6305. var mask = 128, elem = data0[i];
  6306. while (mask > 0) {
  6307. data[pos++] = (elem & mask) ? 0 : 255;
  6308. mask >>= 1;
  6309. }
  6310. }
  6311. // finding iteresting points: every point is located between mask pixels,
  6312. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6313. // will have flags assigned based on neighboring mask pixels:
  6314. // 4 | 8
  6315. // --P--
  6316. // 2 | 1
  6317. // We are interested only in points with the flags:
  6318. // - outside corners: 1, 2, 4, 8;
  6319. // - inside corners: 7, 11, 13, 14;
  6320. // - and, intersections: 5, 10.
  6321. var count = 0;
  6322. pos = 0;
  6323. if (data[pos] !== 0) {
  6324. points[0] = 1;
  6325. ++count;
  6326. }
  6327. for (j = 1; j < width; j++) {
  6328. if (data[pos] !== data[pos + 1]) {
  6329. points[j] = data[pos] ? 2 : 1;
  6330. ++count;
  6331. }
  6332. pos++;
  6333. }
  6334. if (data[pos] !== 0) {
  6335. points[j] = 2;
  6336. ++count;
  6337. }
  6338. for (i = 1; i < height; i++) {
  6339. pos = i * lineSize;
  6340. j0 = i * width1;
  6341. if (data[pos - lineSize] !== data[pos]) {
  6342. points[j0] = data[pos] ? 1 : 8;
  6343. ++count;
  6344. }
  6345. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6346. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6347. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6348. for (j = 1; j < width; j++) {
  6349. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6350. (data[pos - lineSize + 1] ? 8 : 0);
  6351. if (POINT_TYPES[sum]) {
  6352. points[j0 + j] = POINT_TYPES[sum];
  6353. ++count;
  6354. }
  6355. pos++;
  6356. }
  6357. if (data[pos - lineSize] !== data[pos]) {
  6358. points[j0 + j] = data[pos] ? 2 : 4;
  6359. ++count;
  6360. }
  6361. if (count > POINT_TO_PROCESS_LIMIT) {
  6362. return null;
  6363. }
  6364. }
  6365. pos = lineSize * (height - 1);
  6366. j0 = i * width1;
  6367. if (data[pos] !== 0) {
  6368. points[j0] = 8;
  6369. ++count;
  6370. }
  6371. for (j = 1; j < width; j++) {
  6372. if (data[pos] !== data[pos + 1]) {
  6373. points[j0 + j] = data[pos] ? 4 : 8;
  6374. ++count;
  6375. }
  6376. pos++;
  6377. }
  6378. if (data[pos] !== 0) {
  6379. points[j0 + j] = 4;
  6380. ++count;
  6381. }
  6382. if (count > POINT_TO_PROCESS_LIMIT) {
  6383. return null;
  6384. }
  6385. // building outlines
  6386. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6387. var outlines = [];
  6388. for (i = 0; count && i <= height; i++) {
  6389. var p = i * width1;
  6390. var end = p + width;
  6391. while (p < end && !points[p]) {
  6392. p++;
  6393. }
  6394. if (p === end) {
  6395. continue;
  6396. }
  6397. var coords = [p % width1, i];
  6398. var type = points[p], p0 = p, pp;
  6399. do {
  6400. var step = steps[type];
  6401. do {
  6402. p += step;
  6403. } while (!points[p]);
  6404. pp = points[p];
  6405. if (pp !== 5 && pp !== 10) {
  6406. // set new direction
  6407. type = pp;
  6408. // delete mark
  6409. points[p] = 0;
  6410. } else { // type is 5 or 10, ie, a crossing
  6411. // set new direction
  6412. type = pp & ((0x33 * type) >> 4);
  6413. // set new type for "future hit"
  6414. points[p] &= (type >> 2 | type << 2);
  6415. }
  6416. coords.push(p % width1);
  6417. coords.push((p / width1) | 0);
  6418. --count;
  6419. } while (p0 !== p);
  6420. outlines.push(coords);
  6421. --i;
  6422. }
  6423. var drawOutline = function(c) {
  6424. c.save();
  6425. // the path shall be painted in [0..1]x[0..1] space
  6426. c.scale(1 / width, -1 / height);
  6427. c.translate(0, -height);
  6428. c.beginPath();
  6429. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6430. var o = outlines[i];
  6431. c.moveTo(o[0], o[1]);
  6432. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6433. c.lineTo(o[j], o[j+1]);
  6434. }
  6435. }
  6436. c.fill();
  6437. c.beginPath();
  6438. c.restore();
  6439. };
  6440. return drawOutline;
  6441. }
  6442. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6443. function CanvasExtraState(old) {
  6444. // Are soft masks and alpha values shapes or opacities?
  6445. this.alphaIsShape = false;
  6446. this.fontSize = 0;
  6447. this.fontSizeScale = 1;
  6448. this.textMatrix = IDENTITY_MATRIX;
  6449. this.textMatrixScale = 1;
  6450. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6451. this.leading = 0;
  6452. // Current point (in user coordinates)
  6453. this.x = 0;
  6454. this.y = 0;
  6455. // Start of text line (in text coordinates)
  6456. this.lineX = 0;
  6457. this.lineY = 0;
  6458. // Character and word spacing
  6459. this.charSpacing = 0;
  6460. this.wordSpacing = 0;
  6461. this.textHScale = 1;
  6462. this.textRenderingMode = TextRenderingMode.FILL;
  6463. this.textRise = 0;
  6464. // Default fore and background colors
  6465. this.fillColor = '#000000';
  6466. this.strokeColor = '#000000';
  6467. this.patternFill = false;
  6468. // Note: fill alpha applies to all non-stroking operations
  6469. this.fillAlpha = 1;
  6470. this.strokeAlpha = 1;
  6471. this.lineWidth = 1;
  6472. this.activeSMask = null;
  6473. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6474. this.old = old;
  6475. }
  6476. CanvasExtraState.prototype = {
  6477. clone: function CanvasExtraState_clone() {
  6478. return Object.create(this);
  6479. },
  6480. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6481. this.x = x;
  6482. this.y = y;
  6483. }
  6484. };
  6485. return CanvasExtraState;
  6486. })();
  6487. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6488. // Defines the time the executeOperatorList is going to be executing
  6489. // before it stops and shedules a continue of execution.
  6490. var EXECUTION_TIME = 15;
  6491. // Defines the number of steps before checking the execution time
  6492. var EXECUTION_STEPS = 10;
  6493. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6494. this.ctx = canvasCtx;
  6495. this.current = new CanvasExtraState();
  6496. this.stateStack = [];
  6497. this.pendingClip = null;
  6498. this.pendingEOFill = false;
  6499. this.res = null;
  6500. this.xobjs = null;
  6501. this.commonObjs = commonObjs;
  6502. this.objs = objs;
  6503. this.imageLayer = imageLayer;
  6504. this.groupStack = [];
  6505. this.processingType3 = null;
  6506. // Patterns are painted relative to the initial page/form transform, see pdf
  6507. // spec 8.7.2 NOTE 1.
  6508. this.baseTransform = null;
  6509. this.baseTransformStack = [];
  6510. this.groupLevel = 0;
  6511. this.smaskStack = [];
  6512. this.smaskCounter = 0;
  6513. this.tempSMask = null;
  6514. this.cachedCanvases = new CachedCanvases();
  6515. if (canvasCtx) {
  6516. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6517. // the transformation must already be set in canvasCtx._transformMatrix.
  6518. addContextCurrentTransform(canvasCtx);
  6519. }
  6520. this.cachedGetSinglePixelWidth = null;
  6521. }
  6522. function putBinaryImageData(ctx, imgData) {
  6523. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6524. ctx.putImageData(imgData, 0, 0);
  6525. return;
  6526. }
  6527. // Put the image data to the canvas in chunks, rather than putting the
  6528. // whole image at once. This saves JS memory, because the ImageData object
  6529. // is smaller. It also possibly saves C++ memory within the implementation
  6530. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6531. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6532. // because too many putImageData() calls will slow things down.
  6533. //
  6534. // Note: as written, if the last chunk is partial, the putImageData() call
  6535. // will (conceptually) put pixels past the bounds of the canvas. But
  6536. // that's ok; any such pixels are ignored.
  6537. var height = imgData.height, width = imgData.width;
  6538. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6539. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6540. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6541. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6542. var srcPos = 0, destPos;
  6543. var src = imgData.data;
  6544. var dest = chunkImgData.data;
  6545. var i, j, thisChunkHeight, elemsInThisChunk;
  6546. // There are multiple forms in which the pixel data can be passed, and
  6547. // imgData.kind tells us which one this is.
  6548. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6549. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6550. var srcLength = src.byteLength;
  6551. var dest32 = HasCanvasTypedArraysCached.value ?
  6552. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6553. var dest32DataLength = dest32.length;
  6554. var fullSrcDiff = (width + 7) >> 3;
  6555. var white = 0xFFFFFFFF;
  6556. var black = (IsLittleEndianCached.value ||
  6557. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6558. for (i = 0; i < totalChunks; i++) {
  6559. thisChunkHeight =
  6560. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6561. destPos = 0;
  6562. for (j = 0; j < thisChunkHeight; j++) {
  6563. var srcDiff = srcLength - srcPos;
  6564. var k = 0;
  6565. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6566. var kEndUnrolled = kEnd & ~7;
  6567. var mask = 0;
  6568. var srcByte = 0;
  6569. for (; k < kEndUnrolled; k += 8) {
  6570. srcByte = src[srcPos++];
  6571. dest32[destPos++] = (srcByte & 128) ? white : black;
  6572. dest32[destPos++] = (srcByte & 64) ? white : black;
  6573. dest32[destPos++] = (srcByte & 32) ? white : black;
  6574. dest32[destPos++] = (srcByte & 16) ? white : black;
  6575. dest32[destPos++] = (srcByte & 8) ? white : black;
  6576. dest32[destPos++] = (srcByte & 4) ? white : black;
  6577. dest32[destPos++] = (srcByte & 2) ? white : black;
  6578. dest32[destPos++] = (srcByte & 1) ? white : black;
  6579. }
  6580. for (; k < kEnd; k++) {
  6581. if (mask === 0) {
  6582. srcByte = src[srcPos++];
  6583. mask = 128;
  6584. }
  6585. dest32[destPos++] = (srcByte & mask) ? white : black;
  6586. mask >>= 1;
  6587. }
  6588. }
  6589. // We ran out of input. Make all remaining pixels transparent.
  6590. while (destPos < dest32DataLength) {
  6591. dest32[destPos++] = 0;
  6592. }
  6593. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6594. }
  6595. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6596. // RGBA, 32-bits per pixel.
  6597. j = 0;
  6598. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6599. for (i = 0; i < fullChunks; i++) {
  6600. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6601. srcPos += elemsInThisChunk;
  6602. ctx.putImageData(chunkImgData, 0, j);
  6603. j += FULL_CHUNK_HEIGHT;
  6604. }
  6605. if (i < totalChunks) {
  6606. elemsInThisChunk = width * partialChunkHeight * 4;
  6607. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6608. ctx.putImageData(chunkImgData, 0, j);
  6609. }
  6610. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6611. // RGB, 24-bits per pixel.
  6612. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6613. elemsInThisChunk = width * thisChunkHeight;
  6614. for (i = 0; i < totalChunks; i++) {
  6615. if (i >= fullChunks) {
  6616. thisChunkHeight = partialChunkHeight;
  6617. elemsInThisChunk = width * thisChunkHeight;
  6618. }
  6619. destPos = 0;
  6620. for (j = elemsInThisChunk; j--;) {
  6621. dest[destPos++] = src[srcPos++];
  6622. dest[destPos++] = src[srcPos++];
  6623. dest[destPos++] = src[srcPos++];
  6624. dest[destPos++] = 255;
  6625. }
  6626. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6627. }
  6628. } else {
  6629. error('bad image kind: ' + imgData.kind);
  6630. }
  6631. }
  6632. function putBinaryImageMask(ctx, imgData) {
  6633. var height = imgData.height, width = imgData.width;
  6634. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6635. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6636. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6637. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6638. var srcPos = 0;
  6639. var src = imgData.data;
  6640. var dest = chunkImgData.data;
  6641. for (var i = 0; i < totalChunks; i++) {
  6642. var thisChunkHeight =
  6643. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6644. // Expand the mask so it can be used by the canvas. Any required
  6645. // inversion has already been handled.
  6646. var destPos = 3; // alpha component offset
  6647. for (var j = 0; j < thisChunkHeight; j++) {
  6648. var mask = 0;
  6649. for (var k = 0; k < width; k++) {
  6650. if (!mask) {
  6651. var elem = src[srcPos++];
  6652. mask = 128;
  6653. }
  6654. dest[destPos] = (elem & mask) ? 0 : 255;
  6655. destPos += 4;
  6656. mask >>= 1;
  6657. }
  6658. }
  6659. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6660. }
  6661. }
  6662. function copyCtxState(sourceCtx, destCtx) {
  6663. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6664. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6665. 'globalCompositeOperation', 'font'];
  6666. for (var i = 0, ii = properties.length; i < ii; i++) {
  6667. var property = properties[i];
  6668. if (sourceCtx[property] !== undefined) {
  6669. destCtx[property] = sourceCtx[property];
  6670. }
  6671. }
  6672. if (sourceCtx.setLineDash !== undefined) {
  6673. destCtx.setLineDash(sourceCtx.getLineDash());
  6674. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6675. }
  6676. }
  6677. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6678. var length = bytes.length;
  6679. for (var i = 3; i < length; i += 4) {
  6680. var alpha = bytes[i];
  6681. if (alpha === 0) {
  6682. bytes[i - 3] = r0;
  6683. bytes[i - 2] = g0;
  6684. bytes[i - 1] = b0;
  6685. } else if (alpha < 255) {
  6686. var alpha_ = 255 - alpha;
  6687. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6688. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6689. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6690. }
  6691. }
  6692. }
  6693. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6694. var length = maskData.length;
  6695. var scale = 1 / 255;
  6696. for (var i = 3; i < length; i += 4) {
  6697. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6698. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6699. }
  6700. }
  6701. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6702. var length = maskData.length;
  6703. for (var i = 3; i < length; i += 4) {
  6704. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6705. (maskData[i - 2] * 152) + // * 0.59 ....
  6706. (maskData[i - 1] * 28); // * 0.11 ....
  6707. layerData[i] = transferMap ?
  6708. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6709. (layerData[i] * y) >> 16;
  6710. }
  6711. }
  6712. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6713. subtype, backdrop, transferMap) {
  6714. var hasBackdrop = !!backdrop;
  6715. var r0 = hasBackdrop ? backdrop[0] : 0;
  6716. var g0 = hasBackdrop ? backdrop[1] : 0;
  6717. var b0 = hasBackdrop ? backdrop[2] : 0;
  6718. var composeFn;
  6719. if (subtype === 'Luminosity') {
  6720. composeFn = composeSMaskLuminosity;
  6721. } else {
  6722. composeFn = composeSMaskAlpha;
  6723. }
  6724. // processing image in chunks to save memory
  6725. var PIXELS_TO_PROCESS = 1048576;
  6726. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6727. for (var row = 0; row < height; row += chunkSize) {
  6728. var chunkHeight = Math.min(chunkSize, height - row);
  6729. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6730. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6731. if (hasBackdrop) {
  6732. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6733. }
  6734. composeFn(maskData.data, layerData.data, transferMap);
  6735. maskCtx.putImageData(layerData, 0, row);
  6736. }
  6737. }
  6738. function composeSMask(ctx, smask, layerCtx) {
  6739. var mask = smask.canvas;
  6740. var maskCtx = smask.context;
  6741. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6742. smask.offsetX, smask.offsetY);
  6743. var backdrop = smask.backdrop || null;
  6744. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6745. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6746. {subtype: smask.subtype, backdrop: backdrop});
  6747. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6748. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6749. return;
  6750. }
  6751. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6752. smask.subtype, backdrop, smask.transferMap);
  6753. ctx.drawImage(mask, 0, 0);
  6754. }
  6755. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6756. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6757. var NORMAL_CLIP = {};
  6758. var EO_CLIP = {};
  6759. CanvasGraphics.prototype = {
  6760. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6761. transparency) {
  6762. // For pdfs that use blend modes we have to clear the canvas else certain
  6763. // blend modes can look wrong since we'd be blending with a white
  6764. // backdrop. The problem with a transparent backdrop though is we then
  6765. // don't get sub pixel anti aliasing on text, creating temporary
  6766. // transparent canvas when we have blend modes.
  6767. var width = this.ctx.canvas.width;
  6768. var height = this.ctx.canvas.height;
  6769. this.ctx.save();
  6770. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6771. this.ctx.fillRect(0, 0, width, height);
  6772. this.ctx.restore();
  6773. if (transparency) {
  6774. var transparentCanvas = this.cachedCanvases.getCanvas(
  6775. 'transparent', width, height, true);
  6776. this.compositeCtx = this.ctx;
  6777. this.transparentCanvas = transparentCanvas.canvas;
  6778. this.ctx = transparentCanvas.context;
  6779. this.ctx.save();
  6780. // The transform can be applied before rendering, transferring it to
  6781. // the new canvas.
  6782. this.ctx.transform.apply(this.ctx,
  6783. this.compositeCtx.mozCurrentTransform);
  6784. }
  6785. this.ctx.save();
  6786. if (transform) {
  6787. this.ctx.transform.apply(this.ctx, transform);
  6788. }
  6789. this.ctx.transform.apply(this.ctx, viewport.transform);
  6790. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6791. if (this.imageLayer) {
  6792. this.imageLayer.beginLayout();
  6793. }
  6794. },
  6795. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6796. operatorList,
  6797. executionStartIdx, continueCallback,
  6798. stepper) {
  6799. var argsArray = operatorList.argsArray;
  6800. var fnArray = operatorList.fnArray;
  6801. var i = executionStartIdx || 0;
  6802. var argsArrayLen = argsArray.length;
  6803. // Sometimes the OperatorList to execute is empty.
  6804. if (argsArrayLen === i) {
  6805. return i;
  6806. }
  6807. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6808. typeof continueCallback === 'function');
  6809. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6810. var steps = 0;
  6811. var commonObjs = this.commonObjs;
  6812. var objs = this.objs;
  6813. var fnId;
  6814. while (true) {
  6815. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6816. stepper.breakIt(i, continueCallback);
  6817. return i;
  6818. }
  6819. fnId = fnArray[i];
  6820. if (fnId !== OPS.dependency) {
  6821. this[fnId].apply(this, argsArray[i]);
  6822. } else {
  6823. var deps = argsArray[i];
  6824. for (var n = 0, nn = deps.length; n < nn; n++) {
  6825. var depObjId = deps[n];
  6826. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6827. var objsPool = common ? commonObjs : objs;
  6828. // If the promise isn't resolved yet, add the continueCallback
  6829. // to the promise and bail out.
  6830. if (!objsPool.isResolved(depObjId)) {
  6831. objsPool.get(depObjId, continueCallback);
  6832. return i;
  6833. }
  6834. }
  6835. }
  6836. i++;
  6837. // If the entire operatorList was executed, stop as were done.
  6838. if (i === argsArrayLen) {
  6839. return i;
  6840. }
  6841. // If the execution took longer then a certain amount of time and
  6842. // `continueCallback` is specified, interrupt the execution.
  6843. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6844. if (Date.now() > endTime) {
  6845. continueCallback();
  6846. return i;
  6847. }
  6848. steps = 0;
  6849. }
  6850. // If the operatorList isn't executed completely yet OR the execution
  6851. // time was short enough, do another execution round.
  6852. }
  6853. },
  6854. endDrawing: function CanvasGraphics_endDrawing() {
  6855. // Finishing all opened operations such as SMask group painting.
  6856. if (this.current.activeSMask !== null) {
  6857. this.endSMaskGroup();
  6858. }
  6859. this.ctx.restore();
  6860. if (this.transparentCanvas) {
  6861. this.ctx = this.compositeCtx;
  6862. this.ctx.save();
  6863. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6864. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6865. this.ctx.restore();
  6866. this.transparentCanvas = null;
  6867. }
  6868. this.cachedCanvases.clear();
  6869. WebGLUtils.clear();
  6870. if (this.imageLayer) {
  6871. this.imageLayer.endLayout();
  6872. }
  6873. },
  6874. // Graphics state
  6875. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6876. this.current.lineWidth = width;
  6877. this.ctx.lineWidth = width;
  6878. },
  6879. setLineCap: function CanvasGraphics_setLineCap(style) {
  6880. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6881. },
  6882. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6883. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6884. },
  6885. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6886. this.ctx.miterLimit = limit;
  6887. },
  6888. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6889. var ctx = this.ctx;
  6890. if (ctx.setLineDash !== undefined) {
  6891. ctx.setLineDash(dashArray);
  6892. ctx.lineDashOffset = dashPhase;
  6893. }
  6894. },
  6895. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6896. // Maybe if we one day fully support color spaces this will be important
  6897. // for now we can ignore.
  6898. // TODO set rendering intent?
  6899. },
  6900. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6901. // There's no way to control this with canvas, but we can safely ignore.
  6902. // TODO set flatness?
  6903. },
  6904. setGState: function CanvasGraphics_setGState(states) {
  6905. for (var i = 0, ii = states.length; i < ii; i++) {
  6906. var state = states[i];
  6907. var key = state[0];
  6908. var value = state[1];
  6909. switch (key) {
  6910. case 'LW':
  6911. this.setLineWidth(value);
  6912. break;
  6913. case 'LC':
  6914. this.setLineCap(value);
  6915. break;
  6916. case 'LJ':
  6917. this.setLineJoin(value);
  6918. break;
  6919. case 'ML':
  6920. this.setMiterLimit(value);
  6921. break;
  6922. case 'D':
  6923. this.setDash(value[0], value[1]);
  6924. break;
  6925. case 'RI':
  6926. this.setRenderingIntent(value);
  6927. break;
  6928. case 'FL':
  6929. this.setFlatness(value);
  6930. break;
  6931. case 'Font':
  6932. this.setFont(value[0], value[1]);
  6933. break;
  6934. case 'CA':
  6935. this.current.strokeAlpha = state[1];
  6936. break;
  6937. case 'ca':
  6938. this.current.fillAlpha = state[1];
  6939. this.ctx.globalAlpha = state[1];
  6940. break;
  6941. case 'BM':
  6942. if (value && value.name && (value.name !== 'Normal')) {
  6943. var mode = value.name.replace(/([A-Z])/g,
  6944. function(c) {
  6945. return '-' + c.toLowerCase();
  6946. }
  6947. ).substring(1);
  6948. this.ctx.globalCompositeOperation = mode;
  6949. if (this.ctx.globalCompositeOperation !== mode) {
  6950. warn('globalCompositeOperation "' + mode +
  6951. '" is not supported');
  6952. }
  6953. } else {
  6954. this.ctx.globalCompositeOperation = 'source-over';
  6955. }
  6956. break;
  6957. case 'SMask':
  6958. if (this.current.activeSMask) {
  6959. // If SMask is currrenly used, it needs to be suspended or
  6960. // finished. Suspend only makes sense when at least one save()
  6961. // was performed and state needs to be reverted on restore().
  6962. if (this.stateStack.length > 0 &&
  6963. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6964. this.current.activeSMask)) {
  6965. this.suspendSMaskGroup();
  6966. } else {
  6967. this.endSMaskGroup();
  6968. }
  6969. }
  6970. this.current.activeSMask = value ? this.tempSMask : null;
  6971. if (this.current.activeSMask) {
  6972. this.beginSMaskGroup();
  6973. }
  6974. this.tempSMask = null;
  6975. break;
  6976. }
  6977. }
  6978. },
  6979. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6980. var activeSMask = this.current.activeSMask;
  6981. var drawnWidth = activeSMask.canvas.width;
  6982. var drawnHeight = activeSMask.canvas.height;
  6983. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6984. var scratchCanvas = this.cachedCanvases.getCanvas(
  6985. cacheId, drawnWidth, drawnHeight, true);
  6986. var currentCtx = this.ctx;
  6987. var currentTransform = currentCtx.mozCurrentTransform;
  6988. this.ctx.save();
  6989. var groupCtx = scratchCanvas.context;
  6990. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6991. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6992. groupCtx.transform.apply(groupCtx, currentTransform);
  6993. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6994. copyCtxState(currentCtx, groupCtx);
  6995. this.ctx = groupCtx;
  6996. this.setGState([
  6997. ['BM', 'Normal'],
  6998. ['ca', 1],
  6999. ['CA', 1]
  7000. ]);
  7001. this.groupStack.push(currentCtx);
  7002. this.groupLevel++;
  7003. },
  7004. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7005. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7006. // and future ctx state restored.
  7007. var groupCtx = this.ctx;
  7008. this.groupLevel--;
  7009. this.ctx = this.groupStack.pop();
  7010. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7011. this.ctx.restore();
  7012. this.ctx.save(); // save is needed since SMask will be resumed.
  7013. copyCtxState(groupCtx, this.ctx);
  7014. // Saving state for resuming.
  7015. this.current.resumeSMaskCtx = groupCtx;
  7016. // Transform was changed in the SMask canvas, reflecting this change on
  7017. // this.ctx.
  7018. var deltaTransform = Util.transform(
  7019. this.current.activeSMask.startTransformInverse,
  7020. groupCtx.mozCurrentTransform);
  7021. this.ctx.transform.apply(this.ctx, deltaTransform);
  7022. // SMask was composed, the results at the groupCtx can be cleared.
  7023. groupCtx.save();
  7024. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7025. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7026. groupCtx.restore();
  7027. },
  7028. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7029. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7030. // any groupCtx state since restore() command (the only caller) will do
  7031. // that for us. See also beginSMaskGroup.
  7032. var groupCtx = this.current.resumeSMaskCtx;
  7033. var currentCtx = this.ctx;
  7034. this.ctx = groupCtx;
  7035. this.groupStack.push(currentCtx);
  7036. this.groupLevel++;
  7037. },
  7038. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7039. var groupCtx = this.ctx;
  7040. this.groupLevel--;
  7041. this.ctx = this.groupStack.pop();
  7042. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7043. this.ctx.restore();
  7044. copyCtxState(groupCtx, this.ctx);
  7045. // Transform was changed in the SMask canvas, reflecting this change on
  7046. // this.ctx.
  7047. var deltaTransform = Util.transform(
  7048. this.current.activeSMask.startTransformInverse,
  7049. groupCtx.mozCurrentTransform);
  7050. this.ctx.transform.apply(this.ctx, deltaTransform);
  7051. },
  7052. save: function CanvasGraphics_save() {
  7053. this.ctx.save();
  7054. var old = this.current;
  7055. this.stateStack.push(old);
  7056. this.current = old.clone();
  7057. this.current.resumeSMaskCtx = null;
  7058. },
  7059. restore: function CanvasGraphics_restore() {
  7060. // SMask was suspended, we just need to resume it.
  7061. if (this.current.resumeSMaskCtx) {
  7062. this.resumeSMaskGroup();
  7063. }
  7064. // SMask has to be finished once there is no states that are using the
  7065. // same SMask.
  7066. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  7067. this.stateStack[this.stateStack.length - 1].activeSMask !==
  7068. this.current.activeSMask)) {
  7069. this.endSMaskGroup();
  7070. }
  7071. if (this.stateStack.length !== 0) {
  7072. this.current = this.stateStack.pop();
  7073. this.ctx.restore();
  7074. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7075. this.pendingClip = null;
  7076. this.cachedGetSinglePixelWidth = null;
  7077. }
  7078. },
  7079. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7080. this.ctx.transform(a, b, c, d, e, f);
  7081. this.cachedGetSinglePixelWidth = null;
  7082. },
  7083. // Path
  7084. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7085. var ctx = this.ctx;
  7086. var current = this.current;
  7087. var x = current.x, y = current.y;
  7088. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7089. switch (ops[i] | 0) {
  7090. case OPS.rectangle:
  7091. x = args[j++];
  7092. y = args[j++];
  7093. var width = args[j++];
  7094. var height = args[j++];
  7095. if (width === 0) {
  7096. width = this.getSinglePixelWidth();
  7097. }
  7098. if (height === 0) {
  7099. height = this.getSinglePixelWidth();
  7100. }
  7101. var xw = x + width;
  7102. var yh = y + height;
  7103. this.ctx.moveTo(x, y);
  7104. this.ctx.lineTo(xw, y);
  7105. this.ctx.lineTo(xw, yh);
  7106. this.ctx.lineTo(x, yh);
  7107. this.ctx.lineTo(x, y);
  7108. this.ctx.closePath();
  7109. break;
  7110. case OPS.moveTo:
  7111. x = args[j++];
  7112. y = args[j++];
  7113. ctx.moveTo(x, y);
  7114. break;
  7115. case OPS.lineTo:
  7116. x = args[j++];
  7117. y = args[j++];
  7118. ctx.lineTo(x, y);
  7119. break;
  7120. case OPS.curveTo:
  7121. x = args[j + 4];
  7122. y = args[j + 5];
  7123. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  7124. x, y);
  7125. j += 6;
  7126. break;
  7127. case OPS.curveTo2:
  7128. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  7129. args[j + 2], args[j + 3]);
  7130. x = args[j + 2];
  7131. y = args[j + 3];
  7132. j += 4;
  7133. break;
  7134. case OPS.curveTo3:
  7135. x = args[j + 2];
  7136. y = args[j + 3];
  7137. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7138. j += 4;
  7139. break;
  7140. case OPS.closePath:
  7141. ctx.closePath();
  7142. break;
  7143. }
  7144. }
  7145. current.setCurrentPoint(x, y);
  7146. },
  7147. closePath: function CanvasGraphics_closePath() {
  7148. this.ctx.closePath();
  7149. },
  7150. stroke: function CanvasGraphics_stroke(consumePath) {
  7151. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7152. var ctx = this.ctx;
  7153. var strokeColor = this.current.strokeColor;
  7154. // Prevent drawing too thin lines by enforcing a minimum line width.
  7155. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7156. this.current.lineWidth);
  7157. // For stroke we want to temporarily change the global alpha to the
  7158. // stroking alpha.
  7159. ctx.globalAlpha = this.current.strokeAlpha;
  7160. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7161. strokeColor.type === 'Pattern') {
  7162. // for patterns, we transform to pattern space, calculate
  7163. // the pattern, call stroke, and restore to user space
  7164. ctx.save();
  7165. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7166. ctx.stroke();
  7167. ctx.restore();
  7168. } else {
  7169. ctx.stroke();
  7170. }
  7171. if (consumePath) {
  7172. this.consumePath();
  7173. }
  7174. // Restore the global alpha to the fill alpha
  7175. ctx.globalAlpha = this.current.fillAlpha;
  7176. },
  7177. closeStroke: function CanvasGraphics_closeStroke() {
  7178. this.closePath();
  7179. this.stroke();
  7180. },
  7181. fill: function CanvasGraphics_fill(consumePath) {
  7182. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7183. var ctx = this.ctx;
  7184. var fillColor = this.current.fillColor;
  7185. var isPatternFill = this.current.patternFill;
  7186. var needRestore = false;
  7187. if (isPatternFill) {
  7188. ctx.save();
  7189. if (this.baseTransform) {
  7190. ctx.setTransform.apply(ctx, this.baseTransform);
  7191. }
  7192. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7193. needRestore = true;
  7194. }
  7195. if (this.pendingEOFill) {
  7196. if (ctx.mozFillRule !== undefined) {
  7197. ctx.mozFillRule = 'evenodd';
  7198. ctx.fill();
  7199. ctx.mozFillRule = 'nonzero';
  7200. } else {
  7201. ctx.fill('evenodd');
  7202. }
  7203. this.pendingEOFill = false;
  7204. } else {
  7205. ctx.fill();
  7206. }
  7207. if (needRestore) {
  7208. ctx.restore();
  7209. }
  7210. if (consumePath) {
  7211. this.consumePath();
  7212. }
  7213. },
  7214. eoFill: function CanvasGraphics_eoFill() {
  7215. this.pendingEOFill = true;
  7216. this.fill();
  7217. },
  7218. fillStroke: function CanvasGraphics_fillStroke() {
  7219. this.fill(false);
  7220. this.stroke(false);
  7221. this.consumePath();
  7222. },
  7223. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7224. this.pendingEOFill = true;
  7225. this.fillStroke();
  7226. },
  7227. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7228. this.closePath();
  7229. this.fillStroke();
  7230. },
  7231. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7232. this.pendingEOFill = true;
  7233. this.closePath();
  7234. this.fillStroke();
  7235. },
  7236. endPath: function CanvasGraphics_endPath() {
  7237. this.consumePath();
  7238. },
  7239. // Clipping
  7240. clip: function CanvasGraphics_clip() {
  7241. this.pendingClip = NORMAL_CLIP;
  7242. },
  7243. eoClip: function CanvasGraphics_eoClip() {
  7244. this.pendingClip = EO_CLIP;
  7245. },
  7246. // Text
  7247. beginText: function CanvasGraphics_beginText() {
  7248. this.current.textMatrix = IDENTITY_MATRIX;
  7249. this.current.textMatrixScale = 1;
  7250. this.current.x = this.current.lineX = 0;
  7251. this.current.y = this.current.lineY = 0;
  7252. },
  7253. endText: function CanvasGraphics_endText() {
  7254. var paths = this.pendingTextPaths;
  7255. var ctx = this.ctx;
  7256. if (paths === undefined) {
  7257. ctx.beginPath();
  7258. return;
  7259. }
  7260. ctx.save();
  7261. ctx.beginPath();
  7262. for (var i = 0; i < paths.length; i++) {
  7263. var path = paths[i];
  7264. ctx.setTransform.apply(ctx, path.transform);
  7265. ctx.translate(path.x, path.y);
  7266. path.addToPath(ctx, path.fontSize);
  7267. }
  7268. ctx.restore();
  7269. ctx.clip();
  7270. ctx.beginPath();
  7271. delete this.pendingTextPaths;
  7272. },
  7273. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7274. this.current.charSpacing = spacing;
  7275. },
  7276. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7277. this.current.wordSpacing = spacing;
  7278. },
  7279. setHScale: function CanvasGraphics_setHScale(scale) {
  7280. this.current.textHScale = scale / 100;
  7281. },
  7282. setLeading: function CanvasGraphics_setLeading(leading) {
  7283. this.current.leading = -leading;
  7284. },
  7285. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7286. var fontObj = this.commonObjs.get(fontRefName);
  7287. var current = this.current;
  7288. if (!fontObj) {
  7289. error('Can\'t find font for ' + fontRefName);
  7290. }
  7291. current.fontMatrix = (fontObj.fontMatrix ?
  7292. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7293. // A valid matrix needs all main diagonal elements to be non-zero
  7294. // This also ensures we bypass FF bugzilla bug #719844.
  7295. if (current.fontMatrix[0] === 0 ||
  7296. current.fontMatrix[3] === 0) {
  7297. warn('Invalid font matrix for font ' + fontRefName);
  7298. }
  7299. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7300. // and in some docs this can be negative (inverted x-y axes).
  7301. if (size < 0) {
  7302. size = -size;
  7303. current.fontDirection = -1;
  7304. } else {
  7305. current.fontDirection = 1;
  7306. }
  7307. this.current.font = fontObj;
  7308. this.current.fontSize = size;
  7309. if (fontObj.isType3Font) {
  7310. return; // we don't need ctx.font for Type3 fonts
  7311. }
  7312. var name = fontObj.loadedName || 'sans-serif';
  7313. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7314. (fontObj.bold ? 'bold' : 'normal');
  7315. var italic = fontObj.italic ? 'italic' : 'normal';
  7316. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7317. // Some font backends cannot handle fonts below certain size.
  7318. // Keeping the font at minimal size and using the fontSizeScale to change
  7319. // the current transformation matrix before the fillText/strokeText.
  7320. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7321. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7322. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7323. this.current.fontSizeScale = size / browserFontSize;
  7324. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7325. this.ctx.font = rule;
  7326. },
  7327. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7328. this.current.textRenderingMode = mode;
  7329. },
  7330. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7331. this.current.textRise = rise;
  7332. },
  7333. moveText: function CanvasGraphics_moveText(x, y) {
  7334. this.current.x = this.current.lineX += x;
  7335. this.current.y = this.current.lineY += y;
  7336. },
  7337. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7338. this.setLeading(-y);
  7339. this.moveText(x, y);
  7340. },
  7341. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7342. this.current.textMatrix = [a, b, c, d, e, f];
  7343. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7344. this.current.x = this.current.lineX = 0;
  7345. this.current.y = this.current.lineY = 0;
  7346. },
  7347. nextLine: function CanvasGraphics_nextLine() {
  7348. this.moveText(0, this.current.leading);
  7349. },
  7350. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7351. var ctx = this.ctx;
  7352. var current = this.current;
  7353. var font = current.font;
  7354. var textRenderingMode = current.textRenderingMode;
  7355. var fontSize = current.fontSize / current.fontSizeScale;
  7356. var fillStrokeMode = textRenderingMode &
  7357. TextRenderingMode.FILL_STROKE_MASK;
  7358. var isAddToPathSet = !!(textRenderingMode &
  7359. TextRenderingMode.ADD_TO_PATH_FLAG);
  7360. var addToPath;
  7361. if (font.disableFontFace || isAddToPathSet) {
  7362. addToPath = font.getPathGenerator(this.commonObjs, character);
  7363. }
  7364. if (font.disableFontFace) {
  7365. ctx.save();
  7366. ctx.translate(x, y);
  7367. ctx.beginPath();
  7368. addToPath(ctx, fontSize);
  7369. if (fillStrokeMode === TextRenderingMode.FILL ||
  7370. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7371. ctx.fill();
  7372. }
  7373. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7374. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7375. ctx.stroke();
  7376. }
  7377. ctx.restore();
  7378. } else {
  7379. if (fillStrokeMode === TextRenderingMode.FILL ||
  7380. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7381. ctx.fillText(character, x, y);
  7382. }
  7383. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7384. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7385. ctx.strokeText(character, x, y);
  7386. }
  7387. }
  7388. if (isAddToPathSet) {
  7389. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7390. paths.push({
  7391. transform: ctx.mozCurrentTransform,
  7392. x: x,
  7393. y: y,
  7394. fontSize: fontSize,
  7395. addToPath: addToPath
  7396. });
  7397. }
  7398. },
  7399. get isFontSubpixelAAEnabled() {
  7400. // Checks if anti-aliasing is enabled when scaled text is painted.
  7401. // On Windows GDI scaled fonts looks bad.
  7402. var ctx = document.createElement('canvas').getContext('2d');
  7403. ctx.scale(1.5, 1);
  7404. ctx.fillText('I', 0, 10);
  7405. var data = ctx.getImageData(0, 0, 10, 10).data;
  7406. var enabled = false;
  7407. for (var i = 3; i < data.length; i += 4) {
  7408. if (data[i] > 0 && data[i] < 255) {
  7409. enabled = true;
  7410. break;
  7411. }
  7412. }
  7413. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7414. },
  7415. showText: function CanvasGraphics_showText(glyphs) {
  7416. var current = this.current;
  7417. var font = current.font;
  7418. if (font.isType3Font) {
  7419. return this.showType3Text(glyphs);
  7420. }
  7421. var fontSize = current.fontSize;
  7422. if (fontSize === 0) {
  7423. return;
  7424. }
  7425. var ctx = this.ctx;
  7426. var fontSizeScale = current.fontSizeScale;
  7427. var charSpacing = current.charSpacing;
  7428. var wordSpacing = current.wordSpacing;
  7429. var fontDirection = current.fontDirection;
  7430. var textHScale = current.textHScale * fontDirection;
  7431. var glyphsLength = glyphs.length;
  7432. var vertical = font.vertical;
  7433. var spacingDir = vertical ? 1 : -1;
  7434. var defaultVMetrics = font.defaultVMetrics;
  7435. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7436. var simpleFillText =
  7437. current.textRenderingMode === TextRenderingMode.FILL &&
  7438. !font.disableFontFace;
  7439. ctx.save();
  7440. ctx.transform.apply(ctx, current.textMatrix);
  7441. ctx.translate(current.x, current.y + current.textRise);
  7442. if (current.patternFill) {
  7443. // TODO: Some shading patterns are not applied correctly to text,
  7444. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7445. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7446. }
  7447. if (fontDirection > 0) {
  7448. ctx.scale(textHScale, -1);
  7449. } else {
  7450. ctx.scale(textHScale, 1);
  7451. }
  7452. var lineWidth = current.lineWidth;
  7453. var scale = current.textMatrixScale;
  7454. if (scale === 0 || lineWidth === 0) {
  7455. var fillStrokeMode = current.textRenderingMode &
  7456. TextRenderingMode.FILL_STROKE_MASK;
  7457. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7458. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7459. this.cachedGetSinglePixelWidth = null;
  7460. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7461. }
  7462. } else {
  7463. lineWidth /= scale;
  7464. }
  7465. if (fontSizeScale !== 1.0) {
  7466. ctx.scale(fontSizeScale, fontSizeScale);
  7467. lineWidth /= fontSizeScale;
  7468. }
  7469. ctx.lineWidth = lineWidth;
  7470. var x = 0, i;
  7471. for (i = 0; i < glyphsLength; ++i) {
  7472. var glyph = glyphs[i];
  7473. if (isNum(glyph)) {
  7474. x += spacingDir * glyph * fontSize / 1000;
  7475. continue;
  7476. }
  7477. var restoreNeeded = false;
  7478. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7479. var character = glyph.fontChar;
  7480. var accent = glyph.accent;
  7481. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7482. var width = glyph.width;
  7483. if (vertical) {
  7484. var vmetric, vx, vy;
  7485. vmetric = glyph.vmetric || defaultVMetrics;
  7486. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7487. vx = -vx * widthAdvanceScale;
  7488. vy = vmetric[2] * widthAdvanceScale;
  7489. width = vmetric ? -vmetric[0] : width;
  7490. scaledX = vx / fontSizeScale;
  7491. scaledY = (x + vy) / fontSizeScale;
  7492. } else {
  7493. scaledX = x / fontSizeScale;
  7494. scaledY = 0;
  7495. }
  7496. if (font.remeasure && width > 0) {
  7497. // Some standard fonts may not have the exact width: rescale per
  7498. // character if measured width is greater than expected glyph width
  7499. // and subpixel-aa is enabled, otherwise just center the glyph.
  7500. var measuredWidth = ctx.measureText(character).width * 1000 /
  7501. fontSize * fontSizeScale;
  7502. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7503. var characterScaleX = width / measuredWidth;
  7504. restoreNeeded = true;
  7505. ctx.save();
  7506. ctx.scale(characterScaleX, 1);
  7507. scaledX /= characterScaleX;
  7508. } else if (width !== measuredWidth) {
  7509. scaledX += (width - measuredWidth) / 2000 *
  7510. fontSize / fontSizeScale;
  7511. }
  7512. }
  7513. // Only attempt to draw the glyph if it is actually in the embedded font
  7514. // file or if there isn't a font file so the fallback font is shown.
  7515. if (glyph.isInFont || font.missingFile) {
  7516. if (simpleFillText && !accent) {
  7517. // common case
  7518. ctx.fillText(character, scaledX, scaledY);
  7519. } else {
  7520. this.paintChar(character, scaledX, scaledY);
  7521. if (accent) {
  7522. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7523. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7524. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7525. }
  7526. }
  7527. }
  7528. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7529. x += charWidth;
  7530. if (restoreNeeded) {
  7531. ctx.restore();
  7532. }
  7533. }
  7534. if (vertical) {
  7535. current.y -= x * textHScale;
  7536. } else {
  7537. current.x += x * textHScale;
  7538. }
  7539. ctx.restore();
  7540. },
  7541. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7542. // Type3 fonts - each glyph is a "mini-PDF"
  7543. var ctx = this.ctx;
  7544. var current = this.current;
  7545. var font = current.font;
  7546. var fontSize = current.fontSize;
  7547. var fontDirection = current.fontDirection;
  7548. var spacingDir = font.vertical ? 1 : -1;
  7549. var charSpacing = current.charSpacing;
  7550. var wordSpacing = current.wordSpacing;
  7551. var textHScale = current.textHScale * fontDirection;
  7552. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7553. var glyphsLength = glyphs.length;
  7554. var isTextInvisible =
  7555. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7556. var i, glyph, width, spacingLength;
  7557. if (isTextInvisible || fontSize === 0) {
  7558. return;
  7559. }
  7560. this.cachedGetSinglePixelWidth = null;
  7561. ctx.save();
  7562. ctx.transform.apply(ctx, current.textMatrix);
  7563. ctx.translate(current.x, current.y);
  7564. ctx.scale(textHScale, fontDirection);
  7565. for (i = 0; i < glyphsLength; ++i) {
  7566. glyph = glyphs[i];
  7567. if (isNum(glyph)) {
  7568. spacingLength = spacingDir * glyph * fontSize / 1000;
  7569. this.ctx.translate(spacingLength, 0);
  7570. current.x += spacingLength * textHScale;
  7571. continue;
  7572. }
  7573. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7574. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7575. if (!operatorList) {
  7576. warn('Type3 character \"' + glyph.operatorListId +
  7577. '\" is not available');
  7578. continue;
  7579. }
  7580. this.processingType3 = glyph;
  7581. this.save();
  7582. ctx.scale(fontSize, fontSize);
  7583. ctx.transform.apply(ctx, fontMatrix);
  7584. this.executeOperatorList(operatorList);
  7585. this.restore();
  7586. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7587. width = transformed[0] * fontSize + spacing;
  7588. ctx.translate(width, 0);
  7589. current.x += width * textHScale;
  7590. }
  7591. ctx.restore();
  7592. this.processingType3 = null;
  7593. },
  7594. // Type3 fonts
  7595. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7596. // We can safely ignore this since the width should be the same
  7597. // as the width in the Widths array.
  7598. },
  7599. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7600. yWidth,
  7601. llx,
  7602. lly,
  7603. urx,
  7604. ury) {
  7605. // TODO According to the spec we're also suppose to ignore any operators
  7606. // that set color or include images while processing this type3 font.
  7607. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7608. this.clip();
  7609. this.endPath();
  7610. },
  7611. // Color
  7612. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7613. var pattern;
  7614. if (IR[0] === 'TilingPattern') {
  7615. var color = IR[1];
  7616. var baseTransform = this.baseTransform ||
  7617. this.ctx.mozCurrentTransform.slice();
  7618. var self = this;
  7619. var canvasGraphicsFactory = {
  7620. createCanvasGraphics: function (ctx) {
  7621. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7622. }
  7623. };
  7624. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7625. baseTransform);
  7626. } else {
  7627. pattern = getShadingPatternFromIR(IR);
  7628. }
  7629. return pattern;
  7630. },
  7631. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7632. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7633. },
  7634. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7635. this.current.fillColor = this.getColorN_Pattern(arguments);
  7636. this.current.patternFill = true;
  7637. },
  7638. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7639. var color = Util.makeCssRgb(r, g, b);
  7640. this.ctx.strokeStyle = color;
  7641. this.current.strokeColor = color;
  7642. },
  7643. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7644. var color = Util.makeCssRgb(r, g, b);
  7645. this.ctx.fillStyle = color;
  7646. this.current.fillColor = color;
  7647. this.current.patternFill = false;
  7648. },
  7649. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7650. var ctx = this.ctx;
  7651. this.save();
  7652. var pattern = getShadingPatternFromIR(patternIR);
  7653. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7654. var inv = ctx.mozCurrentTransformInverse;
  7655. if (inv) {
  7656. var canvas = ctx.canvas;
  7657. var width = canvas.width;
  7658. var height = canvas.height;
  7659. var bl = Util.applyTransform([0, 0], inv);
  7660. var br = Util.applyTransform([0, height], inv);
  7661. var ul = Util.applyTransform([width, 0], inv);
  7662. var ur = Util.applyTransform([width, height], inv);
  7663. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7664. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7665. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7666. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7667. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7668. } else {
  7669. // HACK to draw the gradient onto an infinite rectangle.
  7670. // PDF gradients are drawn across the entire image while
  7671. // Canvas only allows gradients to be drawn in a rectangle
  7672. // The following bug should allow us to remove this.
  7673. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7674. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7675. }
  7676. this.restore();
  7677. },
  7678. // Images
  7679. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7680. error('Should not call beginInlineImage');
  7681. },
  7682. beginImageData: function CanvasGraphics_beginImageData() {
  7683. error('Should not call beginImageData');
  7684. },
  7685. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7686. bbox) {
  7687. this.save();
  7688. this.baseTransformStack.push(this.baseTransform);
  7689. if (isArray(matrix) && 6 === matrix.length) {
  7690. this.transform.apply(this, matrix);
  7691. }
  7692. this.baseTransform = this.ctx.mozCurrentTransform;
  7693. if (isArray(bbox) && 4 === bbox.length) {
  7694. var width = bbox[2] - bbox[0];
  7695. var height = bbox[3] - bbox[1];
  7696. this.ctx.rect(bbox[0], bbox[1], width, height);
  7697. this.clip();
  7698. this.endPath();
  7699. }
  7700. },
  7701. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7702. this.restore();
  7703. this.baseTransform = this.baseTransformStack.pop();
  7704. },
  7705. beginGroup: function CanvasGraphics_beginGroup(group) {
  7706. this.save();
  7707. var currentCtx = this.ctx;
  7708. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7709. // group results aren't usually that different and they even have tools
  7710. // that ignore this setting. Notes from Rik on implementing:
  7711. // - When you encounter an transparency group, create a new canvas with
  7712. // the dimensions of the bbox
  7713. // - copy the content from the previous canvas to the new canvas
  7714. // - draw as usual
  7715. // - remove the backdrop alpha:
  7716. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7717. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7718. // backdrop
  7719. // - remove background color:
  7720. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7721. if (!group.isolated) {
  7722. info('TODO: Support non-isolated groups.');
  7723. }
  7724. // TODO knockout - supposedly possible with the clever use of compositing
  7725. // modes.
  7726. if (group.knockout) {
  7727. warn('Knockout groups not supported.');
  7728. }
  7729. var currentTransform = currentCtx.mozCurrentTransform;
  7730. if (group.matrix) {
  7731. currentCtx.transform.apply(currentCtx, group.matrix);
  7732. }
  7733. assert(group.bbox, 'Bounding box is required.');
  7734. // Based on the current transform figure out how big the bounding box
  7735. // will actually be.
  7736. var bounds = Util.getAxialAlignedBoundingBox(
  7737. group.bbox,
  7738. currentCtx.mozCurrentTransform);
  7739. // Clip the bounding box to the current canvas.
  7740. var canvasBounds = [0,
  7741. 0,
  7742. currentCtx.canvas.width,
  7743. currentCtx.canvas.height];
  7744. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7745. // Use ceil in case we're between sizes so we don't create canvas that is
  7746. // too small and make the canvas at least 1x1 pixels.
  7747. var offsetX = Math.floor(bounds[0]);
  7748. var offsetY = Math.floor(bounds[1]);
  7749. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7750. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7751. var scaleX = 1, scaleY = 1;
  7752. if (drawnWidth > MAX_GROUP_SIZE) {
  7753. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7754. drawnWidth = MAX_GROUP_SIZE;
  7755. }
  7756. if (drawnHeight > MAX_GROUP_SIZE) {
  7757. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7758. drawnHeight = MAX_GROUP_SIZE;
  7759. }
  7760. var cacheId = 'groupAt' + this.groupLevel;
  7761. if (group.smask) {
  7762. // Using two cache entries is case if masks are used one after another.
  7763. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7764. }
  7765. var scratchCanvas = this.cachedCanvases.getCanvas(
  7766. cacheId, drawnWidth, drawnHeight, true);
  7767. var groupCtx = scratchCanvas.context;
  7768. // Since we created a new canvas that is just the size of the bounding box
  7769. // we have to translate the group ctx.
  7770. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7771. groupCtx.translate(-offsetX, -offsetY);
  7772. groupCtx.transform.apply(groupCtx, currentTransform);
  7773. if (group.smask) {
  7774. // Saving state and cached mask to be used in setGState.
  7775. this.smaskStack.push({
  7776. canvas: scratchCanvas.canvas,
  7777. context: groupCtx,
  7778. offsetX: offsetX,
  7779. offsetY: offsetY,
  7780. scaleX: scaleX,
  7781. scaleY: scaleY,
  7782. subtype: group.smask.subtype,
  7783. backdrop: group.smask.backdrop,
  7784. transferMap: group.smask.transferMap || null,
  7785. startTransformInverse: null, // used during suspend operation
  7786. });
  7787. } else {
  7788. // Setup the current ctx so when the group is popped we draw it at the
  7789. // right location.
  7790. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7791. currentCtx.translate(offsetX, offsetY);
  7792. currentCtx.scale(scaleX, scaleY);
  7793. }
  7794. // The transparency group inherits all off the current graphics state
  7795. // except the blend mode, soft mask, and alpha constants.
  7796. copyCtxState(currentCtx, groupCtx);
  7797. this.ctx = groupCtx;
  7798. this.setGState([
  7799. ['BM', 'Normal'],
  7800. ['ca', 1],
  7801. ['CA', 1]
  7802. ]);
  7803. this.groupStack.push(currentCtx);
  7804. this.groupLevel++;
  7805. // Reseting mask state, masks will be applied on restore of the group.
  7806. this.current.activeSMask = null;
  7807. },
  7808. endGroup: function CanvasGraphics_endGroup(group) {
  7809. this.groupLevel--;
  7810. var groupCtx = this.ctx;
  7811. this.ctx = this.groupStack.pop();
  7812. // Turn off image smoothing to avoid sub pixel interpolation which can
  7813. // look kind of blurry for some pdfs.
  7814. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7815. this.ctx.imageSmoothingEnabled = false;
  7816. } else {
  7817. this.ctx.mozImageSmoothingEnabled = false;
  7818. }
  7819. if (group.smask) {
  7820. this.tempSMask = this.smaskStack.pop();
  7821. } else {
  7822. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7823. }
  7824. this.restore();
  7825. },
  7826. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7827. this.save();
  7828. this.current = new CanvasExtraState();
  7829. if (this.baseTransform) {
  7830. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7831. }
  7832. },
  7833. endAnnotations: function CanvasGraphics_endAnnotations() {
  7834. this.restore();
  7835. },
  7836. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7837. matrix) {
  7838. this.save();
  7839. if (isArray(rect) && 4 === rect.length) {
  7840. var width = rect[2] - rect[0];
  7841. var height = rect[3] - rect[1];
  7842. this.ctx.rect(rect[0], rect[1], width, height);
  7843. this.clip();
  7844. this.endPath();
  7845. }
  7846. this.transform.apply(this, transform);
  7847. this.transform.apply(this, matrix);
  7848. },
  7849. endAnnotation: function CanvasGraphics_endAnnotation() {
  7850. this.restore();
  7851. },
  7852. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7853. var domImage = this.objs.get(objId);
  7854. if (!domImage) {
  7855. warn('Dependent image isn\'t ready yet');
  7856. return;
  7857. }
  7858. this.save();
  7859. var ctx = this.ctx;
  7860. // scale the image to the unit square
  7861. ctx.scale(1 / w, -1 / h);
  7862. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7863. 0, -h, w, h);
  7864. if (this.imageLayer) {
  7865. var currentTransform = ctx.mozCurrentTransformInverse;
  7866. var position = this.getCanvasPosition(0, 0);
  7867. this.imageLayer.appendImage({
  7868. objId: objId,
  7869. left: position[0],
  7870. top: position[1],
  7871. width: w / currentTransform[0],
  7872. height: h / currentTransform[3]
  7873. });
  7874. }
  7875. this.restore();
  7876. },
  7877. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7878. var ctx = this.ctx;
  7879. var width = img.width, height = img.height;
  7880. var fillColor = this.current.fillColor;
  7881. var isPatternFill = this.current.patternFill;
  7882. var glyph = this.processingType3;
  7883. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7884. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7885. glyph.compiled =
  7886. compileType3Glyph({data: img.data, width: width, height: height});
  7887. } else {
  7888. glyph.compiled = null;
  7889. }
  7890. }
  7891. if (glyph && glyph.compiled) {
  7892. glyph.compiled(ctx);
  7893. return;
  7894. }
  7895. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7896. width, height);
  7897. var maskCtx = maskCanvas.context;
  7898. maskCtx.save();
  7899. putBinaryImageMask(maskCtx, img);
  7900. maskCtx.globalCompositeOperation = 'source-in';
  7901. maskCtx.fillStyle = isPatternFill ?
  7902. fillColor.getPattern(maskCtx, this) : fillColor;
  7903. maskCtx.fillRect(0, 0, width, height);
  7904. maskCtx.restore();
  7905. this.paintInlineImageXObject(maskCanvas.canvas);
  7906. },
  7907. paintImageMaskXObjectRepeat:
  7908. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7909. scaleY, positions) {
  7910. var width = imgData.width;
  7911. var height = imgData.height;
  7912. var fillColor = this.current.fillColor;
  7913. var isPatternFill = this.current.patternFill;
  7914. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7915. width, height);
  7916. var maskCtx = maskCanvas.context;
  7917. maskCtx.save();
  7918. putBinaryImageMask(maskCtx, imgData);
  7919. maskCtx.globalCompositeOperation = 'source-in';
  7920. maskCtx.fillStyle = isPatternFill ?
  7921. fillColor.getPattern(maskCtx, this) : fillColor;
  7922. maskCtx.fillRect(0, 0, width, height);
  7923. maskCtx.restore();
  7924. var ctx = this.ctx;
  7925. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7926. ctx.save();
  7927. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7928. ctx.scale(1, -1);
  7929. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7930. 0, -1, 1, 1);
  7931. ctx.restore();
  7932. }
  7933. },
  7934. paintImageMaskXObjectGroup:
  7935. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7936. var ctx = this.ctx;
  7937. var fillColor = this.current.fillColor;
  7938. var isPatternFill = this.current.patternFill;
  7939. for (var i = 0, ii = images.length; i < ii; i++) {
  7940. var image = images[i];
  7941. var width = image.width, height = image.height;
  7942. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7943. width, height);
  7944. var maskCtx = maskCanvas.context;
  7945. maskCtx.save();
  7946. putBinaryImageMask(maskCtx, image);
  7947. maskCtx.globalCompositeOperation = 'source-in';
  7948. maskCtx.fillStyle = isPatternFill ?
  7949. fillColor.getPattern(maskCtx, this) : fillColor;
  7950. maskCtx.fillRect(0, 0, width, height);
  7951. maskCtx.restore();
  7952. ctx.save();
  7953. ctx.transform.apply(ctx, image.transform);
  7954. ctx.scale(1, -1);
  7955. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7956. 0, -1, 1, 1);
  7957. ctx.restore();
  7958. }
  7959. },
  7960. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7961. var imgData = this.objs.get(objId);
  7962. if (!imgData) {
  7963. warn('Dependent image isn\'t ready yet');
  7964. return;
  7965. }
  7966. this.paintInlineImageXObject(imgData);
  7967. },
  7968. paintImageXObjectRepeat:
  7969. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7970. positions) {
  7971. var imgData = this.objs.get(objId);
  7972. if (!imgData) {
  7973. warn('Dependent image isn\'t ready yet');
  7974. return;
  7975. }
  7976. var width = imgData.width;
  7977. var height = imgData.height;
  7978. var map = [];
  7979. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7980. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7981. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7982. }
  7983. this.paintInlineImageXObjectGroup(imgData, map);
  7984. },
  7985. paintInlineImageXObject:
  7986. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7987. var width = imgData.width;
  7988. var height = imgData.height;
  7989. var ctx = this.ctx;
  7990. this.save();
  7991. // scale the image to the unit square
  7992. ctx.scale(1 / width, -1 / height);
  7993. var currentTransform = ctx.mozCurrentTransformInverse;
  7994. var a = currentTransform[0], b = currentTransform[1];
  7995. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7996. var c = currentTransform[2], d = currentTransform[3];
  7997. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7998. var imgToPaint, tmpCanvas;
  7999. // instanceof HTMLElement does not work in jsdom node.js module
  8000. if (imgData instanceof HTMLElement || !imgData.data) {
  8001. imgToPaint = imgData;
  8002. } else {
  8003. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  8004. width, height);
  8005. var tmpCtx = tmpCanvas.context;
  8006. putBinaryImageData(tmpCtx, imgData);
  8007. imgToPaint = tmpCanvas.canvas;
  8008. }
  8009. var paintWidth = width, paintHeight = height;
  8010. var tmpCanvasId = 'prescale1';
  8011. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8012. // pixels during drawImage operation, painting on the temporary canvas(es)
  8013. // that are twice smaller in size
  8014. while ((widthScale > 2 && paintWidth > 1) ||
  8015. (heightScale > 2 && paintHeight > 1)) {
  8016. var newWidth = paintWidth, newHeight = paintHeight;
  8017. if (widthScale > 2 && paintWidth > 1) {
  8018. newWidth = Math.ceil(paintWidth / 2);
  8019. widthScale /= paintWidth / newWidth;
  8020. }
  8021. if (heightScale > 2 && paintHeight > 1) {
  8022. newHeight = Math.ceil(paintHeight / 2);
  8023. heightScale /= paintHeight / newHeight;
  8024. }
  8025. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  8026. newWidth, newHeight);
  8027. tmpCtx = tmpCanvas.context;
  8028. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8029. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  8030. 0, 0, newWidth, newHeight);
  8031. imgToPaint = tmpCanvas.canvas;
  8032. paintWidth = newWidth;
  8033. paintHeight = newHeight;
  8034. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8035. }
  8036. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  8037. 0, -height, width, height);
  8038. if (this.imageLayer) {
  8039. var position = this.getCanvasPosition(0, -height);
  8040. this.imageLayer.appendImage({
  8041. imgData: imgData,
  8042. left: position[0],
  8043. top: position[1],
  8044. width: width / currentTransform[0],
  8045. height: height / currentTransform[3]
  8046. });
  8047. }
  8048. this.restore();
  8049. },
  8050. paintInlineImageXObjectGroup:
  8051. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8052. var ctx = this.ctx;
  8053. var w = imgData.width;
  8054. var h = imgData.height;
  8055. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8056. var tmpCtx = tmpCanvas.context;
  8057. putBinaryImageData(tmpCtx, imgData);
  8058. for (var i = 0, ii = map.length; i < ii; i++) {
  8059. var entry = map[i];
  8060. ctx.save();
  8061. ctx.transform.apply(ctx, entry.transform);
  8062. ctx.scale(1, -1);
  8063. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  8064. 0, -1, 1, 1);
  8065. if (this.imageLayer) {
  8066. var position = this.getCanvasPosition(entry.x, entry.y);
  8067. this.imageLayer.appendImage({
  8068. imgData: imgData,
  8069. left: position[0],
  8070. top: position[1],
  8071. width: w,
  8072. height: h
  8073. });
  8074. }
  8075. ctx.restore();
  8076. }
  8077. },
  8078. paintSolidColorImageMask:
  8079. function CanvasGraphics_paintSolidColorImageMask() {
  8080. this.ctx.fillRect(0, 0, 1, 1);
  8081. },
  8082. paintXObject: function CanvasGraphics_paintXObject() {
  8083. warn('Unsupported \'paintXObject\' command.');
  8084. },
  8085. // Marked content
  8086. markPoint: function CanvasGraphics_markPoint(tag) {
  8087. // TODO Marked content.
  8088. },
  8089. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8090. // TODO Marked content.
  8091. },
  8092. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8093. // TODO Marked content.
  8094. },
  8095. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  8096. tag, properties) {
  8097. // TODO Marked content.
  8098. },
  8099. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8100. // TODO Marked content.
  8101. },
  8102. // Compatibility
  8103. beginCompat: function CanvasGraphics_beginCompat() {
  8104. // TODO ignore undefined operators (should we do that anyway?)
  8105. },
  8106. endCompat: function CanvasGraphics_endCompat() {
  8107. // TODO stop ignoring undefined operators
  8108. },
  8109. // Helper functions
  8110. consumePath: function CanvasGraphics_consumePath() {
  8111. var ctx = this.ctx;
  8112. if (this.pendingClip) {
  8113. if (this.pendingClip === EO_CLIP) {
  8114. if (ctx.mozFillRule !== undefined) {
  8115. ctx.mozFillRule = 'evenodd';
  8116. ctx.clip();
  8117. ctx.mozFillRule = 'nonzero';
  8118. } else {
  8119. ctx.clip('evenodd');
  8120. }
  8121. } else {
  8122. ctx.clip();
  8123. }
  8124. this.pendingClip = null;
  8125. }
  8126. ctx.beginPath();
  8127. },
  8128. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8129. if (this.cachedGetSinglePixelWidth === null) {
  8130. // NOTE: The `save` and `restore` commands used below is a workaround
  8131. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8132. // from intermittently returning incorrect values in Firefox, see:
  8133. // https://github.com/mozilla/pdf.js/issues/7188.
  8134. this.ctx.save();
  8135. var inverse = this.ctx.mozCurrentTransformInverse;
  8136. this.ctx.restore();
  8137. // max of the current horizontal and vertical scale
  8138. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8139. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8140. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8141. }
  8142. return this.cachedGetSinglePixelWidth;
  8143. },
  8144. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8145. var transform = this.ctx.mozCurrentTransform;
  8146. return [
  8147. transform[0] * x + transform[2] * y + transform[4],
  8148. transform[1] * x + transform[3] * y + transform[5]
  8149. ];
  8150. }
  8151. };
  8152. for (var op in OPS) {
  8153. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8154. }
  8155. return CanvasGraphics;
  8156. })();
  8157. exports.CanvasGraphics = CanvasGraphics;
  8158. exports.createScratchCanvas = createScratchCanvas;
  8159. }));
  8160. (function (root, factory) {
  8161. {
  8162. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8163. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8164. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8165. }
  8166. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8167. displayMetadata, displayDOMUtils, amdRequire) {
  8168. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8169. var MessageHandler = sharedUtil.MessageHandler;
  8170. var MissingPDFException = sharedUtil.MissingPDFException;
  8171. var PageViewport = sharedUtil.PageViewport;
  8172. var PasswordResponses = sharedUtil.PasswordResponses;
  8173. var PasswordException = sharedUtil.PasswordException;
  8174. var StatTimer = sharedUtil.StatTimer;
  8175. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8176. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8177. var Util = sharedUtil.Util;
  8178. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8179. var error = sharedUtil.error;
  8180. var deprecated = sharedUtil.deprecated;
  8181. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8182. var info = sharedUtil.info;
  8183. var isInt = sharedUtil.isInt;
  8184. var isArray = sharedUtil.isArray;
  8185. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8186. var isSameOrigin = sharedUtil.isSameOrigin;
  8187. var loadJpegStream = sharedUtil.loadJpegStream;
  8188. var stringToBytes = sharedUtil.stringToBytes;
  8189. var globalScope = sharedUtil.globalScope;
  8190. var warn = sharedUtil.warn;
  8191. var FontFaceObject = displayFontLoader.FontFaceObject;
  8192. var FontLoader = displayFontLoader.FontLoader;
  8193. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8194. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8195. var Metadata = displayMetadata.Metadata;
  8196. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8197. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8198. var isWorkerDisabled = false;
  8199. var workerSrc;
  8200. var isPostMessageTransfersDisabled = false;
  8201. var useRequireEnsure = false;
  8202. if (typeof window === 'undefined') {
  8203. // node.js - disable worker and set require.ensure.
  8204. isWorkerDisabled = true;
  8205. if (typeof require.ensure === 'undefined') {
  8206. require.ensure = require('node-ensure');
  8207. }
  8208. useRequireEnsure = true;
  8209. }
  8210. if (typeof __webpack_require__ !== 'undefined') {
  8211. useRequireEnsure = true;
  8212. }
  8213. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8214. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8215. }
  8216. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8217. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8218. require.ensure([], function () {
  8219. var worker = require('./pdf.worker.js');
  8220. callback(worker.WorkerMessageHandler);
  8221. });
  8222. }) : dynamicLoaderSupported ? (function (callback) {
  8223. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8224. callback(worker.WorkerMessageHandler);
  8225. });
  8226. }) : null;
  8227. /**
  8228. * Document initialization / loading parameters object.
  8229. *
  8230. * @typedef {Object} DocumentInitParameters
  8231. * @property {string} url - The URL of the PDF.
  8232. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8233. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8234. * use atob() to convert it to a binary string first.
  8235. * @property {Object} httpHeaders - Basic authentication headers.
  8236. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8237. * Access-Control requests should be made using credentials such as cookies
  8238. * or authorization headers. The default is false.
  8239. * @property {string} password - For decrypting password-protected PDFs.
  8240. * @property {TypedArray} initialData - A typed array with the first portion or
  8241. * all of the pdf data. Used by the extension since some data is already
  8242. * loaded before the switch to range requests.
  8243. * @property {number} length - The PDF file length. It's used for progress
  8244. * reports and range requests operations.
  8245. * @property {PDFDataRangeTransport} range
  8246. * @property {number} rangeChunkSize - Optional parameter to specify
  8247. * maximum number of bytes fetched per range request. The default value is
  8248. * 2^16 = 65536.
  8249. * @property {PDFWorker} worker - The worker that will be used for the loading
  8250. * and parsing of the PDF data.
  8251. */
  8252. /**
  8253. * @typedef {Object} PDFDocumentStats
  8254. * @property {Array} streamTypes - Used stream types in the document (an item
  8255. * is set to true if specific stream ID was used in the document).
  8256. * @property {Array} fontTypes - Used font type in the document (an item is set
  8257. * to true if specific font ID was used in the document).
  8258. */
  8259. /**
  8260. * This is the main entry point for loading a PDF and interacting with it.
  8261. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8262. * is used, which means it must follow the same origin rules that any XHR does
  8263. * e.g. No cross domain requests without CORS.
  8264. *
  8265. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8266. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8267. * already populated with data or parameter object.
  8268. *
  8269. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8270. * if you want to manually serve range requests for data in the PDF.
  8271. *
  8272. * @param {function} passwordCallback (deprecated) It is used to request a
  8273. * password if wrong or no password was provided. The callback receives two
  8274. * parameters: function that needs to be called with new password and reason
  8275. * (see {PasswordResponses}).
  8276. *
  8277. * @param {function} progressCallback (deprecated) It is used to be able to
  8278. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8279. * a loading bar). The callback receives an {Object} with the properties:
  8280. * {number} loaded and {number} total.
  8281. *
  8282. * @return {PDFDocumentLoadingTask}
  8283. */
  8284. function getDocument(src, pdfDataRangeTransport,
  8285. passwordCallback, progressCallback) {
  8286. var task = new PDFDocumentLoadingTask();
  8287. // Support of the obsolete arguments (for compatibility with API v1.0)
  8288. if (arguments.length > 1) {
  8289. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8290. 'passwordCallback or progressCallback argument');
  8291. }
  8292. if (pdfDataRangeTransport) {
  8293. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8294. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8295. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8296. pdfDataRangeTransport.length = src.length;
  8297. pdfDataRangeTransport.initialData = src.initialData;
  8298. if (!pdfDataRangeTransport.abort) {
  8299. pdfDataRangeTransport.abort = function () {};
  8300. }
  8301. }
  8302. src = Object.create(src);
  8303. src.range = pdfDataRangeTransport;
  8304. }
  8305. task.onPassword = passwordCallback || null;
  8306. task.onProgress = progressCallback || null;
  8307. var source;
  8308. if (typeof src === 'string') {
  8309. source = { url: src };
  8310. } else if (isArrayBuffer(src)) {
  8311. source = { data: src };
  8312. } else if (src instanceof PDFDataRangeTransport) {
  8313. source = { range: src };
  8314. } else {
  8315. if (typeof src !== 'object') {
  8316. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8317. 'string or a parameter object');
  8318. }
  8319. if (!src.url && !src.data && !src.range) {
  8320. error('Invalid parameter object: need either .data, .range or .url');
  8321. }
  8322. source = src;
  8323. }
  8324. var params = {};
  8325. var rangeTransport = null;
  8326. var worker = null;
  8327. for (var key in source) {
  8328. if (key === 'url' && typeof window !== 'undefined') {
  8329. // The full path is required in the 'url' field.
  8330. params[key] = new URL(source[key], window.location).href;
  8331. continue;
  8332. } else if (key === 'range') {
  8333. rangeTransport = source[key];
  8334. continue;
  8335. } else if (key === 'worker') {
  8336. worker = source[key];
  8337. continue;
  8338. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8339. // Converting string or array-like data to Uint8Array.
  8340. var pdfBytes = source[key];
  8341. if (typeof pdfBytes === 'string') {
  8342. params[key] = stringToBytes(pdfBytes);
  8343. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8344. !isNaN(pdfBytes.length)) {
  8345. params[key] = new Uint8Array(pdfBytes);
  8346. } else if (isArrayBuffer(pdfBytes)) {
  8347. params[key] = new Uint8Array(pdfBytes);
  8348. } else {
  8349. error('Invalid PDF binary data: either typed array, string or ' +
  8350. 'array-like object is expected in the data property.');
  8351. }
  8352. continue;
  8353. }
  8354. params[key] = source[key];
  8355. }
  8356. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8357. if (!worker) {
  8358. // Worker was not provided -- creating and owning our own.
  8359. worker = new PDFWorker();
  8360. task._worker = worker;
  8361. }
  8362. var docId = task.docId;
  8363. worker.promise.then(function () {
  8364. if (task.destroyed) {
  8365. throw new Error('Loading aborted');
  8366. }
  8367. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8368. function (workerId) {
  8369. if (task.destroyed) {
  8370. throw new Error('Loading aborted');
  8371. }
  8372. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8373. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8374. task._transport = transport;
  8375. messageHandler.send('Ready', null);
  8376. });
  8377. }).catch(task._capability.reject);
  8378. return task;
  8379. }
  8380. /**
  8381. * Starts fetching of specified PDF document/data.
  8382. * @param {PDFWorker} worker
  8383. * @param {Object} source
  8384. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8385. * @param {string} docId Unique document id, used as MessageHandler id.
  8386. * @returns {Promise} The promise, which is resolved when worker id of
  8387. * MessageHandler is known.
  8388. * @private
  8389. */
  8390. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8391. if (worker.destroyed) {
  8392. return Promise.reject(new Error('Worker was destroyed'));
  8393. }
  8394. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8395. source.disableStream = getDefaultSetting('disableStream');
  8396. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8397. if (pdfDataRangeTransport) {
  8398. source.length = pdfDataRangeTransport.length;
  8399. source.initialData = pdfDataRangeTransport.initialData;
  8400. }
  8401. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8402. docId: docId,
  8403. source: source,
  8404. disableRange: getDefaultSetting('disableRange'),
  8405. maxImageSize: getDefaultSetting('maxImageSize'),
  8406. cMapUrl: getDefaultSetting('cMapUrl'),
  8407. cMapPacked: getDefaultSetting('cMapPacked'),
  8408. disableFontFace: getDefaultSetting('disableFontFace'),
  8409. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8410. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8411. !isPostMessageTransfersDisabled,
  8412. }).then(function (workerId) {
  8413. if (worker.destroyed) {
  8414. throw new Error('Worker was destroyed');
  8415. }
  8416. return workerId;
  8417. });
  8418. }
  8419. /**
  8420. * PDF document loading operation.
  8421. * @class
  8422. * @alias PDFDocumentLoadingTask
  8423. */
  8424. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8425. var nextDocumentId = 0;
  8426. /** @constructs PDFDocumentLoadingTask */
  8427. function PDFDocumentLoadingTask() {
  8428. this._capability = createPromiseCapability();
  8429. this._transport = null;
  8430. this._worker = null;
  8431. /**
  8432. * Unique document loading task id -- used in MessageHandlers.
  8433. * @type {string}
  8434. */
  8435. this.docId = 'd' + (nextDocumentId++);
  8436. /**
  8437. * Shows if loading task is destroyed.
  8438. * @type {boolean}
  8439. */
  8440. this.destroyed = false;
  8441. /**
  8442. * Callback to request a password if wrong or no password was provided.
  8443. * The callback receives two parameters: function that needs to be called
  8444. * with new password and reason (see {PasswordResponses}).
  8445. */
  8446. this.onPassword = null;
  8447. /**
  8448. * Callback to be able to monitor the loading progress of the PDF file
  8449. * (necessary to implement e.g. a loading bar). The callback receives
  8450. * an {Object} with the properties: {number} loaded and {number} total.
  8451. */
  8452. this.onProgress = null;
  8453. /**
  8454. * Callback to when unsupported feature is used. The callback receives
  8455. * an {UNSUPPORTED_FEATURES} argument.
  8456. */
  8457. this.onUnsupportedFeature = null;
  8458. }
  8459. PDFDocumentLoadingTask.prototype =
  8460. /** @lends PDFDocumentLoadingTask.prototype */ {
  8461. /**
  8462. * @return {Promise}
  8463. */
  8464. get promise() {
  8465. return this._capability.promise;
  8466. },
  8467. /**
  8468. * Aborts all network requests and destroys worker.
  8469. * @return {Promise} A promise that is resolved after destruction activity
  8470. * is completed.
  8471. */
  8472. destroy: function () {
  8473. this.destroyed = true;
  8474. var transportDestroyed = !this._transport ? Promise.resolve() :
  8475. this._transport.destroy();
  8476. return transportDestroyed.then(function () {
  8477. this._transport = null;
  8478. if (this._worker) {
  8479. this._worker.destroy();
  8480. this._worker = null;
  8481. }
  8482. }.bind(this));
  8483. },
  8484. /**
  8485. * Registers callbacks to indicate the document loading completion.
  8486. *
  8487. * @param {function} onFulfilled The callback for the loading completion.
  8488. * @param {function} onRejected The callback for the loading failure.
  8489. * @return {Promise} A promise that is resolved after the onFulfilled or
  8490. * onRejected callback.
  8491. */
  8492. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8493. return this.promise.then.apply(this.promise, arguments);
  8494. }
  8495. };
  8496. return PDFDocumentLoadingTask;
  8497. })();
  8498. /**
  8499. * Abstract class to support range requests file loading.
  8500. * @class
  8501. * @alias PDFDataRangeTransport
  8502. * @param {number} length
  8503. * @param {Uint8Array} initialData
  8504. */
  8505. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8506. function PDFDataRangeTransport(length, initialData) {
  8507. this.length = length;
  8508. this.initialData = initialData;
  8509. this._rangeListeners = [];
  8510. this._progressListeners = [];
  8511. this._progressiveReadListeners = [];
  8512. this._readyCapability = createPromiseCapability();
  8513. }
  8514. PDFDataRangeTransport.prototype =
  8515. /** @lends PDFDataRangeTransport.prototype */ {
  8516. addRangeListener:
  8517. function PDFDataRangeTransport_addRangeListener(listener) {
  8518. this._rangeListeners.push(listener);
  8519. },
  8520. addProgressListener:
  8521. function PDFDataRangeTransport_addProgressListener(listener) {
  8522. this._progressListeners.push(listener);
  8523. },
  8524. addProgressiveReadListener:
  8525. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8526. this._progressiveReadListeners.push(listener);
  8527. },
  8528. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8529. var listeners = this._rangeListeners;
  8530. for (var i = 0, n = listeners.length; i < n; ++i) {
  8531. listeners[i](begin, chunk);
  8532. }
  8533. },
  8534. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8535. this._readyCapability.promise.then(function () {
  8536. var listeners = this._progressListeners;
  8537. for (var i = 0, n = listeners.length; i < n; ++i) {
  8538. listeners[i](loaded);
  8539. }
  8540. }.bind(this));
  8541. },
  8542. onDataProgressiveRead:
  8543. function PDFDataRangeTransport_onDataProgress(chunk) {
  8544. this._readyCapability.promise.then(function () {
  8545. var listeners = this._progressiveReadListeners;
  8546. for (var i = 0, n = listeners.length; i < n; ++i) {
  8547. listeners[i](chunk);
  8548. }
  8549. }.bind(this));
  8550. },
  8551. transportReady: function PDFDataRangeTransport_transportReady() {
  8552. this._readyCapability.resolve();
  8553. },
  8554. requestDataRange:
  8555. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8556. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8557. },
  8558. abort: function PDFDataRangeTransport_abort() {
  8559. }
  8560. };
  8561. return PDFDataRangeTransport;
  8562. })();
  8563. /**
  8564. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8565. * properties that can be read synchronously.
  8566. * @class
  8567. * @alias PDFDocumentProxy
  8568. */
  8569. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8570. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8571. this.pdfInfo = pdfInfo;
  8572. this.transport = transport;
  8573. this.loadingTask = loadingTask;
  8574. }
  8575. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8576. /**
  8577. * @return {number} Total number of pages the PDF contains.
  8578. */
  8579. get numPages() {
  8580. return this.pdfInfo.numPages;
  8581. },
  8582. /**
  8583. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8584. * unique.
  8585. */
  8586. get fingerprint() {
  8587. return this.pdfInfo.fingerprint;
  8588. },
  8589. /**
  8590. * @param {number} pageNumber The page number to get. The first page is 1.
  8591. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8592. * object.
  8593. */
  8594. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8595. return this.transport.getPage(pageNumber);
  8596. },
  8597. /**
  8598. * @param {{num: number, gen: number}} ref The page reference. Must have
  8599. * the 'num' and 'gen' properties.
  8600. * @return {Promise} A promise that is resolved with the page index that is
  8601. * associated with the reference.
  8602. */
  8603. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8604. return this.transport.getPageIndex(ref);
  8605. },
  8606. /**
  8607. * @return {Promise} A promise that is resolved with a lookup table for
  8608. * mapping named destinations to reference numbers.
  8609. *
  8610. * This can be slow for large documents: use getDestination instead
  8611. */
  8612. getDestinations: function PDFDocumentProxy_getDestinations() {
  8613. return this.transport.getDestinations();
  8614. },
  8615. /**
  8616. * @param {string} id The named destination to get.
  8617. * @return {Promise} A promise that is resolved with all information
  8618. * of the given named destination.
  8619. */
  8620. getDestination: function PDFDocumentProxy_getDestination(id) {
  8621. return this.transport.getDestination(id);
  8622. },
  8623. /**
  8624. * @return {Promise} A promise that is resolved with:
  8625. * an Array containing the pageLabels that correspond to the pageIndexes,
  8626. * or `null` when no pageLabels are present in the PDF file.
  8627. */
  8628. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8629. return this.transport.getPageLabels();
  8630. },
  8631. /**
  8632. * @return {Promise} A promise that is resolved with a lookup table for
  8633. * mapping named attachments to their content.
  8634. */
  8635. getAttachments: function PDFDocumentProxy_getAttachments() {
  8636. return this.transport.getAttachments();
  8637. },
  8638. /**
  8639. * @return {Promise} A promise that is resolved with an array of all the
  8640. * JavaScript strings in the name tree.
  8641. */
  8642. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8643. return this.transport.getJavaScript();
  8644. },
  8645. /**
  8646. * @return {Promise} A promise that is resolved with an {Array} that is a
  8647. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8648. * [
  8649. * {
  8650. * title: string,
  8651. * bold: boolean,
  8652. * italic: boolean,
  8653. * color: rgb Uint8Array,
  8654. * dest: dest obj,
  8655. * url: string,
  8656. * items: array of more items like this
  8657. * },
  8658. * ...
  8659. * ].
  8660. */
  8661. getOutline: function PDFDocumentProxy_getOutline() {
  8662. return this.transport.getOutline();
  8663. },
  8664. /**
  8665. * @return {Promise} A promise that is resolved with an {Object} that has
  8666. * info and metadata properties. Info is an {Object} filled with anything
  8667. * available in the information dictionary and similarly metadata is a
  8668. * {Metadata} object with information from the metadata section of the PDF.
  8669. */
  8670. getMetadata: function PDFDocumentProxy_getMetadata() {
  8671. return this.transport.getMetadata();
  8672. },
  8673. /**
  8674. * @return {Promise} A promise that is resolved with a TypedArray that has
  8675. * the raw data from the PDF.
  8676. */
  8677. getData: function PDFDocumentProxy_getData() {
  8678. return this.transport.getData();
  8679. },
  8680. /**
  8681. * @return {Promise} A promise that is resolved when the document's data
  8682. * is loaded. It is resolved with an {Object} that contains the length
  8683. * property that indicates size of the PDF data in bytes.
  8684. */
  8685. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8686. return this.transport.downloadInfoCapability.promise;
  8687. },
  8688. /**
  8689. * @return {Promise} A promise this is resolved with current stats about
  8690. * document structures (see {@link PDFDocumentStats}).
  8691. */
  8692. getStats: function PDFDocumentProxy_getStats() {
  8693. return this.transport.getStats();
  8694. },
  8695. /**
  8696. * Cleans up resources allocated by the document, e.g. created @font-face.
  8697. */
  8698. cleanup: function PDFDocumentProxy_cleanup() {
  8699. this.transport.startCleanup();
  8700. },
  8701. /**
  8702. * Destroys current document instance and terminates worker.
  8703. */
  8704. destroy: function PDFDocumentProxy_destroy() {
  8705. return this.loadingTask.destroy();
  8706. }
  8707. };
  8708. return PDFDocumentProxy;
  8709. })();
  8710. /**
  8711. * Page getTextContent parameters.
  8712. *
  8713. * @typedef {Object} getTextContentParameters
  8714. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8715. * whitespace with standard spaces (0x20). The default value is `false`.
  8716. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8717. * same line {@link TextItem}'s. The default value is `false`.
  8718. */
  8719. /**
  8720. * Page text content.
  8721. *
  8722. * @typedef {Object} TextContent
  8723. * @property {array} items - array of {@link TextItem}
  8724. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8725. * name.
  8726. */
  8727. /**
  8728. * Page text content part.
  8729. *
  8730. * @typedef {Object} TextItem
  8731. * @property {string} str - text content.
  8732. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8733. * @property {array} transform - transformation matrix.
  8734. * @property {number} width - width in device space.
  8735. * @property {number} height - height in device space.
  8736. * @property {string} fontName - font name used by pdf.js for converted font.
  8737. */
  8738. /**
  8739. * Text style.
  8740. *
  8741. * @typedef {Object} TextStyle
  8742. * @property {number} ascent - font ascent.
  8743. * @property {number} descent - font descent.
  8744. * @property {boolean} vertical - text is in vertical mode.
  8745. * @property {string} fontFamily - possible font family
  8746. */
  8747. /**
  8748. * Page annotation parameters.
  8749. *
  8750. * @typedef {Object} GetAnnotationsParameters
  8751. * @param {string} intent - Determines the annotations that will be fetched,
  8752. * can be either 'display' (viewable annotations) or 'print'
  8753. * (printable annotations).
  8754. * If the parameter is omitted, all annotations are fetched.
  8755. */
  8756. /**
  8757. * Page render parameters.
  8758. *
  8759. * @typedef {Object} RenderParameters
  8760. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8761. * @property {PageViewport} viewport - Rendering viewport obtained by
  8762. * calling of PDFPage.getViewport method.
  8763. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8764. * (default value is 'display').
  8765. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  8766. * interactive form elements are rendered in the display
  8767. * layer. If so, we do not render them on canvas as well.
  8768. * @property {Array} transform - (optional) Additional transform, applied
  8769. * just before viewport transform.
  8770. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8771. * endLayout and appendImage functions.
  8772. * @property {function} continueCallback - (deprecated) A function that will be
  8773. * called each time the rendering is paused. To continue
  8774. * rendering call the function that is the first argument
  8775. * to the callback.
  8776. */
  8777. /**
  8778. * PDF page operator list.
  8779. *
  8780. * @typedef {Object} PDFOperatorList
  8781. * @property {Array} fnArray - Array containing the operator functions.
  8782. * @property {Array} argsArray - Array containing the arguments of the
  8783. * functions.
  8784. */
  8785. /**
  8786. * Proxy to a PDFPage in the worker thread.
  8787. * @class
  8788. * @alias PDFPageProxy
  8789. */
  8790. var PDFPageProxy = (function PDFPageProxyClosure() {
  8791. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8792. this.pageIndex = pageIndex;
  8793. this.pageInfo = pageInfo;
  8794. this.transport = transport;
  8795. this.stats = new StatTimer();
  8796. this.stats.enabled = getDefaultSetting('enableStats');
  8797. this.commonObjs = transport.commonObjs;
  8798. this.objs = new PDFObjects();
  8799. this.cleanupAfterRender = false;
  8800. this.pendingCleanup = false;
  8801. this.intentStates = Object.create(null);
  8802. this.destroyed = false;
  8803. }
  8804. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8805. /**
  8806. * @return {number} Page number of the page. First page is 1.
  8807. */
  8808. get pageNumber() {
  8809. return this.pageIndex + 1;
  8810. },
  8811. /**
  8812. * @return {number} The number of degrees the page is rotated clockwise.
  8813. */
  8814. get rotate() {
  8815. return this.pageInfo.rotate;
  8816. },
  8817. /**
  8818. * @return {Object} The reference that points to this page. It has 'num' and
  8819. * 'gen' properties.
  8820. */
  8821. get ref() {
  8822. return this.pageInfo.ref;
  8823. },
  8824. /**
  8825. * @return {Array} An array of the visible portion of the PDF page in the
  8826. * user space units - [x1, y1, x2, y2].
  8827. */
  8828. get view() {
  8829. return this.pageInfo.view;
  8830. },
  8831. /**
  8832. * @param {number} scale The desired scale of the viewport.
  8833. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8834. * defaults to the page rotation.
  8835. * @return {PageViewport} Contains 'width' and 'height' properties
  8836. * along with transforms required for rendering.
  8837. */
  8838. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8839. if (arguments.length < 2) {
  8840. rotate = this.rotate;
  8841. }
  8842. return new PageViewport(this.view, scale, rotate, 0, 0);
  8843. },
  8844. /**
  8845. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8846. * @return {Promise} A promise that is resolved with an {Array} of the
  8847. * annotation objects.
  8848. */
  8849. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8850. var intent = (params && params.intent) || null;
  8851. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8852. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8853. intent);
  8854. this.annotationsIntent = intent;
  8855. }
  8856. return this.annotationsPromise;
  8857. },
  8858. /**
  8859. * Begins the process of rendering a page to the desired context.
  8860. * @param {RenderParameters} params Page render parameters.
  8861. * @return {RenderTask} An object that contains the promise, which
  8862. * is resolved when the page finishes rendering.
  8863. */
  8864. render: function PDFPageProxy_render(params) {
  8865. var stats = this.stats;
  8866. stats.time('Overall');
  8867. // If there was a pending destroy cancel it so no cleanup happens during
  8868. // this call to render.
  8869. this.pendingCleanup = false;
  8870. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8871. var renderInteractiveForms = (params.renderInteractiveForms === true ?
  8872. true : /* Default */ false);
  8873. if (!this.intentStates[renderingIntent]) {
  8874. this.intentStates[renderingIntent] = Object.create(null);
  8875. }
  8876. var intentState = this.intentStates[renderingIntent];
  8877. // If there's no displayReadyCapability yet, then the operatorList
  8878. // was never requested before. Make the request and create the promise.
  8879. if (!intentState.displayReadyCapability) {
  8880. intentState.receivingOperatorList = true;
  8881. intentState.displayReadyCapability = createPromiseCapability();
  8882. intentState.operatorList = {
  8883. fnArray: [],
  8884. argsArray: [],
  8885. lastChunk: false
  8886. };
  8887. this.stats.time('Page Request');
  8888. this.transport.messageHandler.send('RenderPageRequest', {
  8889. pageIndex: this.pageNumber - 1,
  8890. intent: renderingIntent,
  8891. renderInteractiveForms: renderInteractiveForms,
  8892. });
  8893. }
  8894. var internalRenderTask = new InternalRenderTask(complete, params,
  8895. this.objs,
  8896. this.commonObjs,
  8897. intentState.operatorList,
  8898. this.pageNumber);
  8899. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8900. if (!intentState.renderTasks) {
  8901. intentState.renderTasks = [];
  8902. }
  8903. intentState.renderTasks.push(internalRenderTask);
  8904. var renderTask = internalRenderTask.task;
  8905. // Obsolete parameter support
  8906. if (params.continueCallback) {
  8907. deprecated('render is used with continueCallback parameter');
  8908. renderTask.onContinue = params.continueCallback;
  8909. }
  8910. var self = this;
  8911. intentState.displayReadyCapability.promise.then(
  8912. function pageDisplayReadyPromise(transparency) {
  8913. if (self.pendingCleanup) {
  8914. complete();
  8915. return;
  8916. }
  8917. stats.time('Rendering');
  8918. internalRenderTask.initializeGraphics(transparency);
  8919. internalRenderTask.operatorListChanged();
  8920. },
  8921. function pageDisplayReadPromiseError(reason) {
  8922. complete(reason);
  8923. }
  8924. );
  8925. function complete(error) {
  8926. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8927. if (i >= 0) {
  8928. intentState.renderTasks.splice(i, 1);
  8929. }
  8930. if (self.cleanupAfterRender) {
  8931. self.pendingCleanup = true;
  8932. }
  8933. self._tryCleanup();
  8934. if (error) {
  8935. internalRenderTask.capability.reject(error);
  8936. } else {
  8937. internalRenderTask.capability.resolve();
  8938. }
  8939. stats.timeEnd('Rendering');
  8940. stats.timeEnd('Overall');
  8941. }
  8942. return renderTask;
  8943. },
  8944. /**
  8945. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8946. * object that represents page's operator list.
  8947. */
  8948. getOperatorList: function PDFPageProxy_getOperatorList() {
  8949. function operatorListChanged() {
  8950. if (intentState.operatorList.lastChunk) {
  8951. intentState.opListReadCapability.resolve(intentState.operatorList);
  8952. var i = intentState.renderTasks.indexOf(opListTask);
  8953. if (i >= 0) {
  8954. intentState.renderTasks.splice(i, 1);
  8955. }
  8956. }
  8957. }
  8958. var renderingIntent = 'oplist';
  8959. if (!this.intentStates[renderingIntent]) {
  8960. this.intentStates[renderingIntent] = Object.create(null);
  8961. }
  8962. var intentState = this.intentStates[renderingIntent];
  8963. var opListTask;
  8964. if (!intentState.opListReadCapability) {
  8965. opListTask = {};
  8966. opListTask.operatorListChanged = operatorListChanged;
  8967. intentState.receivingOperatorList = true;
  8968. intentState.opListReadCapability = createPromiseCapability();
  8969. intentState.renderTasks = [];
  8970. intentState.renderTasks.push(opListTask);
  8971. intentState.operatorList = {
  8972. fnArray: [],
  8973. argsArray: [],
  8974. lastChunk: false
  8975. };
  8976. this.transport.messageHandler.send('RenderPageRequest', {
  8977. pageIndex: this.pageIndex,
  8978. intent: renderingIntent
  8979. });
  8980. }
  8981. return intentState.opListReadCapability.promise;
  8982. },
  8983. /**
  8984. * @param {getTextContentParameters} params - getTextContent parameters.
  8985. * @return {Promise} That is resolved a {@link TextContent}
  8986. * object that represent the page text content.
  8987. */
  8988. getTextContent: function PDFPageProxy_getTextContent(params) {
  8989. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8990. pageIndex: this.pageNumber - 1,
  8991. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8992. true : /* Default */ false),
  8993. combineTextItems: (params && params.disableCombineTextItems === true ?
  8994. false : /* Default */ true),
  8995. });
  8996. },
  8997. /**
  8998. * Destroys page object.
  8999. */
  9000. _destroy: function PDFPageProxy_destroy() {
  9001. this.destroyed = true;
  9002. this.transport.pageCache[this.pageIndex] = null;
  9003. var waitOn = [];
  9004. Object.keys(this.intentStates).forEach(function(intent) {
  9005. if (intent === 'oplist') {
  9006. // Avoid errors below, since the renderTasks are just stubs.
  9007. return;
  9008. }
  9009. var intentState = this.intentStates[intent];
  9010. intentState.renderTasks.forEach(function(renderTask) {
  9011. var renderCompleted = renderTask.capability.promise.
  9012. catch(function () {}); // ignoring failures
  9013. waitOn.push(renderCompleted);
  9014. renderTask.cancel();
  9015. });
  9016. }, this);
  9017. this.objs.clear();
  9018. this.annotationsPromise = null;
  9019. this.pendingCleanup = false;
  9020. return Promise.all(waitOn);
  9021. },
  9022. /**
  9023. * Cleans up resources allocated by the page. (deprecated)
  9024. */
  9025. destroy: function() {
  9026. deprecated('page destroy method, use cleanup() instead');
  9027. this.cleanup();
  9028. },
  9029. /**
  9030. * Cleans up resources allocated by the page.
  9031. */
  9032. cleanup: function PDFPageProxy_cleanup() {
  9033. this.pendingCleanup = true;
  9034. this._tryCleanup();
  9035. },
  9036. /**
  9037. * For internal use only. Attempts to clean up if rendering is in a state
  9038. * where that's possible.
  9039. * @ignore
  9040. */
  9041. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9042. if (!this.pendingCleanup ||
  9043. Object.keys(this.intentStates).some(function(intent) {
  9044. var intentState = this.intentStates[intent];
  9045. return (intentState.renderTasks.length !== 0 ||
  9046. intentState.receivingOperatorList);
  9047. }, this)) {
  9048. return;
  9049. }
  9050. Object.keys(this.intentStates).forEach(function(intent) {
  9051. delete this.intentStates[intent];
  9052. }, this);
  9053. this.objs.clear();
  9054. this.annotationsPromise = null;
  9055. this.pendingCleanup = false;
  9056. },
  9057. /**
  9058. * For internal use only.
  9059. * @ignore
  9060. */
  9061. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  9062. intent) {
  9063. var intentState = this.intentStates[intent];
  9064. // TODO Refactor RenderPageRequest to separate rendering
  9065. // and operator list logic
  9066. if (intentState.displayReadyCapability) {
  9067. intentState.displayReadyCapability.resolve(transparency);
  9068. }
  9069. },
  9070. /**
  9071. * For internal use only.
  9072. * @ignore
  9073. */
  9074. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  9075. intent) {
  9076. var intentState = this.intentStates[intent];
  9077. var i, ii;
  9078. // Add the new chunk to the current operator list.
  9079. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9080. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9081. intentState.operatorList.argsArray.push(
  9082. operatorListChunk.argsArray[i]);
  9083. }
  9084. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9085. // Notify all the rendering tasks there are more operators to be consumed.
  9086. for (i = 0; i < intentState.renderTasks.length; i++) {
  9087. intentState.renderTasks[i].operatorListChanged();
  9088. }
  9089. if (operatorListChunk.lastChunk) {
  9090. intentState.receivingOperatorList = false;
  9091. this._tryCleanup();
  9092. }
  9093. }
  9094. };
  9095. return PDFPageProxy;
  9096. })();
  9097. /**
  9098. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9099. * WorkerTransport for them. If creation of a web worker is not possible,
  9100. * a "fake" worker will be used instead.
  9101. * @class
  9102. */
  9103. var PDFWorker = (function PDFWorkerClosure() {
  9104. var nextFakeWorkerId = 0;
  9105. function getWorkerSrc() {
  9106. if (typeof workerSrc !== 'undefined') {
  9107. return workerSrc;
  9108. }
  9109. if (getDefaultSetting('workerSrc')) {
  9110. return getDefaultSetting('workerSrc');
  9111. }
  9112. if (pdfjsFilePath) {
  9113. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9114. }
  9115. error('No PDFJS.workerSrc specified');
  9116. }
  9117. var fakeWorkerFilesLoadedCapability;
  9118. // Loads worker code into main thread.
  9119. function setupFakeWorkerGlobal() {
  9120. var WorkerMessageHandler;
  9121. if (!fakeWorkerFilesLoadedCapability) {
  9122. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9123. // In the developer build load worker_loader which in turn loads all the
  9124. // other files and resolves the promise. In production only the
  9125. // pdf.worker.js file is needed.
  9126. var loader = fakeWorkerFilesLoader || function (callback) {
  9127. Util.loadScript(getWorkerSrc(), function () {
  9128. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9129. });
  9130. };
  9131. loader(fakeWorkerFilesLoadedCapability.resolve);
  9132. }
  9133. return fakeWorkerFilesLoadedCapability.promise;
  9134. }
  9135. function FakeWorkerPort(defer) {
  9136. this._listeners = [];
  9137. this._defer = defer;
  9138. this._deferred = Promise.resolve(undefined);
  9139. }
  9140. FakeWorkerPort.prototype = {
  9141. postMessage: function (obj, transfers) {
  9142. function cloneValue(value) {
  9143. // Trying to perform a structured clone close to the spec, including
  9144. // transfers.
  9145. if (typeof value !== 'object' || value === null) {
  9146. return value;
  9147. }
  9148. if (cloned.has(value)) { // already cloned the object
  9149. return cloned.get(value);
  9150. }
  9151. var result;
  9152. var buffer;
  9153. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9154. // We found object with ArrayBuffer (typed array).
  9155. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9156. if (value === buffer) {
  9157. // Special case when we are faking typed arrays in compatibility.js.
  9158. result = value;
  9159. } else if (transferable) {
  9160. result = new value.constructor(buffer, value.byteOffset,
  9161. value.byteLength);
  9162. } else {
  9163. result = new value.constructor(value);
  9164. }
  9165. cloned.set(value, result);
  9166. return result;
  9167. }
  9168. result = isArray(value) ? [] : {};
  9169. cloned.set(value, result); // adding to cache now for cyclic references
  9170. // Cloning all value and object properties, however ignoring properties
  9171. // defined via getter.
  9172. for (var i in value) {
  9173. var desc, p = value;
  9174. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9175. p = Object.getPrototypeOf(p);
  9176. }
  9177. if (typeof desc.value === 'undefined' ||
  9178. typeof desc.value === 'function') {
  9179. continue;
  9180. }
  9181. result[i] = cloneValue(desc.value);
  9182. }
  9183. return result;
  9184. }
  9185. if (!this._defer) {
  9186. this._listeners.forEach(function (listener) {
  9187. listener.call(this, {data: obj});
  9188. }, this);
  9189. return;
  9190. }
  9191. var cloned = new WeakMap();
  9192. var e = {data: cloneValue(obj)};
  9193. this._deferred.then(function () {
  9194. this._listeners.forEach(function (listener) {
  9195. listener.call(this, e);
  9196. }, this);
  9197. }.bind(this));
  9198. },
  9199. addEventListener: function (name, listener) {
  9200. this._listeners.push(listener);
  9201. },
  9202. removeEventListener: function (name, listener) {
  9203. var i = this._listeners.indexOf(listener);
  9204. this._listeners.splice(i, 1);
  9205. },
  9206. terminate: function () {
  9207. this._listeners = [];
  9208. }
  9209. };
  9210. function createCDNWrapper(url) {
  9211. // We will rely on blob URL's property to specify origin.
  9212. // We want this function to fail in case if createObjectURL or Blob do not
  9213. // exist or fail for some reason -- our Worker creation will fail anyway.
  9214. var wrapper = 'importScripts(\'' + url + '\');';
  9215. return URL.createObjectURL(new Blob([wrapper]));
  9216. }
  9217. function PDFWorker(name) {
  9218. this.name = name;
  9219. this.destroyed = false;
  9220. this._readyCapability = createPromiseCapability();
  9221. this._port = null;
  9222. this._webWorker = null;
  9223. this._messageHandler = null;
  9224. this._initialize();
  9225. }
  9226. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9227. get promise() {
  9228. return this._readyCapability.promise;
  9229. },
  9230. get port() {
  9231. return this._port;
  9232. },
  9233. get messageHandler() {
  9234. return this._messageHandler;
  9235. },
  9236. _initialize: function PDFWorker_initialize() {
  9237. // If worker support isn't disabled explicit and the browser has worker
  9238. // support, create a new web worker and test if it/the browser fulfills
  9239. // all requirements to run parts of pdf.js in a web worker.
  9240. // Right now, the requirement is, that an Uint8Array is still an
  9241. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9242. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9243. typeof Worker !== 'undefined') {
  9244. var workerSrc = getWorkerSrc();
  9245. try {
  9246. // Wraps workerSrc path into blob URL, if the former does not belong
  9247. // to the same origin.
  9248. if (!isSameOrigin(window.location.href, workerSrc)) {
  9249. workerSrc = createCDNWrapper(
  9250. new URL(workerSrc, window.location).href);
  9251. }
  9252. // Some versions of FF can't create a worker on localhost, see:
  9253. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9254. var worker = new Worker(workerSrc);
  9255. var messageHandler = new MessageHandler('main', 'worker', worker);
  9256. var terminateEarly = function() {
  9257. worker.removeEventListener('error', onWorkerError);
  9258. messageHandler.destroy();
  9259. worker.terminate();
  9260. if (this.destroyed) {
  9261. this._readyCapability.reject(new Error('Worker was destroyed'));
  9262. } else {
  9263. // Fall back to fake worker if the termination is caused by an
  9264. // error (e.g. NetworkError / SecurityError).
  9265. this._setupFakeWorker();
  9266. }
  9267. }.bind(this);
  9268. var onWorkerError = function(event) {
  9269. if (!this._webWorker) {
  9270. // Worker failed to initialize due to an error. Clean up and fall
  9271. // back to the fake worker.
  9272. terminateEarly();
  9273. }
  9274. }.bind(this);
  9275. worker.addEventListener('error', onWorkerError);
  9276. messageHandler.on('test', function PDFWorker_test(data) {
  9277. worker.removeEventListener('error', onWorkerError);
  9278. if (this.destroyed) {
  9279. terminateEarly();
  9280. return; // worker was destroyed
  9281. }
  9282. var supportTypedArray = data && data.supportTypedArray;
  9283. if (supportTypedArray) {
  9284. this._messageHandler = messageHandler;
  9285. this._port = worker;
  9286. this._webWorker = worker;
  9287. if (!data.supportTransfers) {
  9288. isPostMessageTransfersDisabled = true;
  9289. }
  9290. this._readyCapability.resolve();
  9291. // Send global setting, e.g. verbosity level.
  9292. messageHandler.send('configure', {
  9293. verbosity: getVerbosityLevel()
  9294. });
  9295. } else {
  9296. this._setupFakeWorker();
  9297. messageHandler.destroy();
  9298. worker.terminate();
  9299. }
  9300. }.bind(this));
  9301. messageHandler.on('console_log', function (data) {
  9302. console.log.apply(console, data);
  9303. });
  9304. messageHandler.on('console_error', function (data) {
  9305. console.error.apply(console, data);
  9306. });
  9307. messageHandler.on('ready', function (data) {
  9308. worker.removeEventListener('error', onWorkerError);
  9309. if (this.destroyed) {
  9310. terminateEarly();
  9311. return; // worker was destroyed
  9312. }
  9313. try {
  9314. sendTest();
  9315. } catch (e) {
  9316. // We need fallback to a faked worker.
  9317. this._setupFakeWorker();
  9318. }
  9319. }.bind(this));
  9320. var sendTest = function () {
  9321. var postMessageTransfers =
  9322. getDefaultSetting('postMessageTransfers') &&
  9323. !isPostMessageTransfersDisabled;
  9324. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9325. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9326. // typed array. Also, checking if we can use transfers.
  9327. try {
  9328. messageHandler.send('test', testObj, [testObj.buffer]);
  9329. } catch (ex) {
  9330. info('Cannot use postMessage transfers');
  9331. testObj[0] = 0;
  9332. messageHandler.send('test', testObj);
  9333. }
  9334. };
  9335. // It might take time for worker to initialize (especially when AMD
  9336. // loader is used). We will try to send test immediately, and then
  9337. // when 'ready' message will arrive. The worker shall process only
  9338. // first received 'test'.
  9339. sendTest();
  9340. return;
  9341. } catch (e) {
  9342. info('The worker has been disabled.');
  9343. }
  9344. }
  9345. // Either workers are disabled, not supported or have thrown an exception.
  9346. // Thus, we fallback to a faked worker.
  9347. this._setupFakeWorker();
  9348. },
  9349. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9350. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9351. warn('Setting up fake worker.');
  9352. isWorkerDisabled = true;
  9353. }
  9354. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9355. if (this.destroyed) {
  9356. this._readyCapability.reject(new Error('Worker was destroyed'));
  9357. return;
  9358. }
  9359. // We cannot turn on proper fake port simulation (this includes
  9360. // structured cloning) when typed arrays are not supported. Relying
  9361. // on a chance that messages will be sent in proper order.
  9362. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9363. var port = new FakeWorkerPort(isTypedArraysPresent);
  9364. this._port = port;
  9365. // All fake workers use the same port, making id unique.
  9366. var id = 'fake' + (nextFakeWorkerId++);
  9367. // If the main thread is our worker, setup the handling for the
  9368. // messages -- the main thread sends to it self.
  9369. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9370. WorkerMessageHandler.setup(workerHandler, port);
  9371. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9372. this._messageHandler = messageHandler;
  9373. this._readyCapability.resolve();
  9374. }.bind(this));
  9375. },
  9376. /**
  9377. * Destroys the worker instance.
  9378. */
  9379. destroy: function PDFWorker_destroy() {
  9380. this.destroyed = true;
  9381. if (this._webWorker) {
  9382. // We need to terminate only web worker created resource.
  9383. this._webWorker.terminate();
  9384. this._webWorker = null;
  9385. }
  9386. this._port = null;
  9387. if (this._messageHandler) {
  9388. this._messageHandler.destroy();
  9389. this._messageHandler = null;
  9390. }
  9391. }
  9392. };
  9393. return PDFWorker;
  9394. })();
  9395. /**
  9396. * For internal use only.
  9397. * @ignore
  9398. */
  9399. var WorkerTransport = (function WorkerTransportClosure() {
  9400. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9401. this.messageHandler = messageHandler;
  9402. this.loadingTask = loadingTask;
  9403. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9404. this.commonObjs = new PDFObjects();
  9405. this.fontLoader = new FontLoader(loadingTask.docId);
  9406. this.destroyed = false;
  9407. this.destroyCapability = null;
  9408. this.pageCache = [];
  9409. this.pagePromises = [];
  9410. this.downloadInfoCapability = createPromiseCapability();
  9411. this.setupMessageHandler();
  9412. }
  9413. WorkerTransport.prototype = {
  9414. destroy: function WorkerTransport_destroy() {
  9415. if (this.destroyCapability) {
  9416. return this.destroyCapability.promise;
  9417. }
  9418. this.destroyed = true;
  9419. this.destroyCapability = createPromiseCapability();
  9420. var waitOn = [];
  9421. // We need to wait for all renderings to be completed, e.g.
  9422. // timeout/rAF can take a long time.
  9423. this.pageCache.forEach(function (page) {
  9424. if (page) {
  9425. waitOn.push(page._destroy());
  9426. }
  9427. });
  9428. this.pageCache = [];
  9429. this.pagePromises = [];
  9430. var self = this;
  9431. // We also need to wait for the worker to finish its long running tasks.
  9432. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9433. waitOn.push(terminated);
  9434. Promise.all(waitOn).then(function () {
  9435. self.fontLoader.clear();
  9436. if (self.pdfDataRangeTransport) {
  9437. self.pdfDataRangeTransport.abort();
  9438. self.pdfDataRangeTransport = null;
  9439. }
  9440. if (self.messageHandler) {
  9441. self.messageHandler.destroy();
  9442. self.messageHandler = null;
  9443. }
  9444. self.destroyCapability.resolve();
  9445. }, this.destroyCapability.reject);
  9446. return this.destroyCapability.promise;
  9447. },
  9448. setupMessageHandler:
  9449. function WorkerTransport_setupMessageHandler() {
  9450. var messageHandler = this.messageHandler;
  9451. function updatePassword(password) {
  9452. messageHandler.send('UpdatePassword', password);
  9453. }
  9454. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9455. if (pdfDataRangeTransport) {
  9456. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9457. messageHandler.send('OnDataRange', {
  9458. begin: begin,
  9459. chunk: chunk
  9460. });
  9461. });
  9462. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9463. messageHandler.send('OnDataProgress', {
  9464. loaded: loaded
  9465. });
  9466. });
  9467. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9468. messageHandler.send('OnDataRange', {
  9469. chunk: chunk
  9470. });
  9471. });
  9472. messageHandler.on('RequestDataRange',
  9473. function transportDataRange(data) {
  9474. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9475. }, this);
  9476. }
  9477. messageHandler.on('GetDoc', function transportDoc(data) {
  9478. var pdfInfo = data.pdfInfo;
  9479. this.numPages = data.pdfInfo.numPages;
  9480. var loadingTask = this.loadingTask;
  9481. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9482. this.pdfDocument = pdfDocument;
  9483. loadingTask._capability.resolve(pdfDocument);
  9484. }, this);
  9485. messageHandler.on('NeedPassword',
  9486. function transportNeedPassword(exception) {
  9487. var loadingTask = this.loadingTask;
  9488. if (loadingTask.onPassword) {
  9489. return loadingTask.onPassword(updatePassword,
  9490. PasswordResponses.NEED_PASSWORD);
  9491. }
  9492. loadingTask._capability.reject(
  9493. new PasswordException(exception.message, exception.code));
  9494. }, this);
  9495. messageHandler.on('IncorrectPassword',
  9496. function transportIncorrectPassword(exception) {
  9497. var loadingTask = this.loadingTask;
  9498. if (loadingTask.onPassword) {
  9499. return loadingTask.onPassword(updatePassword,
  9500. PasswordResponses.INCORRECT_PASSWORD);
  9501. }
  9502. loadingTask._capability.reject(
  9503. new PasswordException(exception.message, exception.code));
  9504. }, this);
  9505. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9506. this.loadingTask._capability.reject(
  9507. new InvalidPDFException(exception.message));
  9508. }, this);
  9509. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9510. this.loadingTask._capability.reject(
  9511. new MissingPDFException(exception.message));
  9512. }, this);
  9513. messageHandler.on('UnexpectedResponse',
  9514. function transportUnexpectedResponse(exception) {
  9515. this.loadingTask._capability.reject(
  9516. new UnexpectedResponseException(exception.message, exception.status));
  9517. }, this);
  9518. messageHandler.on('UnknownError',
  9519. function transportUnknownError(exception) {
  9520. this.loadingTask._capability.reject(
  9521. new UnknownErrorException(exception.message, exception.details));
  9522. }, this);
  9523. messageHandler.on('DataLoaded', function transportPage(data) {
  9524. this.downloadInfoCapability.resolve(data);
  9525. }, this);
  9526. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9527. if (this.pdfDataRangeTransport) {
  9528. this.pdfDataRangeTransport.transportReady();
  9529. }
  9530. }, this);
  9531. messageHandler.on('StartRenderPage', function transportRender(data) {
  9532. if (this.destroyed) {
  9533. return; // Ignore any pending requests if the worker was terminated.
  9534. }
  9535. var page = this.pageCache[data.pageIndex];
  9536. page.stats.timeEnd('Page Request');
  9537. page._startRenderPage(data.transparency, data.intent);
  9538. }, this);
  9539. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9540. if (this.destroyed) {
  9541. return; // Ignore any pending requests if the worker was terminated.
  9542. }
  9543. var page = this.pageCache[data.pageIndex];
  9544. page._renderPageChunk(data.operatorList, data.intent);
  9545. }, this);
  9546. messageHandler.on('commonobj', function transportObj(data) {
  9547. if (this.destroyed) {
  9548. return; // Ignore any pending requests if the worker was terminated.
  9549. }
  9550. var id = data[0];
  9551. var type = data[1];
  9552. if (this.commonObjs.hasData(id)) {
  9553. return;
  9554. }
  9555. switch (type) {
  9556. case 'Font':
  9557. var exportedData = data[2];
  9558. if ('error' in exportedData) {
  9559. var exportedError = exportedData.error;
  9560. warn('Error during font loading: ' + exportedError);
  9561. this.commonObjs.resolve(id, exportedError);
  9562. break;
  9563. }
  9564. var fontRegistry = null;
  9565. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9566. globalScope['FontInspector'].enabled) {
  9567. fontRegistry = {
  9568. registerFont: function (font, url) {
  9569. globalScope['FontInspector'].fontAdded(font, url);
  9570. }
  9571. };
  9572. }
  9573. var font = new FontFaceObject(exportedData, {
  9574. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9575. disableFontFace: getDefaultSetting('disableFontFace'),
  9576. fontRegistry: fontRegistry
  9577. });
  9578. this.fontLoader.bind(
  9579. [font],
  9580. function fontReady(fontObjs) {
  9581. this.commonObjs.resolve(id, font);
  9582. }.bind(this)
  9583. );
  9584. break;
  9585. case 'FontPath':
  9586. this.commonObjs.resolve(id, data[2]);
  9587. break;
  9588. default:
  9589. error('Got unknown common object type ' + type);
  9590. }
  9591. }, this);
  9592. messageHandler.on('obj', function transportObj(data) {
  9593. if (this.destroyed) {
  9594. return; // Ignore any pending requests if the worker was terminated.
  9595. }
  9596. var id = data[0];
  9597. var pageIndex = data[1];
  9598. var type = data[2];
  9599. var pageProxy = this.pageCache[pageIndex];
  9600. var imageData;
  9601. if (pageProxy.objs.hasData(id)) {
  9602. return;
  9603. }
  9604. switch (type) {
  9605. case 'JpegStream':
  9606. imageData = data[3];
  9607. loadJpegStream(id, imageData, pageProxy.objs);
  9608. break;
  9609. case 'Image':
  9610. imageData = data[3];
  9611. pageProxy.objs.resolve(id, imageData);
  9612. // heuristics that will allow not to store large data
  9613. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9614. if (imageData && 'data' in imageData &&
  9615. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9616. pageProxy.cleanupAfterRender = true;
  9617. }
  9618. break;
  9619. default:
  9620. error('Got unknown object type ' + type);
  9621. }
  9622. }, this);
  9623. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9624. if (this.destroyed) {
  9625. return; // Ignore any pending requests if the worker was terminated.
  9626. }
  9627. var loadingTask = this.loadingTask;
  9628. if (loadingTask.onProgress) {
  9629. loadingTask.onProgress({
  9630. loaded: data.loaded,
  9631. total: data.total
  9632. });
  9633. }
  9634. }, this);
  9635. messageHandler.on('PageError', function transportError(data) {
  9636. if (this.destroyed) {
  9637. return; // Ignore any pending requests if the worker was terminated.
  9638. }
  9639. var page = this.pageCache[data.pageNum - 1];
  9640. var intentState = page.intentStates[data.intent];
  9641. if (intentState.displayReadyCapability) {
  9642. intentState.displayReadyCapability.reject(data.error);
  9643. } else {
  9644. error(data.error);
  9645. }
  9646. if (intentState.operatorList) {
  9647. // Mark operator list as complete.
  9648. intentState.operatorList.lastChunk = true;
  9649. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9650. intentState.renderTasks[i].operatorListChanged();
  9651. }
  9652. }
  9653. }, this);
  9654. messageHandler.on('UnsupportedFeature',
  9655. function transportUnsupportedFeature(data) {
  9656. if (this.destroyed) {
  9657. return; // Ignore any pending requests if the worker was terminated.
  9658. }
  9659. var featureId = data.featureId;
  9660. var loadingTask = this.loadingTask;
  9661. if (loadingTask.onUnsupportedFeature) {
  9662. loadingTask.onUnsupportedFeature(featureId);
  9663. }
  9664. _UnsupportedManager.notify(featureId);
  9665. }, this);
  9666. messageHandler.on('JpegDecode', function(data) {
  9667. if (this.destroyed) {
  9668. return Promise.reject(new Error('Worker was destroyed'));
  9669. }
  9670. var imageUrl = data[0];
  9671. var components = data[1];
  9672. if (components !== 3 && components !== 1) {
  9673. return Promise.reject(
  9674. new Error('Only 3 components or 1 component can be returned'));
  9675. }
  9676. return new Promise(function (resolve, reject) {
  9677. var img = new Image();
  9678. img.onload = function () {
  9679. var width = img.width;
  9680. var height = img.height;
  9681. var size = width * height;
  9682. var rgbaLength = size * 4;
  9683. var buf = new Uint8Array(size * components);
  9684. var tmpCanvas = createScratchCanvas(width, height);
  9685. var tmpCtx = tmpCanvas.getContext('2d');
  9686. tmpCtx.drawImage(img, 0, 0);
  9687. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9688. var i, j;
  9689. if (components === 3) {
  9690. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9691. buf[j] = data[i];
  9692. buf[j + 1] = data[i + 1];
  9693. buf[j + 2] = data[i + 2];
  9694. }
  9695. } else if (components === 1) {
  9696. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9697. buf[j] = data[i];
  9698. }
  9699. }
  9700. resolve({ data: buf, width: width, height: height});
  9701. };
  9702. img.onerror = function () {
  9703. reject(new Error('JpegDecode failed to load image'));
  9704. };
  9705. img.src = imageUrl;
  9706. });
  9707. }, this);
  9708. },
  9709. getData: function WorkerTransport_getData() {
  9710. return this.messageHandler.sendWithPromise('GetData', null);
  9711. },
  9712. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9713. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9714. return Promise.reject(new Error('Invalid page request'));
  9715. }
  9716. var pageIndex = pageNumber - 1;
  9717. if (pageIndex in this.pagePromises) {
  9718. return this.pagePromises[pageIndex];
  9719. }
  9720. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9721. pageIndex: pageIndex
  9722. }).then(function (pageInfo) {
  9723. if (this.destroyed) {
  9724. throw new Error('Transport destroyed');
  9725. }
  9726. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9727. this.pageCache[pageIndex] = page;
  9728. return page;
  9729. }.bind(this));
  9730. this.pagePromises[pageIndex] = promise;
  9731. return promise;
  9732. },
  9733. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9734. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9735. ref: ref,
  9736. }).catch(function (reason) {
  9737. return Promise.reject(new Error(reason));
  9738. });
  9739. },
  9740. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9741. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9742. pageIndex: pageIndex,
  9743. intent: intent,
  9744. });
  9745. },
  9746. getDestinations: function WorkerTransport_getDestinations() {
  9747. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9748. },
  9749. getDestination: function WorkerTransport_getDestination(id) {
  9750. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9751. },
  9752. getPageLabels: function WorkerTransport_getPageLabels() {
  9753. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9754. },
  9755. getAttachments: function WorkerTransport_getAttachments() {
  9756. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9757. },
  9758. getJavaScript: function WorkerTransport_getJavaScript() {
  9759. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9760. },
  9761. getOutline: function WorkerTransport_getOutline() {
  9762. return this.messageHandler.sendWithPromise('GetOutline', null);
  9763. },
  9764. getMetadata: function WorkerTransport_getMetadata() {
  9765. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9766. then(function transportMetadata(results) {
  9767. return {
  9768. info: results[0],
  9769. metadata: (results[1] ? new Metadata(results[1]) : null)
  9770. };
  9771. });
  9772. },
  9773. getStats: function WorkerTransport_getStats() {
  9774. return this.messageHandler.sendWithPromise('GetStats', null);
  9775. },
  9776. startCleanup: function WorkerTransport_startCleanup() {
  9777. this.messageHandler.sendWithPromise('Cleanup', null).
  9778. then(function endCleanup() {
  9779. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9780. var page = this.pageCache[i];
  9781. if (page) {
  9782. page.cleanup();
  9783. }
  9784. }
  9785. this.commonObjs.clear();
  9786. this.fontLoader.clear();
  9787. }.bind(this));
  9788. }
  9789. };
  9790. return WorkerTransport;
  9791. })();
  9792. /**
  9793. * A PDF document and page is built of many objects. E.g. there are objects
  9794. * for fonts, images, rendering code and such. These objects might get processed
  9795. * inside of a worker. The `PDFObjects` implements some basic functions to
  9796. * manage these objects.
  9797. * @ignore
  9798. */
  9799. var PDFObjects = (function PDFObjectsClosure() {
  9800. function PDFObjects() {
  9801. this.objs = Object.create(null);
  9802. }
  9803. PDFObjects.prototype = {
  9804. /**
  9805. * Internal function.
  9806. * Ensures there is an object defined for `objId`.
  9807. */
  9808. ensureObj: function PDFObjects_ensureObj(objId) {
  9809. if (this.objs[objId]) {
  9810. return this.objs[objId];
  9811. }
  9812. var obj = {
  9813. capability: createPromiseCapability(),
  9814. data: null,
  9815. resolved: false
  9816. };
  9817. this.objs[objId] = obj;
  9818. return obj;
  9819. },
  9820. /**
  9821. * If called *without* callback, this returns the data of `objId` but the
  9822. * object needs to be resolved. If it isn't, this function throws.
  9823. *
  9824. * If called *with* a callback, the callback is called with the data of the
  9825. * object once the object is resolved. That means, if you call this
  9826. * function and the object is already resolved, the callback gets called
  9827. * right away.
  9828. */
  9829. get: function PDFObjects_get(objId, callback) {
  9830. // If there is a callback, then the get can be async and the object is
  9831. // not required to be resolved right now
  9832. if (callback) {
  9833. this.ensureObj(objId).capability.promise.then(callback);
  9834. return null;
  9835. }
  9836. // If there isn't a callback, the user expects to get the resolved data
  9837. // directly.
  9838. var obj = this.objs[objId];
  9839. // If there isn't an object yet or the object isn't resolved, then the
  9840. // data isn't ready yet!
  9841. if (!obj || !obj.resolved) {
  9842. error('Requesting object that isn\'t resolved yet ' + objId);
  9843. }
  9844. return obj.data;
  9845. },
  9846. /**
  9847. * Resolves the object `objId` with optional `data`.
  9848. */
  9849. resolve: function PDFObjects_resolve(objId, data) {
  9850. var obj = this.ensureObj(objId);
  9851. obj.resolved = true;
  9852. obj.data = data;
  9853. obj.capability.resolve(data);
  9854. },
  9855. isResolved: function PDFObjects_isResolved(objId) {
  9856. var objs = this.objs;
  9857. if (!objs[objId]) {
  9858. return false;
  9859. } else {
  9860. return objs[objId].resolved;
  9861. }
  9862. },
  9863. hasData: function PDFObjects_hasData(objId) {
  9864. return this.isResolved(objId);
  9865. },
  9866. /**
  9867. * Returns the data of `objId` if object exists, null otherwise.
  9868. */
  9869. getData: function PDFObjects_getData(objId) {
  9870. var objs = this.objs;
  9871. if (!objs[objId] || !objs[objId].resolved) {
  9872. return null;
  9873. } else {
  9874. return objs[objId].data;
  9875. }
  9876. },
  9877. clear: function PDFObjects_clear() {
  9878. this.objs = Object.create(null);
  9879. }
  9880. };
  9881. return PDFObjects;
  9882. })();
  9883. /**
  9884. * Allows controlling of the rendering tasks.
  9885. * @class
  9886. * @alias RenderTask
  9887. */
  9888. var RenderTask = (function RenderTaskClosure() {
  9889. function RenderTask(internalRenderTask) {
  9890. this._internalRenderTask = internalRenderTask;
  9891. /**
  9892. * Callback for incremental rendering -- a function that will be called
  9893. * each time the rendering is paused. To continue rendering call the
  9894. * function that is the first argument to the callback.
  9895. * @type {function}
  9896. */
  9897. this.onContinue = null;
  9898. }
  9899. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9900. /**
  9901. * Promise for rendering task completion.
  9902. * @return {Promise}
  9903. */
  9904. get promise() {
  9905. return this._internalRenderTask.capability.promise;
  9906. },
  9907. /**
  9908. * Cancels the rendering task. If the task is currently rendering it will
  9909. * not be cancelled until graphics pauses with a timeout. The promise that
  9910. * this object extends will resolved when cancelled.
  9911. */
  9912. cancel: function RenderTask_cancel() {
  9913. this._internalRenderTask.cancel();
  9914. },
  9915. /**
  9916. * Registers callbacks to indicate the rendering task completion.
  9917. *
  9918. * @param {function} onFulfilled The callback for the rendering completion.
  9919. * @param {function} onRejected The callback for the rendering failure.
  9920. * @return {Promise} A promise that is resolved after the onFulfilled or
  9921. * onRejected callback.
  9922. */
  9923. then: function RenderTask_then(onFulfilled, onRejected) {
  9924. return this.promise.then.apply(this.promise, arguments);
  9925. }
  9926. };
  9927. return RenderTask;
  9928. })();
  9929. /**
  9930. * For internal use only.
  9931. * @ignore
  9932. */
  9933. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9934. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9935. pageNumber) {
  9936. this.callback = callback;
  9937. this.params = params;
  9938. this.objs = objs;
  9939. this.commonObjs = commonObjs;
  9940. this.operatorListIdx = null;
  9941. this.operatorList = operatorList;
  9942. this.pageNumber = pageNumber;
  9943. this.running = false;
  9944. this.graphicsReadyCallback = null;
  9945. this.graphicsReady = false;
  9946. this.useRequestAnimationFrame = false;
  9947. this.cancelled = false;
  9948. this.capability = createPromiseCapability();
  9949. this.task = new RenderTask(this);
  9950. // caching this-bound methods
  9951. this._continueBound = this._continue.bind(this);
  9952. this._scheduleNextBound = this._scheduleNext.bind(this);
  9953. this._nextBound = this._next.bind(this);
  9954. }
  9955. InternalRenderTask.prototype = {
  9956. initializeGraphics:
  9957. function InternalRenderTask_initializeGraphics(transparency) {
  9958. if (this.cancelled) {
  9959. return;
  9960. }
  9961. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9962. globalScope.StepperManager.enabled) {
  9963. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9964. this.stepper.init(this.operatorList);
  9965. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9966. }
  9967. var params = this.params;
  9968. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9969. this.objs, params.imageLayer);
  9970. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9971. this.operatorListIdx = 0;
  9972. this.graphicsReady = true;
  9973. if (this.graphicsReadyCallback) {
  9974. this.graphicsReadyCallback();
  9975. }
  9976. },
  9977. cancel: function InternalRenderTask_cancel() {
  9978. this.running = false;
  9979. this.cancelled = true;
  9980. this.callback('cancelled');
  9981. },
  9982. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9983. if (!this.graphicsReady) {
  9984. if (!this.graphicsReadyCallback) {
  9985. this.graphicsReadyCallback = this._continueBound;
  9986. }
  9987. return;
  9988. }
  9989. if (this.stepper) {
  9990. this.stepper.updateOperatorList(this.operatorList);
  9991. }
  9992. if (this.running) {
  9993. return;
  9994. }
  9995. this._continue();
  9996. },
  9997. _continue: function InternalRenderTask__continue() {
  9998. this.running = true;
  9999. if (this.cancelled) {
  10000. return;
  10001. }
  10002. if (this.task.onContinue) {
  10003. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10004. } else {
  10005. this._scheduleNext();
  10006. }
  10007. },
  10008. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10009. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10010. window.requestAnimationFrame(this._nextBound);
  10011. } else {
  10012. Promise.resolve(undefined).then(this._nextBound);
  10013. }
  10014. },
  10015. _next: function InternalRenderTask__next() {
  10016. if (this.cancelled) {
  10017. return;
  10018. }
  10019. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  10020. this.operatorListIdx,
  10021. this._continueBound,
  10022. this.stepper);
  10023. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10024. this.running = false;
  10025. if (this.operatorList.lastChunk) {
  10026. this.gfx.endDrawing();
  10027. this.callback();
  10028. }
  10029. }
  10030. }
  10031. };
  10032. return InternalRenderTask;
  10033. })();
  10034. /**
  10035. * (Deprecated) Global observer of unsupported feature usages. Use
  10036. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10037. */
  10038. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  10039. var listeners = [];
  10040. return {
  10041. listen: function (cb) {
  10042. deprecated('Global UnsupportedManager.listen is used: ' +
  10043. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10044. listeners.push(cb);
  10045. },
  10046. notify: function (featureId) {
  10047. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10048. listeners[i](featureId);
  10049. }
  10050. }
  10051. };
  10052. })();
  10053. if (typeof pdfjsVersion !== 'undefined') {
  10054. exports.version = pdfjsVersion;
  10055. }
  10056. if (typeof pdfjsBuild !== 'undefined') {
  10057. exports.build = pdfjsBuild;
  10058. }
  10059. exports.getDocument = getDocument;
  10060. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10061. exports.PDFWorker = PDFWorker;
  10062. exports.PDFDocumentProxy = PDFDocumentProxy;
  10063. exports.PDFPageProxy = PDFPageProxy;
  10064. exports._UnsupportedManager = _UnsupportedManager;
  10065. }));
  10066. (function (root, factory) {
  10067. {
  10068. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  10069. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  10070. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  10071. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10072. }
  10073. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  10074. displayAnnotationLayer, displayTextLayer, displayMetadata,
  10075. displaySVG) {
  10076. var globalScope = sharedUtil.globalScope;
  10077. var deprecated = sharedUtil.deprecated;
  10078. var warn = sharedUtil.warn;
  10079. var LinkTarget = displayDOMUtils.LinkTarget;
  10080. var isWorker = (typeof window === 'undefined');
  10081. // The global PDFJS object is now deprecated and will not be supported in
  10082. // the future. The members below are maintained for backward compatibility
  10083. // and shall not be extended or modified. If the global.js is included as
  10084. // a module, we will create a global PDFJS object instance or use existing.
  10085. if (!globalScope.PDFJS) {
  10086. globalScope.PDFJS = {};
  10087. }
  10088. var PDFJS = globalScope.PDFJS;
  10089. if (typeof pdfjsVersion !== 'undefined') {
  10090. PDFJS.version = pdfjsVersion;
  10091. }
  10092. if (typeof pdfjsBuild !== 'undefined') {
  10093. PDFJS.build = pdfjsBuild;
  10094. }
  10095. PDFJS.pdfBug = false;
  10096. if (PDFJS.verbosity !== undefined) {
  10097. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10098. }
  10099. delete PDFJS.verbosity;
  10100. Object.defineProperty(PDFJS, 'verbosity', {
  10101. get: function () { return sharedUtil.getVerbosityLevel(); },
  10102. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10107. PDFJS.OPS = sharedUtil.OPS;
  10108. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10109. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10110. PDFJS.shadow = sharedUtil.shadow;
  10111. PDFJS.createBlob = sharedUtil.createBlob;
  10112. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10113. return sharedUtil.createObjectURL(data, contentType,
  10114. PDFJS.disableCreateObjectURL);
  10115. };
  10116. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10117. configurable: true,
  10118. get: function PDFJS_isLittleEndian() {
  10119. var value = sharedUtil.isLittleEndian();
  10120. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10121. }
  10122. });
  10123. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10124. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10125. PDFJS.PasswordException = sharedUtil.PasswordException;
  10126. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10127. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10128. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10129. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10130. PDFJS.Util = sharedUtil.Util;
  10131. PDFJS.PageViewport = sharedUtil.PageViewport;
  10132. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10133. /**
  10134. * The maximum allowed image size in total pixels e.g. width * height. Images
  10135. * above this value will not be drawn. Use -1 for no limit.
  10136. * @var {number}
  10137. */
  10138. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  10139. -1 : PDFJS.maxImageSize);
  10140. /**
  10141. * The url of where the predefined Adobe CMaps are located. Include trailing
  10142. * slash.
  10143. * @var {string}
  10144. */
  10145. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  10146. /**
  10147. * Specifies if CMaps are binary packed.
  10148. * @var {boolean}
  10149. */
  10150. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10151. /**
  10152. * By default fonts are converted to OpenType fonts and loaded via font face
  10153. * rules. If disabled, the font will be rendered using a built in font
  10154. * renderer that constructs the glyphs with primitive path commands.
  10155. * @var {boolean}
  10156. */
  10157. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  10158. false : PDFJS.disableFontFace);
  10159. /**
  10160. * Path for image resources, mainly for annotation icons. Include trailing
  10161. * slash.
  10162. * @var {string}
  10163. */
  10164. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  10165. '' : PDFJS.imageResourcesPath);
  10166. /**
  10167. * Disable the web worker and run all code on the main thread. This will
  10168. * happen automatically if the browser doesn't support workers or sending
  10169. * typed arrays to workers.
  10170. * @var {boolean}
  10171. */
  10172. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  10173. false : PDFJS.disableWorker);
  10174. /**
  10175. * Path and filename of the worker file. Required when the worker is enabled
  10176. * in development mode. If unspecified in the production build, the worker
  10177. * will be loaded based on the location of the pdf.js file. It is recommended
  10178. * that the workerSrc is set in a custom application to prevent issues caused
  10179. * by third-party frameworks and libraries.
  10180. * @var {string}
  10181. */
  10182. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  10183. /**
  10184. * Disable range request loading of PDF files. When enabled and if the server
  10185. * supports partial content requests then the PDF will be fetched in chunks.
  10186. * Enabled (false) by default.
  10187. * @var {boolean}
  10188. */
  10189. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  10190. false : PDFJS.disableRange);
  10191. /**
  10192. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10193. * in chunks. This default behavior can be disabled.
  10194. * @var {boolean}
  10195. */
  10196. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  10197. false : PDFJS.disableStream);
  10198. /**
  10199. * Disable pre-fetching of PDF file data. When range requests are enabled
  10200. * PDF.js will automatically keep fetching more data even if it isn't needed
  10201. * to display the current page. This default behavior can be disabled.
  10202. *
  10203. * NOTE: It is also necessary to disable streaming, see above,
  10204. * in order for disabling of pre-fetching to work correctly.
  10205. * @var {boolean}
  10206. */
  10207. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10208. false : PDFJS.disableAutoFetch);
  10209. /**
  10210. * Enables special hooks for debugging PDF.js.
  10211. * @var {boolean}
  10212. */
  10213. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10214. /**
  10215. * Enables transfer usage in postMessage for ArrayBuffers.
  10216. * @var {boolean}
  10217. */
  10218. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10219. true : PDFJS.postMessageTransfers);
  10220. /**
  10221. * Disables URL.createObjectURL usage.
  10222. * @var {boolean}
  10223. */
  10224. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10225. false : PDFJS.disableCreateObjectURL);
  10226. /**
  10227. * Disables WebGL usage.
  10228. * @var {boolean}
  10229. */
  10230. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10231. true : PDFJS.disableWebGL);
  10232. /**
  10233. * Specifies the |target| attribute for external links.
  10234. * The constants from PDFJS.LinkTarget should be used:
  10235. * - NONE [default]
  10236. * - SELF
  10237. * - BLANK
  10238. * - PARENT
  10239. * - TOP
  10240. * @var {number}
  10241. */
  10242. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10243. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10244. /**
  10245. * Specifies the |rel| attribute for external links. Defaults to stripping
  10246. * the referrer.
  10247. * @var {string}
  10248. */
  10249. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10250. 'noreferrer' : PDFJS.externalLinkRel);
  10251. /**
  10252. * Determines if we can eval strings as JS. Primarily used to improve
  10253. * performance for font rendering.
  10254. * @var {boolean}
  10255. */
  10256. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10257. true : PDFJS.isEvalSupported);
  10258. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10259. delete PDFJS.openExternalLinksInNewWindow;
  10260. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10261. get: function () {
  10262. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10263. },
  10264. set: function (value) {
  10265. if (value) {
  10266. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10267. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10268. }
  10269. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10270. warn('PDFJS.externalLinkTarget is already initialized');
  10271. return;
  10272. }
  10273. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. if (savedOpenExternalLinksInNewWindow) {
  10279. /**
  10280. * (Deprecated) Opens external links in a new window if enabled.
  10281. * The default behavior opens external links in the PDF.js window.
  10282. *
  10283. * NOTE: This property has been deprecated, please use
  10284. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10285. * @var {boolean}
  10286. */
  10287. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10288. }
  10289. PDFJS.getDocument = displayAPI.getDocument;
  10290. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10291. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10292. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10293. configurable: true,
  10294. get: function PDFJS_hasCanvasTypedArrays() {
  10295. var value = displayDOMUtils.hasCanvasTypedArrays();
  10296. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10297. }
  10298. });
  10299. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10300. PDFJS.LinkTarget = LinkTarget;
  10301. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10302. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10303. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10304. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10305. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10306. PDFJS.Metadata = displayMetadata.Metadata;
  10307. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10308. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10309. exports.globalScope = globalScope;
  10310. exports.isWorker = isWorker;
  10311. exports.PDFJS = globalScope.PDFJS;
  10312. }));
  10313. }).call(pdfjsLibs);
  10314. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10315. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10316. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10317. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10318. exports.PDFDataRangeTransport =
  10319. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10320. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10321. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10322. exports.AnnotationLayer =
  10323. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10324. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10325. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10326. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10327. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10328. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10329. exports.UnexpectedResponseException =
  10330. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10331. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10332. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10333. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10334. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10335. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10336. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10337. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10338. exports.getFilenameFromUrl =
  10339. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10340. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10341. }));