pdf.js 346 KB

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