pdf.js 362 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* jshint globalstrict: false */
  16. /* umdutils ignore */
  17. (function (root, factory) {
  18. 'use strict';
  19. if (typeof define === 'function' && define.amd) {
  20. define('pdfjs-dist/build/pdf', ['exports'], factory);
  21. } else if (typeof exports !== 'undefined') {
  22. factory(exports);
  23. } else {
  24. factory((root.pdfjsDistBuildPdf = {}));
  25. }
  26. }(this, function (exports) {
  27. // Use strict in our context only - users might not want it
  28. 'use strict';
  29. var pdfjsVersion = '1.5.450';
  30. var pdfjsBuild = '6b05cfd';
  31. var pdfjsFilePath =
  32. typeof document !== 'undefined' && document.currentScript ?
  33. document.currentScript.src : null;
  34. var pdfjsLibs = {};
  35. (function pdfjsWrapper() {
  36. (function (root, factory) {
  37. {
  38. factory((root.pdfjsSharedUtil = {}));
  39. }
  40. }(this, function (exports) {
  41. var globalScope = (typeof window !== 'undefined') ? window :
  42. (typeof global !== 'undefined') ? global :
  43. (typeof self !== 'undefined') ? self : this;
  44. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  45. var TextRenderingMode = {
  46. FILL: 0,
  47. STROKE: 1,
  48. FILL_STROKE: 2,
  49. INVISIBLE: 3,
  50. FILL_ADD_TO_PATH: 4,
  51. STROKE_ADD_TO_PATH: 5,
  52. FILL_STROKE_ADD_TO_PATH: 6,
  53. ADD_TO_PATH: 7,
  54. FILL_STROKE_MASK: 3,
  55. ADD_TO_PATH_FLAG: 4
  56. };
  57. var ImageKind = {
  58. GRAYSCALE_1BPP: 1,
  59. RGB_24BPP: 2,
  60. RGBA_32BPP: 3
  61. };
  62. var AnnotationType = {
  63. TEXT: 1,
  64. LINK: 2,
  65. FREETEXT: 3,
  66. LINE: 4,
  67. SQUARE: 5,
  68. CIRCLE: 6,
  69. POLYGON: 7,
  70. POLYLINE: 8,
  71. HIGHLIGHT: 9,
  72. UNDERLINE: 10,
  73. SQUIGGLY: 11,
  74. STRIKEOUT: 12,
  75. STAMP: 13,
  76. CARET: 14,
  77. INK: 15,
  78. POPUP: 16,
  79. FILEATTACHMENT: 17,
  80. SOUND: 18,
  81. MOVIE: 19,
  82. WIDGET: 20,
  83. SCREEN: 21,
  84. PRINTERMARK: 22,
  85. TRAPNET: 23,
  86. WATERMARK: 24,
  87. THREED: 25,
  88. REDACT: 26
  89. };
  90. var AnnotationFlag = {
  91. INVISIBLE: 0x01,
  92. HIDDEN: 0x02,
  93. PRINT: 0x04,
  94. NOZOOM: 0x08,
  95. NOROTATE: 0x10,
  96. NOVIEW: 0x20,
  97. READONLY: 0x40,
  98. LOCKED: 0x80,
  99. TOGGLENOVIEW: 0x100,
  100. LOCKEDCONTENTS: 0x200
  101. };
  102. var AnnotationBorderStyleType = {
  103. SOLID: 1,
  104. DASHED: 2,
  105. BEVELED: 3,
  106. INSET: 4,
  107. UNDERLINE: 5
  108. };
  109. var StreamType = {
  110. UNKNOWN: 0,
  111. FLATE: 1,
  112. LZW: 2,
  113. DCT: 3,
  114. JPX: 4,
  115. JBIG: 5,
  116. A85: 6,
  117. AHX: 7,
  118. CCF: 8,
  119. RL: 9
  120. };
  121. var FontType = {
  122. UNKNOWN: 0,
  123. TYPE1: 1,
  124. TYPE1C: 2,
  125. CIDFONTTYPE0: 3,
  126. CIDFONTTYPE0C: 4,
  127. TRUETYPE: 5,
  128. CIDFONTTYPE2: 6,
  129. TYPE3: 7,
  130. OPENTYPE: 8,
  131. TYPE0: 9,
  132. MMTYPE1: 10
  133. };
  134. var VERBOSITY_LEVELS = {
  135. errors: 0,
  136. warnings: 1,
  137. infos: 5
  138. };
  139. // All the possible operations for an operator list.
  140. var OPS = {
  141. // Intentionally start from 1 so it is easy to spot bad operators that will be
  142. // 0's.
  143. dependency: 1,
  144. setLineWidth: 2,
  145. setLineCap: 3,
  146. setLineJoin: 4,
  147. setMiterLimit: 5,
  148. setDash: 6,
  149. setRenderingIntent: 7,
  150. setFlatness: 8,
  151. setGState: 9,
  152. save: 10,
  153. restore: 11,
  154. transform: 12,
  155. moveTo: 13,
  156. lineTo: 14,
  157. curveTo: 15,
  158. curveTo2: 16,
  159. curveTo3: 17,
  160. closePath: 18,
  161. rectangle: 19,
  162. stroke: 20,
  163. closeStroke: 21,
  164. fill: 22,
  165. eoFill: 23,
  166. fillStroke: 24,
  167. eoFillStroke: 25,
  168. closeFillStroke: 26,
  169. closeEOFillStroke: 27,
  170. endPath: 28,
  171. clip: 29,
  172. eoClip: 30,
  173. beginText: 31,
  174. endText: 32,
  175. setCharSpacing: 33,
  176. setWordSpacing: 34,
  177. setHScale: 35,
  178. setLeading: 36,
  179. setFont: 37,
  180. setTextRenderingMode: 38,
  181. setTextRise: 39,
  182. moveText: 40,
  183. setLeadingMoveText: 41,
  184. setTextMatrix: 42,
  185. nextLine: 43,
  186. showText: 44,
  187. showSpacedText: 45,
  188. nextLineShowText: 46,
  189. nextLineSetSpacingShowText: 47,
  190. setCharWidth: 48,
  191. setCharWidthAndBounds: 49,
  192. setStrokeColorSpace: 50,
  193. setFillColorSpace: 51,
  194. setStrokeColor: 52,
  195. setStrokeColorN: 53,
  196. setFillColor: 54,
  197. setFillColorN: 55,
  198. setStrokeGray: 56,
  199. setFillGray: 57,
  200. setStrokeRGBColor: 58,
  201. setFillRGBColor: 59,
  202. setStrokeCMYKColor: 60,
  203. setFillCMYKColor: 61,
  204. shadingFill: 62,
  205. beginInlineImage: 63,
  206. beginImageData: 64,
  207. endInlineImage: 65,
  208. paintXObject: 66,
  209. markPoint: 67,
  210. markPointProps: 68,
  211. beginMarkedContent: 69,
  212. beginMarkedContentProps: 70,
  213. endMarkedContent: 71,
  214. beginCompat: 72,
  215. endCompat: 73,
  216. paintFormXObjectBegin: 74,
  217. paintFormXObjectEnd: 75,
  218. beginGroup: 76,
  219. endGroup: 77,
  220. beginAnnotations: 78,
  221. endAnnotations: 79,
  222. beginAnnotation: 80,
  223. endAnnotation: 81,
  224. paintJpegXObject: 82,
  225. paintImageMaskXObject: 83,
  226. paintImageMaskXObjectGroup: 84,
  227. paintImageXObject: 85,
  228. paintInlineImageXObject: 86,
  229. paintInlineImageXObjectGroup: 87,
  230. paintImageXObjectRepeat: 88,
  231. paintImageMaskXObjectRepeat: 89,
  232. paintSolidColorImageMask: 90,
  233. constructPath: 91
  234. };
  235. var verbosity = VERBOSITY_LEVELS.warnings;
  236. function setVerbosityLevel(level) {
  237. verbosity = level;
  238. }
  239. function getVerbosityLevel() {
  240. return verbosity;
  241. }
  242. // A notice for devs. These are good for things that are helpful to devs, such
  243. // as warning that Workers were disabled, which is important to devs but not
  244. // end users.
  245. function info(msg) {
  246. if (verbosity >= VERBOSITY_LEVELS.infos) {
  247. console.log('Info: ' + msg);
  248. }
  249. }
  250. // Non-fatal warnings.
  251. function warn(msg) {
  252. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  253. console.log('Warning: ' + msg);
  254. }
  255. }
  256. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  257. function deprecated(details) {
  258. console.log('Deprecated API usage: ' + details);
  259. }
  260. // Fatal errors that should trigger the fallback UI and halt execution by
  261. // throwing an exception.
  262. function error(msg) {
  263. if (verbosity >= VERBOSITY_LEVELS.errors) {
  264. console.log('Error: ' + msg);
  265. console.log(backtrace());
  266. }
  267. throw new Error(msg);
  268. }
  269. function backtrace() {
  270. try {
  271. throw new Error();
  272. } catch (e) {
  273. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  274. }
  275. }
  276. function assert(cond, msg) {
  277. if (!cond) {
  278. error(msg);
  279. }
  280. }
  281. var UNSUPPORTED_FEATURES = {
  282. unknown: 'unknown',
  283. forms: 'forms',
  284. javaScript: 'javaScript',
  285. smask: 'smask',
  286. shadingPattern: 'shadingPattern',
  287. font: 'font'
  288. };
  289. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  290. function isSameOrigin(baseUrl, otherUrl) {
  291. try {
  292. var base = new URL(baseUrl);
  293. if (!base.origin || base.origin === 'null') {
  294. return false; // non-HTTP url
  295. }
  296. } catch (e) {
  297. return false;
  298. }
  299. var other = new URL(otherUrl, base);
  300. return base.origin === other.origin;
  301. }
  302. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  303. function isValidUrl(url, allowRelative) {
  304. if (!url || typeof url !== 'string') {
  305. return false;
  306. }
  307. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  308. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  309. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  310. if (!protocol) {
  311. return allowRelative;
  312. }
  313. protocol = protocol[0].toLowerCase();
  314. switch (protocol) {
  315. case 'http':
  316. case 'https':
  317. case 'ftp':
  318. case 'mailto':
  319. case 'tel':
  320. return true;
  321. default:
  322. return false;
  323. }
  324. }
  325. function shadow(obj, prop, value) {
  326. Object.defineProperty(obj, prop, { value: value,
  327. enumerable: true,
  328. configurable: true,
  329. writable: false });
  330. return value;
  331. }
  332. function getLookupTableFactory(initializer) {
  333. var lookup;
  334. return function () {
  335. if (initializer) {
  336. lookup = Object.create(null);
  337. initializer(lookup);
  338. initializer = null;
  339. }
  340. return lookup;
  341. };
  342. }
  343. var PasswordResponses = {
  344. NEED_PASSWORD: 1,
  345. INCORRECT_PASSWORD: 2
  346. };
  347. var PasswordException = (function PasswordExceptionClosure() {
  348. function PasswordException(msg, code) {
  349. this.name = 'PasswordException';
  350. this.message = msg;
  351. this.code = code;
  352. }
  353. PasswordException.prototype = new Error();
  354. PasswordException.constructor = PasswordException;
  355. return PasswordException;
  356. })();
  357. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  358. function UnknownErrorException(msg, details) {
  359. this.name = 'UnknownErrorException';
  360. this.message = msg;
  361. this.details = details;
  362. }
  363. UnknownErrorException.prototype = new Error();
  364. UnknownErrorException.constructor = UnknownErrorException;
  365. return UnknownErrorException;
  366. })();
  367. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  368. function InvalidPDFException(msg) {
  369. this.name = 'InvalidPDFException';
  370. this.message = msg;
  371. }
  372. InvalidPDFException.prototype = new Error();
  373. InvalidPDFException.constructor = InvalidPDFException;
  374. return InvalidPDFException;
  375. })();
  376. var MissingPDFException = (function MissingPDFExceptionClosure() {
  377. function MissingPDFException(msg) {
  378. this.name = 'MissingPDFException';
  379. this.message = msg;
  380. }
  381. MissingPDFException.prototype = new Error();
  382. MissingPDFException.constructor = MissingPDFException;
  383. return MissingPDFException;
  384. })();
  385. var UnexpectedResponseException =
  386. (function UnexpectedResponseExceptionClosure() {
  387. function UnexpectedResponseException(msg, status) {
  388. this.name = 'UnexpectedResponseException';
  389. this.message = msg;
  390. this.status = status;
  391. }
  392. UnexpectedResponseException.prototype = new Error();
  393. UnexpectedResponseException.constructor = UnexpectedResponseException;
  394. return UnexpectedResponseException;
  395. })();
  396. var NotImplementedException = (function NotImplementedExceptionClosure() {
  397. function NotImplementedException(msg) {
  398. this.message = msg;
  399. }
  400. NotImplementedException.prototype = new Error();
  401. NotImplementedException.prototype.name = 'NotImplementedException';
  402. NotImplementedException.constructor = NotImplementedException;
  403. return NotImplementedException;
  404. })();
  405. var MissingDataException = (function MissingDataExceptionClosure() {
  406. function MissingDataException(begin, end) {
  407. this.begin = begin;
  408. this.end = end;
  409. this.message = 'Missing data [' + begin + ', ' + end + ')';
  410. }
  411. MissingDataException.prototype = new Error();
  412. MissingDataException.prototype.name = 'MissingDataException';
  413. MissingDataException.constructor = MissingDataException;
  414. return MissingDataException;
  415. })();
  416. var XRefParseException = (function XRefParseExceptionClosure() {
  417. function XRefParseException(msg) {
  418. this.message = msg;
  419. }
  420. XRefParseException.prototype = new Error();
  421. XRefParseException.prototype.name = 'XRefParseException';
  422. XRefParseException.constructor = XRefParseException;
  423. return XRefParseException;
  424. })();
  425. var NullCharactersRegExp = /\x00/g;
  426. function removeNullCharacters(str) {
  427. if (typeof str !== 'string') {
  428. warn('The argument for removeNullCharacters must be a string.');
  429. return str;
  430. }
  431. return str.replace(NullCharactersRegExp, '');
  432. }
  433. function bytesToString(bytes) {
  434. assert(bytes !== null && typeof bytes === 'object' &&
  435. bytes.length !== undefined, 'Invalid argument for bytesToString');
  436. var length = bytes.length;
  437. var MAX_ARGUMENT_COUNT = 8192;
  438. if (length < MAX_ARGUMENT_COUNT) {
  439. return String.fromCharCode.apply(null, bytes);
  440. }
  441. var strBuf = [];
  442. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  443. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  444. var chunk = bytes.subarray(i, chunkEnd);
  445. strBuf.push(String.fromCharCode.apply(null, chunk));
  446. }
  447. return strBuf.join('');
  448. }
  449. function stringToBytes(str) {
  450. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  451. var length = str.length;
  452. var bytes = new Uint8Array(length);
  453. for (var i = 0; i < length; ++i) {
  454. bytes[i] = str.charCodeAt(i) & 0xFF;
  455. }
  456. return bytes;
  457. }
  458. /**
  459. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  460. * @param {Array|Uint8Array|string} arr
  461. * @returns {number}
  462. */
  463. function arrayByteLength(arr) {
  464. if (arr.length !== undefined) {
  465. return arr.length;
  466. }
  467. assert(arr.byteLength !== undefined);
  468. return arr.byteLength;
  469. }
  470. /**
  471. * Combines array items (arrays) into single Uint8Array object.
  472. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  473. * @returns {Uint8Array}
  474. */
  475. function arraysToBytes(arr) {
  476. // Shortcut: if first and only item is Uint8Array, return it.
  477. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {
  478. return arr[0];
  479. }
  480. var resultLength = 0;
  481. var i, ii = arr.length;
  482. var item, itemLength ;
  483. for (i = 0; i < ii; i++) {
  484. item = arr[i];
  485. itemLength = arrayByteLength(item);
  486. resultLength += itemLength;
  487. }
  488. var pos = 0;
  489. var data = new Uint8Array(resultLength);
  490. for (i = 0; i < ii; i++) {
  491. item = arr[i];
  492. if (!(item instanceof Uint8Array)) {
  493. if (typeof item === 'string') {
  494. item = stringToBytes(item);
  495. } else {
  496. item = new Uint8Array(item);
  497. }
  498. }
  499. itemLength = item.byteLength;
  500. data.set(item, pos);
  501. pos += itemLength;
  502. }
  503. return data;
  504. }
  505. function string32(value) {
  506. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  507. (value >> 8) & 0xff, value & 0xff);
  508. }
  509. function log2(x) {
  510. var n = 1, i = 0;
  511. while (x > n) {
  512. n <<= 1;
  513. i++;
  514. }
  515. return i;
  516. }
  517. function readInt8(data, start) {
  518. return (data[start] << 24) >> 24;
  519. }
  520. function readUint16(data, offset) {
  521. return (data[offset] << 8) | data[offset + 1];
  522. }
  523. function readUint32(data, offset) {
  524. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  525. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  526. }
  527. // Lazy test the endianness of the platform
  528. // NOTE: This will be 'true' for simulated TypedArrays
  529. function isLittleEndian() {
  530. var buffer8 = new Uint8Array(2);
  531. buffer8[0] = 1;
  532. var buffer16 = new Uint16Array(buffer8.buffer);
  533. return (buffer16[0] === 1);
  534. }
  535. // Checks if it's possible to eval JS expressions.
  536. function isEvalSupported() {
  537. try {
  538. /* jshint evil: true */
  539. new Function('');
  540. return true;
  541. } catch (e) {
  542. return false;
  543. }
  544. }
  545. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  546. function Uint32ArrayView(buffer, length) {
  547. this.buffer = buffer;
  548. this.byteLength = buffer.length;
  549. this.length = length === undefined ? (this.byteLength >> 2) : length;
  550. ensureUint32ArrayViewProps(this.length);
  551. }
  552. Uint32ArrayView.prototype = Object.create(null);
  553. var uint32ArrayViewSetters = 0;
  554. function createUint32ArrayProp(index) {
  555. return {
  556. get: function () {
  557. var buffer = this.buffer, offset = index << 2;
  558. return (buffer[offset] | (buffer[offset + 1] << 8) |
  559. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  560. },
  561. set: function (value) {
  562. var buffer = this.buffer, offset = index << 2;
  563. buffer[offset] = value & 255;
  564. buffer[offset + 1] = (value >> 8) & 255;
  565. buffer[offset + 2] = (value >> 16) & 255;
  566. buffer[offset + 3] = (value >>> 24) & 255;
  567. }
  568. };
  569. }
  570. function ensureUint32ArrayViewProps(length) {
  571. while (uint32ArrayViewSetters < length) {
  572. Object.defineProperty(Uint32ArrayView.prototype,
  573. uint32ArrayViewSetters,
  574. createUint32ArrayProp(uint32ArrayViewSetters));
  575. uint32ArrayViewSetters++;
  576. }
  577. }
  578. return Uint32ArrayView;
  579. })();
  580. exports.Uint32ArrayView = Uint32ArrayView;
  581. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  582. var Util = (function UtilClosure() {
  583. function Util() {}
  584. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  585. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  586. // creating many intermediate strings.
  587. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  588. rgbBuf[1] = r;
  589. rgbBuf[3] = g;
  590. rgbBuf[5] = b;
  591. return rgbBuf.join('');
  592. };
  593. // Concatenates two transformation matrices together and returns the result.
  594. Util.transform = function Util_transform(m1, m2) {
  595. return [
  596. m1[0] * m2[0] + m1[2] * m2[1],
  597. m1[1] * m2[0] + m1[3] * m2[1],
  598. m1[0] * m2[2] + m1[2] * m2[3],
  599. m1[1] * m2[2] + m1[3] * m2[3],
  600. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  601. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  602. ];
  603. };
  604. // For 2d affine transforms
  605. Util.applyTransform = function Util_applyTransform(p, m) {
  606. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  607. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  608. return [xt, yt];
  609. };
  610. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  611. var d = m[0] * m[3] - m[1] * m[2];
  612. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  613. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  614. return [xt, yt];
  615. };
  616. // Applies the transform to the rectangle and finds the minimum axially
  617. // aligned bounding box.
  618. Util.getAxialAlignedBoundingBox =
  619. function Util_getAxialAlignedBoundingBox(r, m) {
  620. var p1 = Util.applyTransform(r, m);
  621. var p2 = Util.applyTransform(r.slice(2, 4), m);
  622. var p3 = Util.applyTransform([r[0], r[3]], m);
  623. var p4 = Util.applyTransform([r[2], r[1]], m);
  624. return [
  625. Math.min(p1[0], p2[0], p3[0], p4[0]),
  626. Math.min(p1[1], p2[1], p3[1], p4[1]),
  627. Math.max(p1[0], p2[0], p3[0], p4[0]),
  628. Math.max(p1[1], p2[1], p3[1], p4[1])
  629. ];
  630. };
  631. Util.inverseTransform = function Util_inverseTransform(m) {
  632. var d = m[0] * m[3] - m[1] * m[2];
  633. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  634. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  635. };
  636. // Apply a generic 3d matrix M on a 3-vector v:
  637. // | a b c | | X |
  638. // | d e f | x | Y |
  639. // | g h i | | Z |
  640. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  641. // with v as [X,Y,Z]
  642. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  643. return [
  644. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  645. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  646. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  647. ];
  648. };
  649. // This calculation uses Singular Value Decomposition.
  650. // The SVD can be represented with formula A = USV. We are interested in the
  651. // matrix S here because it represents the scale values.
  652. Util.singularValueDecompose2dScale =
  653. function Util_singularValueDecompose2dScale(m) {
  654. var transpose = [m[0], m[2], m[1], m[3]];
  655. // Multiply matrix m with its transpose.
  656. var a = m[0] * transpose[0] + m[1] * transpose[2];
  657. var b = m[0] * transpose[1] + m[1] * transpose[3];
  658. var c = m[2] * transpose[0] + m[3] * transpose[2];
  659. var d = m[2] * transpose[1] + m[3] * transpose[3];
  660. // Solve the second degree polynomial to get roots.
  661. var first = (a + d) / 2;
  662. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  663. var sx = first + second || 1;
  664. var sy = first - second || 1;
  665. // Scale values are the square roots of the eigenvalues.
  666. return [Math.sqrt(sx), Math.sqrt(sy)];
  667. };
  668. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  669. // For coordinate systems whose origin lies in the bottom-left, this
  670. // means normalization to (BL,TR) ordering. For systems with origin in the
  671. // top-left, this means (TL,BR) ordering.
  672. Util.normalizeRect = function Util_normalizeRect(rect) {
  673. var r = rect.slice(0); // clone rect
  674. if (rect[0] > rect[2]) {
  675. r[0] = rect[2];
  676. r[2] = rect[0];
  677. }
  678. if (rect[1] > rect[3]) {
  679. r[1] = rect[3];
  680. r[3] = rect[1];
  681. }
  682. return r;
  683. };
  684. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  685. // intersection of rect1 and rect2. If no intersection, returns 'false'
  686. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  687. Util.intersect = function Util_intersect(rect1, rect2) {
  688. function compare(a, b) {
  689. return a - b;
  690. }
  691. // Order points along the axes
  692. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  693. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  694. result = [];
  695. rect1 = Util.normalizeRect(rect1);
  696. rect2 = Util.normalizeRect(rect2);
  697. // X: first and second points belong to different rectangles?
  698. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  699. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  700. // Intersection must be between second and third points
  701. result[0] = orderedX[1];
  702. result[2] = orderedX[2];
  703. } else {
  704. return false;
  705. }
  706. // Y: first and second points belong to different rectangles?
  707. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  708. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  709. // Intersection must be between second and third points
  710. result[1] = orderedY[1];
  711. result[3] = orderedY[2];
  712. } else {
  713. return false;
  714. }
  715. return result;
  716. };
  717. Util.sign = function Util_sign(num) {
  718. return num < 0 ? -1 : 1;
  719. };
  720. var ROMAN_NUMBER_MAP = [
  721. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  722. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  723. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  724. ];
  725. /**
  726. * Converts positive integers to (upper case) Roman numerals.
  727. * @param {integer} number - The number that should be converted.
  728. * @param {boolean} lowerCase - Indicates if the result should be converted
  729. * to lower case letters. The default is false.
  730. * @return {string} The resulting Roman number.
  731. */
  732. Util.toRoman = function Util_toRoman(number, lowerCase) {
  733. assert(isInt(number) && number > 0,
  734. 'The number should be a positive integer.');
  735. var pos, romanBuf = [];
  736. // Thousands
  737. while (number >= 1000) {
  738. number -= 1000;
  739. romanBuf.push('M');
  740. }
  741. // Hundreds
  742. pos = (number / 100) | 0;
  743. number %= 100;
  744. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  745. // Tens
  746. pos = (number / 10) | 0;
  747. number %= 10;
  748. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  749. // Ones
  750. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  751. var romanStr = romanBuf.join('');
  752. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  753. };
  754. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  755. Array.prototype.push.apply(arr1, arr2);
  756. };
  757. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  758. Array.prototype.unshift.apply(arr1, arr2);
  759. };
  760. Util.extendObj = function extendObj(obj1, obj2) {
  761. for (var key in obj2) {
  762. obj1[key] = obj2[key];
  763. }
  764. };
  765. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  766. name) {
  767. while (dict && !dict.has(name)) {
  768. dict = dict.get('Parent');
  769. }
  770. if (!dict) {
  771. return null;
  772. }
  773. return dict.get(name);
  774. };
  775. Util.inherit = function Util_inherit(sub, base, prototype) {
  776. sub.prototype = Object.create(base.prototype);
  777. sub.prototype.constructor = sub;
  778. for (var prop in prototype) {
  779. sub.prototype[prop] = prototype[prop];
  780. }
  781. };
  782. Util.loadScript = function Util_loadScript(src, callback) {
  783. var script = document.createElement('script');
  784. var loaded = false;
  785. script.setAttribute('src', src);
  786. if (callback) {
  787. script.onload = function() {
  788. if (!loaded) {
  789. callback();
  790. }
  791. loaded = true;
  792. };
  793. }
  794. document.getElementsByTagName('head')[0].appendChild(script);
  795. };
  796. return Util;
  797. })();
  798. /**
  799. * PDF page viewport created based on scale, rotation and offset.
  800. * @class
  801. * @alias PageViewport
  802. */
  803. var PageViewport = (function PageViewportClosure() {
  804. /**
  805. * @constructor
  806. * @private
  807. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  808. * @param scale {number} scale of the viewport.
  809. * @param rotation {number} rotations of the viewport in degrees.
  810. * @param offsetX {number} offset X
  811. * @param offsetY {number} offset Y
  812. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  813. */
  814. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  815. this.viewBox = viewBox;
  816. this.scale = scale;
  817. this.rotation = rotation;
  818. this.offsetX = offsetX;
  819. this.offsetY = offsetY;
  820. // creating transform to convert pdf coordinate system to the normal
  821. // canvas like coordinates taking in account scale and rotation
  822. var centerX = (viewBox[2] + viewBox[0]) / 2;
  823. var centerY = (viewBox[3] + viewBox[1]) / 2;
  824. var rotateA, rotateB, rotateC, rotateD;
  825. rotation = rotation % 360;
  826. rotation = rotation < 0 ? rotation + 360 : rotation;
  827. switch (rotation) {
  828. case 180:
  829. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  830. break;
  831. case 90:
  832. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  833. break;
  834. case 270:
  835. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  836. break;
  837. //case 0:
  838. default:
  839. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  840. break;
  841. }
  842. if (dontFlip) {
  843. rotateC = -rotateC; rotateD = -rotateD;
  844. }
  845. var offsetCanvasX, offsetCanvasY;
  846. var width, height;
  847. if (rotateA === 0) {
  848. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  849. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  850. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  851. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  852. } else {
  853. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  854. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  855. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  856. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  857. }
  858. // creating transform for the following operations:
  859. // translate(-centerX, -centerY), rotate and flip vertically,
  860. // scale, and translate(offsetCanvasX, offsetCanvasY)
  861. this.transform = [
  862. rotateA * scale,
  863. rotateB * scale,
  864. rotateC * scale,
  865. rotateD * scale,
  866. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  867. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  868. ];
  869. this.width = width;
  870. this.height = height;
  871. this.fontScale = scale;
  872. }
  873. PageViewport.prototype = /** @lends PageViewport.prototype */ {
  874. /**
  875. * Clones viewport with additional properties.
  876. * @param args {Object} (optional) If specified, may contain the 'scale' or
  877. * 'rotation' properties to override the corresponding properties in
  878. * the cloned viewport.
  879. * @returns {PageViewport} Cloned viewport.
  880. */
  881. clone: function PageViewPort_clone(args) {
  882. args = args || {};
  883. var scale = 'scale' in args ? args.scale : this.scale;
  884. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  885. return new PageViewport(this.viewBox.slice(), scale, rotation,
  886. this.offsetX, this.offsetY, args.dontFlip);
  887. },
  888. /**
  889. * Converts PDF point to the viewport coordinates. For examples, useful for
  890. * converting PDF location into canvas pixel coordinates.
  891. * @param x {number} X coordinate.
  892. * @param y {number} Y coordinate.
  893. * @returns {Object} Object that contains 'x' and 'y' properties of the
  894. * point in the viewport coordinate space.
  895. * @see {@link convertToPdfPoint}
  896. * @see {@link convertToViewportRectangle}
  897. */
  898. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  899. return Util.applyTransform([x, y], this.transform);
  900. },
  901. /**
  902. * Converts PDF rectangle to the viewport coordinates.
  903. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  904. * @returns {Array} Contains corresponding coordinates of the rectangle
  905. * in the viewport coordinate space.
  906. * @see {@link convertToViewportPoint}
  907. */
  908. convertToViewportRectangle:
  909. function PageViewport_convertToViewportRectangle(rect) {
  910. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  911. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  912. return [tl[0], tl[1], br[0], br[1]];
  913. },
  914. /**
  915. * Converts viewport coordinates to the PDF location. For examples, useful
  916. * for converting canvas pixel location into PDF one.
  917. * @param x {number} X coordinate.
  918. * @param y {number} Y coordinate.
  919. * @returns {Object} Object that contains 'x' and 'y' properties of the
  920. * point in the PDF coordinate space.
  921. * @see {@link convertToViewportPoint}
  922. */
  923. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  924. return Util.applyInverseTransform([x, y], this.transform);
  925. }
  926. };
  927. return PageViewport;
  928. })();
  929. var PDFStringTranslateTable = [
  930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  931. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  936. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  937. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  938. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  939. ];
  940. function stringToPDFString(str) {
  941. var i, n = str.length, strBuf = [];
  942. if (str[0] === '\xFE' && str[1] === '\xFF') {
  943. // UTF16BE BOM
  944. for (i = 2; i < n; i += 2) {
  945. strBuf.push(String.fromCharCode(
  946. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  947. }
  948. } else {
  949. for (i = 0; i < n; ++i) {
  950. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  951. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  952. }
  953. }
  954. return strBuf.join('');
  955. }
  956. function stringToUTF8String(str) {
  957. return decodeURIComponent(escape(str));
  958. }
  959. function utf8StringToString(str) {
  960. return unescape(encodeURIComponent(str));
  961. }
  962. function isEmptyObj(obj) {
  963. for (var key in obj) {
  964. return false;
  965. }
  966. return true;
  967. }
  968. function isBool(v) {
  969. return typeof v === 'boolean';
  970. }
  971. function isInt(v) {
  972. return typeof v === 'number' && ((v | 0) === v);
  973. }
  974. function isNum(v) {
  975. return typeof v === 'number';
  976. }
  977. function isString(v) {
  978. return typeof v === 'string';
  979. }
  980. function isArray(v) {
  981. return v instanceof Array;
  982. }
  983. function isArrayBuffer(v) {
  984. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  985. }
  986. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  987. function isSpace(ch) {
  988. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  989. }
  990. /**
  991. * Promise Capability object.
  992. *
  993. * @typedef {Object} PromiseCapability
  994. * @property {Promise} promise - A promise object.
  995. * @property {function} resolve - Fulfills the promise.
  996. * @property {function} reject - Rejects the promise.
  997. */
  998. /**
  999. * Creates a promise capability object.
  1000. * @alias createPromiseCapability
  1001. *
  1002. * @return {PromiseCapability} A capability object contains:
  1003. * - a Promise, resolve and reject methods.
  1004. */
  1005. function createPromiseCapability() {
  1006. var capability = {};
  1007. capability.promise = new Promise(function (resolve, reject) {
  1008. capability.resolve = resolve;
  1009. capability.reject = reject;
  1010. });
  1011. return capability;
  1012. }
  1013. /**
  1014. * Polyfill for Promises:
  1015. * The following promise implementation tries to generally implement the
  1016. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1017. * - There currently isn't a separate deferred and promise object.
  1018. * - Unhandled rejections eventually show an error if they aren't handled.
  1019. *
  1020. * Based off of the work in:
  1021. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1022. */
  1023. (function PromiseClosure() {
  1024. if (globalScope.Promise) {
  1025. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1026. if (typeof globalScope.Promise.all !== 'function') {
  1027. globalScope.Promise.all = function (iterable) {
  1028. var count = 0, results = [], resolve, reject;
  1029. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1030. resolve = resolve_;
  1031. reject = reject_;
  1032. });
  1033. iterable.forEach(function (p, i) {
  1034. count++;
  1035. p.then(function (result) {
  1036. results[i] = result;
  1037. count--;
  1038. if (count === 0) {
  1039. resolve(results);
  1040. }
  1041. }, reject);
  1042. });
  1043. if (count === 0) {
  1044. resolve(results);
  1045. }
  1046. return promise;
  1047. };
  1048. }
  1049. if (typeof globalScope.Promise.resolve !== 'function') {
  1050. globalScope.Promise.resolve = function (value) {
  1051. return new globalScope.Promise(function (resolve) { resolve(value); });
  1052. };
  1053. }
  1054. if (typeof globalScope.Promise.reject !== 'function') {
  1055. globalScope.Promise.reject = function (reason) {
  1056. return new globalScope.Promise(function (resolve, reject) {
  1057. reject(reason);
  1058. });
  1059. };
  1060. }
  1061. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1062. globalScope.Promise.prototype.catch = function (onReject) {
  1063. return globalScope.Promise.prototype.then(undefined, onReject);
  1064. };
  1065. }
  1066. return;
  1067. }
  1068. var STATUS_PENDING = 0;
  1069. var STATUS_RESOLVED = 1;
  1070. var STATUS_REJECTED = 2;
  1071. // In an attempt to avoid silent exceptions, unhandled rejections are
  1072. // tracked and if they aren't handled in a certain amount of time an
  1073. // error is logged.
  1074. var REJECTION_TIMEOUT = 500;
  1075. var HandlerManager = {
  1076. handlers: [],
  1077. running: false,
  1078. unhandledRejections: [],
  1079. pendingRejectionCheck: false,
  1080. scheduleHandlers: function scheduleHandlers(promise) {
  1081. if (promise._status === STATUS_PENDING) {
  1082. return;
  1083. }
  1084. this.handlers = this.handlers.concat(promise._handlers);
  1085. promise._handlers = [];
  1086. if (this.running) {
  1087. return;
  1088. }
  1089. this.running = true;
  1090. setTimeout(this.runHandlers.bind(this), 0);
  1091. },
  1092. runHandlers: function runHandlers() {
  1093. var RUN_TIMEOUT = 1; // ms
  1094. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1095. while (this.handlers.length > 0) {
  1096. var handler = this.handlers.shift();
  1097. var nextStatus = handler.thisPromise._status;
  1098. var nextValue = handler.thisPromise._value;
  1099. try {
  1100. if (nextStatus === STATUS_RESOLVED) {
  1101. if (typeof handler.onResolve === 'function') {
  1102. nextValue = handler.onResolve(nextValue);
  1103. }
  1104. } else if (typeof handler.onReject === 'function') {
  1105. nextValue = handler.onReject(nextValue);
  1106. nextStatus = STATUS_RESOLVED;
  1107. if (handler.thisPromise._unhandledRejection) {
  1108. this.removeUnhandeledRejection(handler.thisPromise);
  1109. }
  1110. }
  1111. } catch (ex) {
  1112. nextStatus = STATUS_REJECTED;
  1113. nextValue = ex;
  1114. }
  1115. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1116. if (Date.now() >= timeoutAt) {
  1117. break;
  1118. }
  1119. }
  1120. if (this.handlers.length > 0) {
  1121. setTimeout(this.runHandlers.bind(this), 0);
  1122. return;
  1123. }
  1124. this.running = false;
  1125. },
  1126. addUnhandledRejection: function addUnhandledRejection(promise) {
  1127. this.unhandledRejections.push({
  1128. promise: promise,
  1129. time: Date.now()
  1130. });
  1131. this.scheduleRejectionCheck();
  1132. },
  1133. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1134. promise._unhandledRejection = false;
  1135. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1136. if (this.unhandledRejections[i].promise === promise) {
  1137. this.unhandledRejections.splice(i);
  1138. i--;
  1139. }
  1140. }
  1141. },
  1142. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1143. if (this.pendingRejectionCheck) {
  1144. return;
  1145. }
  1146. this.pendingRejectionCheck = true;
  1147. setTimeout(function rejectionCheck() {
  1148. this.pendingRejectionCheck = false;
  1149. var now = Date.now();
  1150. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1151. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1152. var unhandled = this.unhandledRejections[i].promise._value;
  1153. var msg = 'Unhandled rejection: ' + unhandled;
  1154. if (unhandled.stack) {
  1155. msg += '\n' + unhandled.stack;
  1156. }
  1157. warn(msg);
  1158. this.unhandledRejections.splice(i);
  1159. i--;
  1160. }
  1161. }
  1162. if (this.unhandledRejections.length) {
  1163. this.scheduleRejectionCheck();
  1164. }
  1165. }.bind(this), REJECTION_TIMEOUT);
  1166. }
  1167. };
  1168. function Promise(resolver) {
  1169. this._status = STATUS_PENDING;
  1170. this._handlers = [];
  1171. try {
  1172. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1173. } catch (e) {
  1174. this._reject(e);
  1175. }
  1176. }
  1177. /**
  1178. * Builds a promise that is resolved when all the passed in promises are
  1179. * resolved.
  1180. * @param {array} promises array of data and/or promises to wait for.
  1181. * @return {Promise} New dependent promise.
  1182. */
  1183. Promise.all = function Promise_all(promises) {
  1184. var resolveAll, rejectAll;
  1185. var deferred = new Promise(function (resolve, reject) {
  1186. resolveAll = resolve;
  1187. rejectAll = reject;
  1188. });
  1189. var unresolved = promises.length;
  1190. var results = [];
  1191. if (unresolved === 0) {
  1192. resolveAll(results);
  1193. return deferred;
  1194. }
  1195. function reject(reason) {
  1196. if (deferred._status === STATUS_REJECTED) {
  1197. return;
  1198. }
  1199. results = [];
  1200. rejectAll(reason);
  1201. }
  1202. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1203. var promise = promises[i];
  1204. var resolve = (function(i) {
  1205. return function(value) {
  1206. if (deferred._status === STATUS_REJECTED) {
  1207. return;
  1208. }
  1209. results[i] = value;
  1210. unresolved--;
  1211. if (unresolved === 0) {
  1212. resolveAll(results);
  1213. }
  1214. };
  1215. })(i);
  1216. if (Promise.isPromise(promise)) {
  1217. promise.then(resolve, reject);
  1218. } else {
  1219. resolve(promise);
  1220. }
  1221. }
  1222. return deferred;
  1223. };
  1224. /**
  1225. * Checks if the value is likely a promise (has a 'then' function).
  1226. * @return {boolean} true if value is thenable
  1227. */
  1228. Promise.isPromise = function Promise_isPromise(value) {
  1229. return value && typeof value.then === 'function';
  1230. };
  1231. /**
  1232. * Creates resolved promise
  1233. * @param value resolve value
  1234. * @returns {Promise}
  1235. */
  1236. Promise.resolve = function Promise_resolve(value) {
  1237. return new Promise(function (resolve) { resolve(value); });
  1238. };
  1239. /**
  1240. * Creates rejected promise
  1241. * @param reason rejection value
  1242. * @returns {Promise}
  1243. */
  1244. Promise.reject = function Promise_reject(reason) {
  1245. return new Promise(function (resolve, reject) { reject(reason); });
  1246. };
  1247. Promise.prototype = {
  1248. _status: null,
  1249. _value: null,
  1250. _handlers: null,
  1251. _unhandledRejection: null,
  1252. _updateStatus: function Promise__updateStatus(status, value) {
  1253. if (this._status === STATUS_RESOLVED ||
  1254. this._status === STATUS_REJECTED) {
  1255. return;
  1256. }
  1257. if (status === STATUS_RESOLVED &&
  1258. Promise.isPromise(value)) {
  1259. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1260. this._updateStatus.bind(this, STATUS_REJECTED));
  1261. return;
  1262. }
  1263. this._status = status;
  1264. this._value = value;
  1265. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1266. this._unhandledRejection = true;
  1267. HandlerManager.addUnhandledRejection(this);
  1268. }
  1269. HandlerManager.scheduleHandlers(this);
  1270. },
  1271. _resolve: function Promise_resolve(value) {
  1272. this._updateStatus(STATUS_RESOLVED, value);
  1273. },
  1274. _reject: function Promise_reject(reason) {
  1275. this._updateStatus(STATUS_REJECTED, reason);
  1276. },
  1277. then: function Promise_then(onResolve, onReject) {
  1278. var nextPromise = new Promise(function (resolve, reject) {
  1279. this.resolve = resolve;
  1280. this.reject = reject;
  1281. });
  1282. this._handlers.push({
  1283. thisPromise: this,
  1284. onResolve: onResolve,
  1285. onReject: onReject,
  1286. nextPromise: nextPromise
  1287. });
  1288. HandlerManager.scheduleHandlers(this);
  1289. return nextPromise;
  1290. },
  1291. catch: function Promise_catch(onReject) {
  1292. return this.then(undefined, onReject);
  1293. }
  1294. };
  1295. globalScope.Promise = Promise;
  1296. })();
  1297. (function WeakMapClosure() {
  1298. if (globalScope.WeakMap) {
  1299. return;
  1300. }
  1301. var id = 0;
  1302. function WeakMap() {
  1303. this.id = '$weakmap' + (id++);
  1304. }
  1305. WeakMap.prototype = {
  1306. has: function(obj) {
  1307. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1308. },
  1309. get: function(obj, defaultValue) {
  1310. return this.has(obj) ? obj[this.id] : defaultValue;
  1311. },
  1312. set: function(obj, value) {
  1313. Object.defineProperty(obj, this.id, {
  1314. value: value,
  1315. enumerable: false,
  1316. configurable: true
  1317. });
  1318. },
  1319. delete: function(obj) {
  1320. delete obj[this.id];
  1321. }
  1322. };
  1323. globalScope.WeakMap = WeakMap;
  1324. })();
  1325. var StatTimer = (function StatTimerClosure() {
  1326. function rpad(str, pad, length) {
  1327. while (str.length < length) {
  1328. str += pad;
  1329. }
  1330. return str;
  1331. }
  1332. function StatTimer() {
  1333. this.started = Object.create(null);
  1334. this.times = [];
  1335. this.enabled = true;
  1336. }
  1337. StatTimer.prototype = {
  1338. time: function StatTimer_time(name) {
  1339. if (!this.enabled) {
  1340. return;
  1341. }
  1342. if (name in this.started) {
  1343. warn('Timer is already running for ' + name);
  1344. }
  1345. this.started[name] = Date.now();
  1346. },
  1347. timeEnd: function StatTimer_timeEnd(name) {
  1348. if (!this.enabled) {
  1349. return;
  1350. }
  1351. if (!(name in this.started)) {
  1352. warn('Timer has not been started for ' + name);
  1353. }
  1354. this.times.push({
  1355. 'name': name,
  1356. 'start': this.started[name],
  1357. 'end': Date.now()
  1358. });
  1359. // Remove timer from started so it can be called again.
  1360. delete this.started[name];
  1361. },
  1362. toString: function StatTimer_toString() {
  1363. var i, ii;
  1364. var times = this.times;
  1365. var out = '';
  1366. // Find the longest name for padding purposes.
  1367. var longest = 0;
  1368. for (i = 0, ii = times.length; i < ii; ++i) {
  1369. var name = times[i]['name'];
  1370. if (name.length > longest) {
  1371. longest = name.length;
  1372. }
  1373. }
  1374. for (i = 0, ii = times.length; i < ii; ++i) {
  1375. var span = times[i];
  1376. var duration = span.end - span.start;
  1377. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1378. }
  1379. return out;
  1380. }
  1381. };
  1382. return StatTimer;
  1383. })();
  1384. var createBlob = function createBlob(data, contentType) {
  1385. if (typeof Blob !== 'undefined') {
  1386. return new Blob([data], { type: contentType });
  1387. }
  1388. warn('The "Blob" constructor is not supported.');
  1389. };
  1390. var createObjectURL = (function createObjectURLClosure() {
  1391. // Blob/createObjectURL is not available, falling back to data schema.
  1392. var digits =
  1393. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1394. return function createObjectURL(data, contentType, forceDataSchema) {
  1395. if (!forceDataSchema &&
  1396. typeof URL !== 'undefined' && URL.createObjectURL) {
  1397. var blob = createBlob(data, contentType);
  1398. return URL.createObjectURL(blob);
  1399. }
  1400. var buffer = 'data:' + contentType + ';base64,';
  1401. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1402. var b1 = data[i] & 0xFF;
  1403. var b2 = data[i + 1] & 0xFF;
  1404. var b3 = data[i + 2] & 0xFF;
  1405. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1406. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1407. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1408. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1409. }
  1410. return buffer;
  1411. };
  1412. })();
  1413. function MessageHandler(sourceName, targetName, comObj) {
  1414. this.sourceName = sourceName;
  1415. this.targetName = targetName;
  1416. this.comObj = comObj;
  1417. this.callbackIndex = 1;
  1418. this.postMessageTransfers = true;
  1419. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1420. var ah = this.actionHandler = Object.create(null);
  1421. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1422. var data = event.data;
  1423. if (data.targetName !== this.sourceName) {
  1424. return;
  1425. }
  1426. if (data.isReply) {
  1427. var callbackId = data.callbackId;
  1428. if (data.callbackId in callbacksCapabilities) {
  1429. var callback = callbacksCapabilities[callbackId];
  1430. delete callbacksCapabilities[callbackId];
  1431. if ('error' in data) {
  1432. callback.reject(data.error);
  1433. } else {
  1434. callback.resolve(data.data);
  1435. }
  1436. } else {
  1437. error('Cannot resolve callback ' + callbackId);
  1438. }
  1439. } else if (data.action in ah) {
  1440. var action = ah[data.action];
  1441. if (data.callbackId) {
  1442. var sourceName = this.sourceName;
  1443. var targetName = data.sourceName;
  1444. Promise.resolve().then(function () {
  1445. return action[0].call(action[1], data.data);
  1446. }).then(function (result) {
  1447. comObj.postMessage({
  1448. sourceName: sourceName,
  1449. targetName: targetName,
  1450. isReply: true,
  1451. callbackId: data.callbackId,
  1452. data: result
  1453. });
  1454. }, function (reason) {
  1455. if (reason instanceof Error) {
  1456. // Serialize error to avoid "DataCloneError"
  1457. reason = reason + '';
  1458. }
  1459. comObj.postMessage({
  1460. sourceName: sourceName,
  1461. targetName: targetName,
  1462. isReply: true,
  1463. callbackId: data.callbackId,
  1464. error: reason
  1465. });
  1466. });
  1467. } else {
  1468. action[0].call(action[1], data.data);
  1469. }
  1470. } else {
  1471. error('Unknown action from worker: ' + data.action);
  1472. }
  1473. }.bind(this);
  1474. comObj.addEventListener('message', this._onComObjOnMessage);
  1475. }
  1476. MessageHandler.prototype = {
  1477. on: function messageHandlerOn(actionName, handler, scope) {
  1478. var ah = this.actionHandler;
  1479. if (ah[actionName]) {
  1480. error('There is already an actionName called "' + actionName + '"');
  1481. }
  1482. ah[actionName] = [handler, scope];
  1483. },
  1484. /**
  1485. * Sends a message to the comObj to invoke the action with the supplied data.
  1486. * @param {String} actionName Action to call.
  1487. * @param {JSON} data JSON data to send.
  1488. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1489. */
  1490. send: function messageHandlerSend(actionName, data, transfers) {
  1491. var message = {
  1492. sourceName: this.sourceName,
  1493. targetName: this.targetName,
  1494. action: actionName,
  1495. data: data
  1496. };
  1497. this.postMessage(message, transfers);
  1498. },
  1499. /**
  1500. * Sends a message to the comObj to invoke the action with the supplied data.
  1501. * Expects that other side will callback with the response.
  1502. * @param {String} actionName Action to call.
  1503. * @param {JSON} data JSON data to send.
  1504. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1505. * @returns {Promise} Promise to be resolved with response data.
  1506. */
  1507. sendWithPromise:
  1508. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1509. var callbackId = this.callbackIndex++;
  1510. var message = {
  1511. sourceName: this.sourceName,
  1512. targetName: this.targetName,
  1513. action: actionName,
  1514. data: data,
  1515. callbackId: callbackId
  1516. };
  1517. var capability = createPromiseCapability();
  1518. this.callbacksCapabilities[callbackId] = capability;
  1519. try {
  1520. this.postMessage(message, transfers);
  1521. } catch (e) {
  1522. capability.reject(e);
  1523. }
  1524. return capability.promise;
  1525. },
  1526. /**
  1527. * Sends raw message to the comObj.
  1528. * @private
  1529. * @param message {Object} Raw message.
  1530. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1531. */
  1532. postMessage: function (message, transfers) {
  1533. if (transfers && this.postMessageTransfers) {
  1534. this.comObj.postMessage(message, transfers);
  1535. } else {
  1536. this.comObj.postMessage(message);
  1537. }
  1538. },
  1539. destroy: function () {
  1540. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1541. }
  1542. };
  1543. function loadJpegStream(id, imageUrl, objs) {
  1544. var img = new Image();
  1545. img.onload = (function loadJpegStream_onloadClosure() {
  1546. objs.resolve(id, img);
  1547. });
  1548. img.onerror = (function loadJpegStream_onerrorClosure() {
  1549. objs.resolve(id, null);
  1550. warn('Error during JPEG image loading');
  1551. });
  1552. img.src = imageUrl;
  1553. }
  1554. // Polyfill from https://github.com/Polymer/URL
  1555. /* Any copyright is dedicated to the Public Domain.
  1556. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1557. (function checkURLConstructor(scope) {
  1558. /* jshint ignore:start */
  1559. // feature detect for URL constructor
  1560. var hasWorkingUrl = false;
  1561. try {
  1562. if (typeof URL === 'function' &&
  1563. typeof URL.prototype === 'object' &&
  1564. ('origin' in URL.prototype)) {
  1565. var u = new URL('b', 'http://a');
  1566. u.pathname = 'c%20d';
  1567. hasWorkingUrl = u.href === 'http://a/c%20d';
  1568. }
  1569. } catch(e) { }
  1570. if (hasWorkingUrl)
  1571. return;
  1572. var relative = Object.create(null);
  1573. relative['ftp'] = 21;
  1574. relative['file'] = 0;
  1575. relative['gopher'] = 70;
  1576. relative['http'] = 80;
  1577. relative['https'] = 443;
  1578. relative['ws'] = 80;
  1579. relative['wss'] = 443;
  1580. var relativePathDotMapping = Object.create(null);
  1581. relativePathDotMapping['%2e'] = '.';
  1582. relativePathDotMapping['.%2e'] = '..';
  1583. relativePathDotMapping['%2e.'] = '..';
  1584. relativePathDotMapping['%2e%2e'] = '..';
  1585. function isRelativeScheme(scheme) {
  1586. return relative[scheme] !== undefined;
  1587. }
  1588. function invalid() {
  1589. clear.call(this);
  1590. this._isInvalid = true;
  1591. }
  1592. function IDNAToASCII(h) {
  1593. if ('' == h) {
  1594. invalid.call(this)
  1595. }
  1596. // XXX
  1597. return h.toLowerCase()
  1598. }
  1599. function percentEscape(c) {
  1600. var unicode = c.charCodeAt(0);
  1601. if (unicode > 0x20 &&
  1602. unicode < 0x7F &&
  1603. // " # < > ? `
  1604. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
  1605. ) {
  1606. return c;
  1607. }
  1608. return encodeURIComponent(c);
  1609. }
  1610. function percentEscapeQuery(c) {
  1611. // XXX This actually needs to encode c using encoding and then
  1612. // convert the bytes one-by-one.
  1613. var unicode = c.charCodeAt(0);
  1614. if (unicode > 0x20 &&
  1615. unicode < 0x7F &&
  1616. // " # < > ` (do not escape '?')
  1617. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1
  1618. ) {
  1619. return c;
  1620. }
  1621. return encodeURIComponent(c);
  1622. }
  1623. var EOF = undefined,
  1624. ALPHA = /[a-zA-Z]/,
  1625. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1626. function parse(input, stateOverride, base) {
  1627. function err(message) {
  1628. errors.push(message)
  1629. }
  1630. var state = stateOverride || 'scheme start',
  1631. cursor = 0,
  1632. buffer = '',
  1633. seenAt = false,
  1634. seenBracket = false,
  1635. errors = [];
  1636. loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
  1637. var c = input[cursor];
  1638. switch (state) {
  1639. case 'scheme start':
  1640. if (c && ALPHA.test(c)) {
  1641. buffer += c.toLowerCase(); // ASCII-safe
  1642. state = 'scheme';
  1643. } else if (!stateOverride) {
  1644. buffer = '';
  1645. state = 'no scheme';
  1646. continue;
  1647. } else {
  1648. err('Invalid scheme.');
  1649. break loop;
  1650. }
  1651. break;
  1652. case 'scheme':
  1653. if (c && ALPHANUMERIC.test(c)) {
  1654. buffer += c.toLowerCase(); // ASCII-safe
  1655. } else if (':' == c) {
  1656. this._scheme = buffer;
  1657. buffer = '';
  1658. if (stateOverride) {
  1659. break loop;
  1660. }
  1661. if (isRelativeScheme(this._scheme)) {
  1662. this._isRelative = true;
  1663. }
  1664. if ('file' == this._scheme) {
  1665. state = 'relative';
  1666. } else if (this._isRelative && base && base._scheme == this._scheme) {
  1667. state = 'relative or authority';
  1668. } else if (this._isRelative) {
  1669. state = 'authority first slash';
  1670. } else {
  1671. state = 'scheme data';
  1672. }
  1673. } else if (!stateOverride) {
  1674. buffer = '';
  1675. cursor = 0;
  1676. state = 'no scheme';
  1677. continue;
  1678. } else if (EOF == c) {
  1679. break loop;
  1680. } else {
  1681. err('Code point not allowed in scheme: ' + c)
  1682. break loop;
  1683. }
  1684. break;
  1685. case 'scheme data':
  1686. if ('?' == c) {
  1687. this._query = '?';
  1688. state = 'query';
  1689. } else if ('#' == c) {
  1690. this._fragment = '#';
  1691. state = 'fragment';
  1692. } else {
  1693. // XXX error handling
  1694. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1695. this._schemeData += percentEscape(c);
  1696. }
  1697. }
  1698. break;
  1699. case 'no scheme':
  1700. if (!base || !(isRelativeScheme(base._scheme))) {
  1701. err('Missing scheme.');
  1702. invalid.call(this);
  1703. } else {
  1704. state = 'relative';
  1705. continue;
  1706. }
  1707. break;
  1708. case 'relative or authority':
  1709. if ('/' == c && '/' == input[cursor+1]) {
  1710. state = 'authority ignore slashes';
  1711. } else {
  1712. err('Expected /, got: ' + c);
  1713. state = 'relative';
  1714. continue
  1715. }
  1716. break;
  1717. case 'relative':
  1718. this._isRelative = true;
  1719. if ('file' != this._scheme)
  1720. this._scheme = base._scheme;
  1721. if (EOF == c) {
  1722. this._host = base._host;
  1723. this._port = base._port;
  1724. this._path = base._path.slice();
  1725. this._query = base._query;
  1726. this._username = base._username;
  1727. this._password = base._password;
  1728. break loop;
  1729. } else if ('/' == c || '\\' == c) {
  1730. if ('\\' == c)
  1731. err('\\ is an invalid code point.');
  1732. state = 'relative slash';
  1733. } else if ('?' == c) {
  1734. this._host = base._host;
  1735. this._port = base._port;
  1736. this._path = base._path.slice();
  1737. this._query = '?';
  1738. this._username = base._username;
  1739. this._password = base._password;
  1740. state = 'query';
  1741. } else if ('#' == c) {
  1742. this._host = base._host;
  1743. this._port = base._port;
  1744. this._path = base._path.slice();
  1745. this._query = base._query;
  1746. this._fragment = '#';
  1747. this._username = base._username;
  1748. this._password = base._password;
  1749. state = 'fragment';
  1750. } else {
  1751. var nextC = input[cursor+1]
  1752. var nextNextC = input[cursor+2]
  1753. if (
  1754. 'file' != this._scheme || !ALPHA.test(c) ||
  1755. (nextC != ':' && nextC != '|') ||
  1756. (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) {
  1757. this._host = base._host;
  1758. this._port = base._port;
  1759. this._username = base._username;
  1760. this._password = base._password;
  1761. this._path = base._path.slice();
  1762. this._path.pop();
  1763. }
  1764. state = 'relative path';
  1765. continue;
  1766. }
  1767. break;
  1768. case 'relative slash':
  1769. if ('/' == c || '\\' == c) {
  1770. if ('\\' == c) {
  1771. err('\\ is an invalid code point.');
  1772. }
  1773. if ('file' == this._scheme) {
  1774. state = 'file host';
  1775. } else {
  1776. state = 'authority ignore slashes';
  1777. }
  1778. } else {
  1779. if ('file' != this._scheme) {
  1780. this._host = base._host;
  1781. this._port = base._port;
  1782. this._username = base._username;
  1783. this._password = base._password;
  1784. }
  1785. state = 'relative path';
  1786. continue;
  1787. }
  1788. break;
  1789. case 'authority first slash':
  1790. if ('/' == c) {
  1791. state = 'authority second slash';
  1792. } else {
  1793. err("Expected '/', got: " + c);
  1794. state = 'authority ignore slashes';
  1795. continue;
  1796. }
  1797. break;
  1798. case 'authority second slash':
  1799. state = 'authority ignore slashes';
  1800. if ('/' != c) {
  1801. err("Expected '/', got: " + c);
  1802. continue;
  1803. }
  1804. break;
  1805. case 'authority ignore slashes':
  1806. if ('/' != c && '\\' != c) {
  1807. state = 'authority';
  1808. continue;
  1809. } else {
  1810. err('Expected authority, got: ' + c);
  1811. }
  1812. break;
  1813. case 'authority':
  1814. if ('@' == c) {
  1815. if (seenAt) {
  1816. err('@ already seen.');
  1817. buffer += '%40';
  1818. }
  1819. seenAt = true;
  1820. for (var i = 0; i < buffer.length; i++) {
  1821. var cp = buffer[i];
  1822. if ('\t' == cp || '\n' == cp || '\r' == cp) {
  1823. err('Invalid whitespace in authority.');
  1824. continue;
  1825. }
  1826. // XXX check URL code points
  1827. if (':' == cp && null === this._password) {
  1828. this._password = '';
  1829. continue;
  1830. }
  1831. var tempC = percentEscape(cp);
  1832. (null !== this._password) ? this._password += tempC : this._username += tempC;
  1833. }
  1834. buffer = '';
  1835. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1836. cursor -= buffer.length;
  1837. buffer = '';
  1838. state = 'host';
  1839. continue;
  1840. } else {
  1841. buffer += c;
  1842. }
  1843. break;
  1844. case 'file host':
  1845. if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1846. if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
  1847. state = 'relative path';
  1848. } else if (buffer.length == 0) {
  1849. state = 'relative path start';
  1850. } else {
  1851. this._host = IDNAToASCII.call(this, buffer);
  1852. buffer = '';
  1853. state = 'relative path start';
  1854. }
  1855. continue;
  1856. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1857. err('Invalid whitespace in file host.');
  1858. } else {
  1859. buffer += c;
  1860. }
  1861. break;
  1862. case 'host':
  1863. case 'hostname':
  1864. if (':' == c && !seenBracket) {
  1865. // XXX host parsing
  1866. this._host = IDNAToASCII.call(this, buffer);
  1867. buffer = '';
  1868. state = 'port';
  1869. if ('hostname' == stateOverride) {
  1870. break loop;
  1871. }
  1872. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1873. this._host = IDNAToASCII.call(this, buffer);
  1874. buffer = '';
  1875. state = 'relative path start';
  1876. if (stateOverride) {
  1877. break loop;
  1878. }
  1879. continue;
  1880. } else if ('\t' != c && '\n' != c && '\r' != c) {
  1881. if ('[' == c) {
  1882. seenBracket = true;
  1883. } else if (']' == c) {
  1884. seenBracket = false;
  1885. }
  1886. buffer += c;
  1887. } else {
  1888. err('Invalid code point in host/hostname: ' + c);
  1889. }
  1890. break;
  1891. case 'port':
  1892. if (/[0-9]/.test(c)) {
  1893. buffer += c;
  1894. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
  1895. if ('' != buffer) {
  1896. var temp = parseInt(buffer, 10);
  1897. if (temp != relative[this._scheme]) {
  1898. this._port = temp + '';
  1899. }
  1900. buffer = '';
  1901. }
  1902. if (stateOverride) {
  1903. break loop;
  1904. }
  1905. state = 'relative path start';
  1906. continue;
  1907. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1908. err('Invalid code point in port: ' + c);
  1909. } else {
  1910. invalid.call(this);
  1911. }
  1912. break;
  1913. case 'relative path start':
  1914. if ('\\' == c)
  1915. err("'\\' not allowed in path.");
  1916. state = 'relative path';
  1917. if ('/' != c && '\\' != c) {
  1918. continue;
  1919. }
  1920. break;
  1921. case 'relative path':
  1922. if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) {
  1923. if ('\\' == c) {
  1924. err('\\ not allowed in relative path.');
  1925. }
  1926. var tmp;
  1927. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1928. buffer = tmp;
  1929. }
  1930. if ('..' == buffer) {
  1931. this._path.pop();
  1932. if ('/' != c && '\\' != c) {
  1933. this._path.push('');
  1934. }
  1935. } else if ('.' == buffer && '/' != c && '\\' != c) {
  1936. this._path.push('');
  1937. } else if ('.' != buffer) {
  1938. if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
  1939. buffer = buffer[0] + ':';
  1940. }
  1941. this._path.push(buffer);
  1942. }
  1943. buffer = '';
  1944. if ('?' == c) {
  1945. this._query = '?';
  1946. state = 'query';
  1947. } else if ('#' == c) {
  1948. this._fragment = '#';
  1949. state = 'fragment';
  1950. }
  1951. } else if ('\t' != c && '\n' != c && '\r' != c) {
  1952. buffer += percentEscape(c);
  1953. }
  1954. break;
  1955. case 'query':
  1956. if (!stateOverride && '#' == c) {
  1957. this._fragment = '#';
  1958. state = 'fragment';
  1959. } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1960. this._query += percentEscapeQuery(c);
  1961. }
  1962. break;
  1963. case 'fragment':
  1964. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1965. this._fragment += c;
  1966. }
  1967. break;
  1968. }
  1969. cursor++;
  1970. }
  1971. }
  1972. function clear() {
  1973. this._scheme = '';
  1974. this._schemeData = '';
  1975. this._username = '';
  1976. this._password = null;
  1977. this._host = '';
  1978. this._port = '';
  1979. this._path = [];
  1980. this._query = '';
  1981. this._fragment = '';
  1982. this._isInvalid = false;
  1983. this._isRelative = false;
  1984. }
  1985. // Does not process domain names or IP addresses.
  1986. // Does not handle encoding for the query parameter.
  1987. function jURL(url, base /* , encoding */) {
  1988. if (base !== undefined && !(base instanceof jURL))
  1989. base = new jURL(String(base));
  1990. this._url = url;
  1991. clear.call(this);
  1992. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  1993. // encoding = encoding || 'utf-8'
  1994. parse.call(this, input, null, base);
  1995. }
  1996. jURL.prototype = {
  1997. toString: function() {
  1998. return this.href;
  1999. },
  2000. get href() {
  2001. if (this._isInvalid)
  2002. return this._url;
  2003. var authority = '';
  2004. if ('' != this._username || null != this._password) {
  2005. authority = this._username +
  2006. (null != this._password ? ':' + this._password : '') + '@';
  2007. }
  2008. return this.protocol +
  2009. (this._isRelative ? '//' + authority + this.host : '') +
  2010. this.pathname + this._query + this._fragment;
  2011. },
  2012. set href(href) {
  2013. clear.call(this);
  2014. parse.call(this, href);
  2015. },
  2016. get protocol() {
  2017. return this._scheme + ':';
  2018. },
  2019. set protocol(protocol) {
  2020. if (this._isInvalid)
  2021. return;
  2022. parse.call(this, protocol + ':', 'scheme start');
  2023. },
  2024. get host() {
  2025. return this._isInvalid ? '' : this._port ?
  2026. this._host + ':' + this._port : this._host;
  2027. },
  2028. set host(host) {
  2029. if (this._isInvalid || !this._isRelative)
  2030. return;
  2031. parse.call(this, host, 'host');
  2032. },
  2033. get hostname() {
  2034. return this._host;
  2035. },
  2036. set hostname(hostname) {
  2037. if (this._isInvalid || !this._isRelative)
  2038. return;
  2039. parse.call(this, hostname, 'hostname');
  2040. },
  2041. get port() {
  2042. return this._port;
  2043. },
  2044. set port(port) {
  2045. if (this._isInvalid || !this._isRelative)
  2046. return;
  2047. parse.call(this, port, 'port');
  2048. },
  2049. get pathname() {
  2050. return this._isInvalid ? '' : this._isRelative ?
  2051. '/' + this._path.join('/') : this._schemeData;
  2052. },
  2053. set pathname(pathname) {
  2054. if (this._isInvalid || !this._isRelative)
  2055. return;
  2056. this._path = [];
  2057. parse.call(this, pathname, 'relative path start');
  2058. },
  2059. get search() {
  2060. return this._isInvalid || !this._query || '?' == this._query ?
  2061. '' : this._query;
  2062. },
  2063. set search(search) {
  2064. if (this._isInvalid || !this._isRelative)
  2065. return;
  2066. this._query = '?';
  2067. if ('?' == search[0])
  2068. search = search.slice(1);
  2069. parse.call(this, search, 'query');
  2070. },
  2071. get hash() {
  2072. return this._isInvalid || !this._fragment || '#' == this._fragment ?
  2073. '' : this._fragment;
  2074. },
  2075. set hash(hash) {
  2076. if (this._isInvalid)
  2077. return;
  2078. this._fragment = '#';
  2079. if ('#' == hash[0])
  2080. hash = hash.slice(1);
  2081. parse.call(this, hash, 'fragment');
  2082. },
  2083. get origin() {
  2084. var host;
  2085. if (this._isInvalid || !this._scheme) {
  2086. return '';
  2087. }
  2088. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2089. // Gecko throws error for "data://"
  2090. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2091. // Gecko returns String("") for file: mailto:
  2092. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2093. switch (this._scheme) {
  2094. case 'data':
  2095. case 'file':
  2096. case 'javascript':
  2097. case 'mailto':
  2098. return 'null';
  2099. }
  2100. host = this.host;
  2101. if (!host) {
  2102. return '';
  2103. }
  2104. return this._scheme + '://' + host;
  2105. }
  2106. };
  2107. // Copy over the static methods
  2108. var OriginalURL = scope.URL;
  2109. if (OriginalURL) {
  2110. jURL.createObjectURL = function(blob) {
  2111. // IE extension allows a second optional options argument.
  2112. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2113. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2114. };
  2115. jURL.revokeObjectURL = function(url) {
  2116. OriginalURL.revokeObjectURL(url);
  2117. };
  2118. }
  2119. scope.URL = jURL;
  2120. /* jshint ignore:end */
  2121. })(globalScope);
  2122. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2123. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2124. exports.OPS = OPS;
  2125. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2126. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2127. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2128. exports.AnnotationFlag = AnnotationFlag;
  2129. exports.AnnotationType = AnnotationType;
  2130. exports.FontType = FontType;
  2131. exports.ImageKind = ImageKind;
  2132. exports.InvalidPDFException = InvalidPDFException;
  2133. exports.MessageHandler = MessageHandler;
  2134. exports.MissingDataException = MissingDataException;
  2135. exports.MissingPDFException = MissingPDFException;
  2136. exports.NotImplementedException = NotImplementedException;
  2137. exports.PageViewport = PageViewport;
  2138. exports.PasswordException = PasswordException;
  2139. exports.PasswordResponses = PasswordResponses;
  2140. exports.StatTimer = StatTimer;
  2141. exports.StreamType = StreamType;
  2142. exports.TextRenderingMode = TextRenderingMode;
  2143. exports.UnexpectedResponseException = UnexpectedResponseException;
  2144. exports.UnknownErrorException = UnknownErrorException;
  2145. exports.Util = Util;
  2146. exports.XRefParseException = XRefParseException;
  2147. exports.arrayByteLength = arrayByteLength;
  2148. exports.arraysToBytes = arraysToBytes;
  2149. exports.assert = assert;
  2150. exports.bytesToString = bytesToString;
  2151. exports.createBlob = createBlob;
  2152. exports.createPromiseCapability = createPromiseCapability;
  2153. exports.createObjectURL = createObjectURL;
  2154. exports.deprecated = deprecated;
  2155. exports.error = error;
  2156. exports.getLookupTableFactory = getLookupTableFactory;
  2157. exports.getVerbosityLevel = getVerbosityLevel;
  2158. exports.globalScope = globalScope;
  2159. exports.info = info;
  2160. exports.isArray = isArray;
  2161. exports.isArrayBuffer = isArrayBuffer;
  2162. exports.isBool = isBool;
  2163. exports.isEmptyObj = isEmptyObj;
  2164. exports.isInt = isInt;
  2165. exports.isNum = isNum;
  2166. exports.isString = isString;
  2167. exports.isSpace = isSpace;
  2168. exports.isSameOrigin = isSameOrigin;
  2169. exports.isValidUrl = isValidUrl;
  2170. exports.isLittleEndian = isLittleEndian;
  2171. exports.isEvalSupported = isEvalSupported;
  2172. exports.loadJpegStream = loadJpegStream;
  2173. exports.log2 = log2;
  2174. exports.readInt8 = readInt8;
  2175. exports.readUint16 = readUint16;
  2176. exports.readUint32 = readUint32;
  2177. exports.removeNullCharacters = removeNullCharacters;
  2178. exports.setVerbosityLevel = setVerbosityLevel;
  2179. exports.shadow = shadow;
  2180. exports.string32 = string32;
  2181. exports.stringToBytes = stringToBytes;
  2182. exports.stringToPDFString = stringToPDFString;
  2183. exports.stringToUTF8String = stringToUTF8String;
  2184. exports.utf8StringToString = utf8StringToString;
  2185. exports.warn = warn;
  2186. }));
  2187. (function (root, factory) {
  2188. {
  2189. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil);
  2190. }
  2191. }(this, function (exports, sharedUtil) {
  2192. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2193. var warn = sharedUtil.warn;
  2194. /**
  2195. * Optimised CSS custom property getter/setter.
  2196. * @class
  2197. */
  2198. var CustomStyle = (function CustomStyleClosure() {
  2199. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2200. // animate-css-transforms-firefox-webkit.html
  2201. // in some versions of IE9 it is critical that ms appear in this list
  2202. // before Moz
  2203. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  2204. var _cache = Object.create(null);
  2205. function CustomStyle() {}
  2206. CustomStyle.getProp = function get(propName, element) {
  2207. // check cache only when no element is given
  2208. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2209. return _cache[propName];
  2210. }
  2211. element = element || document.documentElement;
  2212. var style = element.style, prefixed, uPropName;
  2213. // test standard property first
  2214. if (typeof style[propName] === 'string') {
  2215. return (_cache[propName] = propName);
  2216. }
  2217. // capitalize
  2218. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2219. // test vendor specific properties
  2220. for (var i = 0, l = prefixes.length; i < l; i++) {
  2221. prefixed = prefixes[i] + uPropName;
  2222. if (typeof style[prefixed] === 'string') {
  2223. return (_cache[propName] = prefixed);
  2224. }
  2225. }
  2226. //if all fails then set to undefined
  2227. return (_cache[propName] = 'undefined');
  2228. };
  2229. CustomStyle.setProp = function set(propName, element, str) {
  2230. var prop = this.getProp(propName);
  2231. if (prop !== 'undefined') {
  2232. element.style[prop] = str;
  2233. }
  2234. };
  2235. return CustomStyle;
  2236. })();
  2237. function hasCanvasTypedArrays() {
  2238. var canvas = document.createElement('canvas');
  2239. canvas.width = canvas.height = 1;
  2240. var ctx = canvas.getContext('2d');
  2241. var imageData = ctx.createImageData(1, 1);
  2242. return (typeof imageData.data.buffer !== 'undefined');
  2243. }
  2244. var LinkTarget = {
  2245. NONE: 0, // Default value.
  2246. SELF: 1,
  2247. BLANK: 2,
  2248. PARENT: 3,
  2249. TOP: 4,
  2250. };
  2251. var LinkTargetStringMap = [
  2252. '',
  2253. '_self',
  2254. '_blank',
  2255. '_parent',
  2256. '_top'
  2257. ];
  2258. /**
  2259. * @typedef ExternalLinkParameters
  2260. * @typedef {Object} ExternalLinkParameters
  2261. * @property {string} url - An absolute URL.
  2262. * @property {LinkTarget} target - The link target.
  2263. * @property {string} rel - The link relationship.
  2264. */
  2265. /**
  2266. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2267. * @param {HTMLLinkElement} link - The link element.
  2268. * @param {ExternalLinkParameters} params
  2269. */
  2270. function addLinkAttributes(link, params) {
  2271. var url = params && params.url;
  2272. link.href = link.title = (url ? removeNullCharacters(url) : '');
  2273. if (url) {
  2274. var target = params.target;
  2275. if (typeof target === 'undefined') {
  2276. target = getDefaultSetting('externalLinkTarget');
  2277. }
  2278. link.target = LinkTargetStringMap[target];
  2279. var rel = params.rel;
  2280. if (typeof rel === 'undefined') {
  2281. rel = getDefaultSetting('externalLinkRel');
  2282. }
  2283. link.rel = rel;
  2284. }
  2285. }
  2286. // Gets the file name from a given URL.
  2287. function getFilenameFromUrl(url) {
  2288. var anchor = url.indexOf('#');
  2289. var query = url.indexOf('?');
  2290. var end = Math.min(
  2291. anchor > 0 ? anchor : url.length,
  2292. query > 0 ? query : url.length);
  2293. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2294. }
  2295. function getDefaultSetting(id) {
  2296. // The list of the settings and their default is maintained for backward
  2297. // compatibility and shall not be extended or modified. See also global.js.
  2298. var globalSettings = sharedUtil.globalScope.PDFJS;
  2299. switch (id) {
  2300. case 'pdfBug':
  2301. return globalSettings ? globalSettings.pdfBug : false;
  2302. case 'disableAutoFetch':
  2303. return globalSettings ? globalSettings.disableAutoFetch : false;
  2304. case 'disableStream':
  2305. return globalSettings ? globalSettings.disableStream : false;
  2306. case 'disableRange':
  2307. return globalSettings ? globalSettings.disableRange : false;
  2308. case 'disableFontFace':
  2309. return globalSettings ? globalSettings.disableFontFace : false;
  2310. case 'disableCreateObjectURL':
  2311. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2312. case 'disableWebGL':
  2313. return globalSettings ? globalSettings.disableWebGL : true;
  2314. case 'cMapUrl':
  2315. return globalSettings ? globalSettings.cMapUrl : null;
  2316. case 'cMapPacked':
  2317. return globalSettings ? globalSettings.cMapPacked : false;
  2318. case 'postMessageTransfers':
  2319. return globalSettings ? globalSettings.postMessageTransfers : true;
  2320. case 'workerSrc':
  2321. return globalSettings ? globalSettings.workerSrc : null;
  2322. case 'disableWorker':
  2323. return globalSettings ? globalSettings.disableWorker : false;
  2324. case 'maxImageSize':
  2325. return globalSettings ? globalSettings.maxImageSize : -1;
  2326. case 'imageResourcesPath':
  2327. return globalSettings ? globalSettings.imageResourcesPath : '';
  2328. case 'isEvalSupported':
  2329. return globalSettings ? globalSettings.isEvalSupported : true;
  2330. case 'externalLinkTarget':
  2331. if (!globalSettings) {
  2332. return LinkTarget.NONE;
  2333. }
  2334. switch (globalSettings.externalLinkTarget) {
  2335. case LinkTarget.NONE:
  2336. case LinkTarget.SELF:
  2337. case LinkTarget.BLANK:
  2338. case LinkTarget.PARENT:
  2339. case LinkTarget.TOP:
  2340. return globalSettings.externalLinkTarget;
  2341. }
  2342. warn('PDFJS.externalLinkTarget is invalid: ' +
  2343. globalSettings.externalLinkTarget);
  2344. // Reset the external link target, to suppress further warnings.
  2345. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2346. return LinkTarget.NONE;
  2347. case 'externalLinkRel':
  2348. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2349. case 'enableStats':
  2350. return !!(globalSettings && globalSettings.enableStats);
  2351. default:
  2352. throw new Error('Unknown default setting: ' + id);
  2353. }
  2354. }
  2355. function isExternalLinkTargetSet() {
  2356. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2357. switch (externalLinkTarget) {
  2358. case LinkTarget.NONE:
  2359. return false;
  2360. case LinkTarget.SELF:
  2361. case LinkTarget.BLANK:
  2362. case LinkTarget.PARENT:
  2363. case LinkTarget.TOP:
  2364. return true;
  2365. }
  2366. }
  2367. exports.CustomStyle = CustomStyle;
  2368. exports.addLinkAttributes = addLinkAttributes;
  2369. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2370. exports.getFilenameFromUrl = getFilenameFromUrl;
  2371. exports.LinkTarget = LinkTarget;
  2372. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2373. exports.getDefaultSetting = getDefaultSetting;
  2374. }));
  2375. (function (root, factory) {
  2376. {
  2377. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil);
  2378. }
  2379. }(this, function (exports, sharedUtil) {
  2380. var assert = sharedUtil.assert;
  2381. var bytesToString = sharedUtil.bytesToString;
  2382. var string32 = sharedUtil.string32;
  2383. var shadow = sharedUtil.shadow;
  2384. var warn = sharedUtil.warn;
  2385. function FontLoader(docId) {
  2386. this.docId = docId;
  2387. this.styleElement = null;
  2388. this.nativeFontFaces = [];
  2389. this.loadTestFontId = 0;
  2390. this.loadingContext = {
  2391. requests: [],
  2392. nextRequestId: 0
  2393. };
  2394. }
  2395. FontLoader.prototype = {
  2396. insertRule: function fontLoaderInsertRule(rule) {
  2397. var styleElement = this.styleElement;
  2398. if (!styleElement) {
  2399. styleElement = this.styleElement = document.createElement('style');
  2400. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2401. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2402. styleElement);
  2403. }
  2404. var styleSheet = styleElement.sheet;
  2405. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2406. },
  2407. clear: function fontLoaderClear() {
  2408. var styleElement = this.styleElement;
  2409. if (styleElement) {
  2410. styleElement.parentNode.removeChild(styleElement);
  2411. styleElement = this.styleElement = null;
  2412. }
  2413. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2414. document.fonts.delete(nativeFontFace);
  2415. });
  2416. this.nativeFontFaces.length = 0;
  2417. },
  2418. get loadTestFont() {
  2419. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2420. // height.
  2421. return shadow(this, 'loadTestFont', atob(
  2422. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2423. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2424. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2425. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2426. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2427. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2428. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2429. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2430. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2431. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2432. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2433. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2434. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2435. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2436. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2437. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2438. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2439. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2440. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2441. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2442. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2443. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2444. ));
  2445. },
  2446. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2447. this.nativeFontFaces.push(nativeFontFace);
  2448. document.fonts.add(nativeFontFace);
  2449. },
  2450. bind: function fontLoaderBind(fonts, callback) {
  2451. var rules = [];
  2452. var fontsToLoad = [];
  2453. var fontLoadPromises = [];
  2454. var getNativeFontPromise = function(nativeFontFace) {
  2455. // Return a promise that is always fulfilled, even when the font fails to
  2456. // load.
  2457. return nativeFontFace.loaded.catch(function(e) {
  2458. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2459. });
  2460. };
  2461. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2462. var font = fonts[i];
  2463. // Add the font to the DOM only once or skip if the font
  2464. // is already loaded.
  2465. if (font.attached || font.loading === false) {
  2466. continue;
  2467. }
  2468. font.attached = true;
  2469. if (FontLoader.isFontLoadingAPISupported) {
  2470. var nativeFontFace = font.createNativeFontFace();
  2471. if (nativeFontFace) {
  2472. this.addNativeFontFace(nativeFontFace);
  2473. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2474. }
  2475. } else {
  2476. var rule = font.createFontFaceRule();
  2477. if (rule) {
  2478. this.insertRule(rule);
  2479. rules.push(rule);
  2480. fontsToLoad.push(font);
  2481. }
  2482. }
  2483. }
  2484. var request = this.queueLoadingCallback(callback);
  2485. if (FontLoader.isFontLoadingAPISupported) {
  2486. Promise.all(fontLoadPromises).then(function() {
  2487. request.complete();
  2488. });
  2489. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2490. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2491. } else {
  2492. request.complete();
  2493. }
  2494. },
  2495. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  2496. function LoadLoader_completeRequest() {
  2497. assert(!request.end, 'completeRequest() cannot be called twice');
  2498. request.end = Date.now();
  2499. // sending all completed requests in order how they were queued
  2500. while (context.requests.length > 0 && context.requests[0].end) {
  2501. var otherRequest = context.requests.shift();
  2502. setTimeout(otherRequest.callback, 0);
  2503. }
  2504. }
  2505. var context = this.loadingContext;
  2506. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  2507. var request = {
  2508. id: requestId,
  2509. complete: LoadLoader_completeRequest,
  2510. callback: callback,
  2511. started: Date.now()
  2512. };
  2513. context.requests.push(request);
  2514. return request;
  2515. },
  2516. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  2517. fonts,
  2518. request) {
  2519. /** Hack begin */
  2520. // There's currently no event when a font has finished downloading so the
  2521. // following code is a dirty hack to 'guess' when a font is
  2522. // ready. It's assumed fonts are loaded in order, so add a known test
  2523. // font after the desired fonts and then test for the loading of that
  2524. // test font.
  2525. function int32(data, offset) {
  2526. return (data.charCodeAt(offset) << 24) |
  2527. (data.charCodeAt(offset + 1) << 16) |
  2528. (data.charCodeAt(offset + 2) << 8) |
  2529. (data.charCodeAt(offset + 3) & 0xff);
  2530. }
  2531. function spliceString(s, offset, remove, insert) {
  2532. var chunk1 = s.substr(0, offset);
  2533. var chunk2 = s.substr(offset + remove);
  2534. return chunk1 + insert + chunk2;
  2535. }
  2536. var i, ii;
  2537. var canvas = document.createElement('canvas');
  2538. canvas.width = 1;
  2539. canvas.height = 1;
  2540. var ctx = canvas.getContext('2d');
  2541. var called = 0;
  2542. function isFontReady(name, callback) {
  2543. called++;
  2544. // With setTimeout clamping this gives the font ~100ms to load.
  2545. if(called > 30) {
  2546. warn('Load test font never loaded.');
  2547. callback();
  2548. return;
  2549. }
  2550. ctx.font = '30px ' + name;
  2551. ctx.fillText('.', 0, 20);
  2552. var imageData = ctx.getImageData(0, 0, 1, 1);
  2553. if (imageData.data[3] > 0) {
  2554. callback();
  2555. return;
  2556. }
  2557. setTimeout(isFontReady.bind(null, name, callback));
  2558. }
  2559. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2560. // Chromium seems to cache fonts based on a hash of the actual font data,
  2561. // so the font must be modified for each load test else it will appear to
  2562. // be loaded already.
  2563. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2564. // font by splitting it in chunks before hand and padding the font id.
  2565. var data = this.loadTestFont;
  2566. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  2567. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  2568. loadTestFontId);
  2569. // CFF checksum is important for IE, adjusting it
  2570. var CFF_CHECKSUM_OFFSET = 16;
  2571. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  2572. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2573. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2574. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  2575. }
  2576. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  2577. checksum = (checksum - XXXX_VALUE +
  2578. int32(loadTestFontId + 'XXX', i)) | 0;
  2579. }
  2580. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2581. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2582. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  2583. url + '}';
  2584. this.insertRule(rule);
  2585. var names = [];
  2586. for (i = 0, ii = fonts.length; i < ii; i++) {
  2587. names.push(fonts[i].loadedName);
  2588. }
  2589. names.push(loadTestFontId);
  2590. var div = document.createElement('div');
  2591. div.setAttribute('style',
  2592. 'visibility: hidden;' +
  2593. 'width: 10px; height: 10px;' +
  2594. 'position: absolute; top: 0px; left: 0px;');
  2595. for (i = 0, ii = names.length; i < ii; ++i) {
  2596. var span = document.createElement('span');
  2597. span.textContent = 'Hi';
  2598. span.style.fontFamily = names[i];
  2599. div.appendChild(span);
  2600. }
  2601. document.body.appendChild(div);
  2602. isFontReady(loadTestFontId, function() {
  2603. document.body.removeChild(div);
  2604. request.complete();
  2605. });
  2606. /** Hack end */
  2607. }
  2608. };
  2609. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' &&
  2610. !!document.fonts;
  2611. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2612. get: function () {
  2613. if (typeof navigator === 'undefined') {
  2614. // node.js - we can pretend sync font loading is supported.
  2615. return shadow(FontLoader, 'isSyncFontLoadingSupported', true);
  2616. }
  2617. var supported = false;
  2618. // User agent string sniffing is bad, but there is no reliable way to tell
  2619. // if font is fully loaded and ready to be used with canvas.
  2620. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2621. if (m && m[1] >= 14) {
  2622. supported = true;
  2623. }
  2624. // TODO other browsers
  2625. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  2626. },
  2627. enumerable: true,
  2628. configurable: true
  2629. });
  2630. var IsEvalSupportedCached = {
  2631. get value() {
  2632. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2633. }
  2634. };
  2635. var FontFaceObject = (function FontFaceObjectClosure() {
  2636. function FontFaceObject(translatedData, options) {
  2637. this.compiledGlyphs = Object.create(null);
  2638. // importing translated data
  2639. for (var i in translatedData) {
  2640. this[i] = translatedData[i];
  2641. }
  2642. this.options = options;
  2643. }
  2644. FontFaceObject.prototype = {
  2645. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2646. if (!this.data) {
  2647. return null;
  2648. }
  2649. if (this.options.disableFontFace) {
  2650. this.disableFontFace = true;
  2651. return null;
  2652. }
  2653. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2654. if (this.options.fontRegistry) {
  2655. this.options.fontRegistry.registerFont(this);
  2656. }
  2657. return nativeFontFace;
  2658. },
  2659. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2660. if (!this.data) {
  2661. return null;
  2662. }
  2663. if (this.options.disableFontFace) {
  2664. this.disableFontFace = true;
  2665. return null;
  2666. }
  2667. var data = bytesToString(new Uint8Array(this.data));
  2668. var fontName = this.loadedName;
  2669. // Add the font-face rule to the document
  2670. var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
  2671. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2672. if (this.options.fontRegistry) {
  2673. this.options.fontRegistry.registerFont(this, url);
  2674. }
  2675. return rule;
  2676. },
  2677. getPathGenerator:
  2678. function FontFaceObject_getPathGenerator(objs, character) {
  2679. if (!(character in this.compiledGlyphs)) {
  2680. var cmds = objs.get(this.loadedName + '_path_' + character);
  2681. var current, i, len;
  2682. // If we can, compile cmds into JS for MAXIMUM SPEED
  2683. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2684. var args, js = '';
  2685. for (i = 0, len = cmds.length; i < len; i++) {
  2686. current = cmds[i];
  2687. if (current.args !== undefined) {
  2688. args = current.args.join(',');
  2689. } else {
  2690. args = '';
  2691. }
  2692. js += 'c.' + current.cmd + '(' + args + ');\n';
  2693. }
  2694. /* jshint -W054 */
  2695. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2696. } else {
  2697. // But fall back on using Function.prototype.apply() if we're
  2698. // blocked from using eval() for whatever reason (like CSP policies)
  2699. this.compiledGlyphs[character] = function(c, size) {
  2700. for (i = 0, len = cmds.length; i < len; i++) {
  2701. current = cmds[i];
  2702. if (current.cmd === 'scale') {
  2703. current.args = [size, -size];
  2704. }
  2705. c[current.cmd].apply(c, current.args);
  2706. }
  2707. };
  2708. }
  2709. }
  2710. return this.compiledGlyphs[character];
  2711. }
  2712. };
  2713. return FontFaceObject;
  2714. })();
  2715. exports.FontFaceObject = FontFaceObject;
  2716. exports.FontLoader = FontLoader;
  2717. }));
  2718. (function (root, factory) {
  2719. {
  2720. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  2721. }
  2722. }(this, function (exports, sharedUtil) {
  2723. var error = sharedUtil.error;
  2724. function fixMetadata(meta) {
  2725. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2726. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2727. function(code, d1, d2, d3) {
  2728. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2729. });
  2730. var chars = '';
  2731. for (var i = 0; i < bytes.length; i += 2) {
  2732. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2733. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2734. code !== 38 && false ? String.fromCharCode(code) :
  2735. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2736. }
  2737. return '>' + chars;
  2738. });
  2739. }
  2740. function Metadata(meta) {
  2741. if (typeof meta === 'string') {
  2742. // Ghostscript produces invalid metadata
  2743. meta = fixMetadata(meta);
  2744. var parser = new DOMParser();
  2745. meta = parser.parseFromString(meta, 'application/xml');
  2746. } else if (!(meta instanceof Document)) {
  2747. error('Metadata: Invalid metadata object');
  2748. }
  2749. this.metaDocument = meta;
  2750. this.metadata = Object.create(null);
  2751. this.parse();
  2752. }
  2753. Metadata.prototype = {
  2754. parse: function Metadata_parse() {
  2755. var doc = this.metaDocument;
  2756. var rdf = doc.documentElement;
  2757. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2758. rdf = rdf.firstChild;
  2759. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2760. rdf = rdf.nextSibling;
  2761. }
  2762. }
  2763. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2764. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2765. return;
  2766. }
  2767. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2768. for (i = 0, length = children.length; i < length; i++) {
  2769. desc = children[i];
  2770. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2771. continue;
  2772. }
  2773. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2774. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2775. entry = desc.childNodes[ii];
  2776. name = entry.nodeName.toLowerCase();
  2777. this.metadata[name] = entry.textContent.trim();
  2778. }
  2779. }
  2780. }
  2781. },
  2782. get: function Metadata_get(name) {
  2783. return this.metadata[name] || null;
  2784. },
  2785. has: function Metadata_has(name) {
  2786. return typeof this.metadata[name] !== 'undefined';
  2787. }
  2788. };
  2789. exports.Metadata = Metadata;
  2790. }));
  2791. (function (root, factory) {
  2792. {
  2793. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  2794. }
  2795. }(this, function (exports, sharedUtil) {
  2796. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2797. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2798. var ImageKind = sharedUtil.ImageKind;
  2799. var OPS = sharedUtil.OPS;
  2800. var Util = sharedUtil.Util;
  2801. var isNum = sharedUtil.isNum;
  2802. var isArray = sharedUtil.isArray;
  2803. var warn = sharedUtil.warn;
  2804. var createObjectURL = sharedUtil.createObjectURL;
  2805. var SVG_DEFAULTS = {
  2806. fontStyle: 'normal',
  2807. fontWeight: 'normal',
  2808. fillColor: '#000000'
  2809. };
  2810. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  2811. var PNG_HEADER =
  2812. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  2813. var CHUNK_WRAPPER_SIZE = 12;
  2814. var crcTable = new Int32Array(256);
  2815. for (var i = 0; i < 256; i++) {
  2816. var c = i;
  2817. for (var h = 0; h < 8; h++) {
  2818. if (c & 1) {
  2819. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  2820. } else {
  2821. c = (c >> 1) & 0x7fffffff;
  2822. }
  2823. }
  2824. crcTable[i] = c;
  2825. }
  2826. function crc32(data, start, end) {
  2827. var crc = -1;
  2828. for (var i = start; i < end; i++) {
  2829. var a = (crc ^ data[i]) & 0xff;
  2830. var b = crcTable[a];
  2831. crc = (crc >>> 8) ^ b;
  2832. }
  2833. return crc ^ -1;
  2834. }
  2835. function writePngChunk(type, body, data, offset) {
  2836. var p = offset;
  2837. var len = body.length;
  2838. data[p] = len >> 24 & 0xff;
  2839. data[p + 1] = len >> 16 & 0xff;
  2840. data[p + 2] = len >> 8 & 0xff;
  2841. data[p + 3] = len & 0xff;
  2842. p += 4;
  2843. data[p] = type.charCodeAt(0) & 0xff;
  2844. data[p + 1] = type.charCodeAt(1) & 0xff;
  2845. data[p + 2] = type.charCodeAt(2) & 0xff;
  2846. data[p + 3] = type.charCodeAt(3) & 0xff;
  2847. p += 4;
  2848. data.set(body, p);
  2849. p += body.length;
  2850. var crc = crc32(data, offset + 4, p);
  2851. data[p] = crc >> 24 & 0xff;
  2852. data[p + 1] = crc >> 16 & 0xff;
  2853. data[p + 2] = crc >> 8 & 0xff;
  2854. data[p + 3] = crc & 0xff;
  2855. }
  2856. function adler32(data, start, end) {
  2857. var a = 1;
  2858. var b = 0;
  2859. for (var i = start; i < end; ++i) {
  2860. a = (a + (data[i] & 0xff)) % 65521;
  2861. b = (b + a) % 65521;
  2862. }
  2863. return (b << 16) | a;
  2864. }
  2865. function encode(imgData, kind, forceDataSchema) {
  2866. var width = imgData.width;
  2867. var height = imgData.height;
  2868. var bitDepth, colorType, lineSize;
  2869. var bytes = imgData.data;
  2870. switch (kind) {
  2871. case ImageKind.GRAYSCALE_1BPP:
  2872. colorType = 0;
  2873. bitDepth = 1;
  2874. lineSize = (width + 7) >> 3;
  2875. break;
  2876. case ImageKind.RGB_24BPP:
  2877. colorType = 2;
  2878. bitDepth = 8;
  2879. lineSize = width * 3;
  2880. break;
  2881. case ImageKind.RGBA_32BPP:
  2882. colorType = 6;
  2883. bitDepth = 8;
  2884. lineSize = width * 4;
  2885. break;
  2886. default:
  2887. throw new Error('invalid format');
  2888. }
  2889. // prefix every row with predictor 0
  2890. var literals = new Uint8Array((1 + lineSize) * height);
  2891. var offsetLiterals = 0, offsetBytes = 0;
  2892. var y, i;
  2893. for (y = 0; y < height; ++y) {
  2894. literals[offsetLiterals++] = 0; // no prediction
  2895. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  2896. offsetLiterals);
  2897. offsetBytes += lineSize;
  2898. offsetLiterals += lineSize;
  2899. }
  2900. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2901. // inverting for B/W
  2902. offsetLiterals = 0;
  2903. for (y = 0; y < height; y++) {
  2904. offsetLiterals++; // skipping predictor
  2905. for (i = 0; i < lineSize; i++) {
  2906. literals[offsetLiterals++] ^= 0xFF;
  2907. }
  2908. }
  2909. }
  2910. var ihdr = new Uint8Array([
  2911. width >> 24 & 0xff,
  2912. width >> 16 & 0xff,
  2913. width >> 8 & 0xff,
  2914. width & 0xff,
  2915. height >> 24 & 0xff,
  2916. height >> 16 & 0xff,
  2917. height >> 8 & 0xff,
  2918. height & 0xff,
  2919. bitDepth, // bit depth
  2920. colorType, // color type
  2921. 0x00, // compression method
  2922. 0x00, // filter method
  2923. 0x00 // interlace method
  2924. ]);
  2925. var len = literals.length;
  2926. var maxBlockLength = 0xFFFF;
  2927. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2928. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2929. var pi = 0;
  2930. idat[pi++] = 0x78; // compression method and flags
  2931. idat[pi++] = 0x9c; // flags
  2932. var pos = 0;
  2933. while (len > maxBlockLength) {
  2934. // writing non-final DEFLATE blocks type 0 and length of 65535
  2935. idat[pi++] = 0x00;
  2936. idat[pi++] = 0xff;
  2937. idat[pi++] = 0xff;
  2938. idat[pi++] = 0x00;
  2939. idat[pi++] = 0x00;
  2940. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2941. pi += maxBlockLength;
  2942. pos += maxBlockLength;
  2943. len -= maxBlockLength;
  2944. }
  2945. // writing non-final DEFLATE blocks type 0
  2946. idat[pi++] = 0x01;
  2947. idat[pi++] = len & 0xff;
  2948. idat[pi++] = len >> 8 & 0xff;
  2949. idat[pi++] = (~len & 0xffff) & 0xff;
  2950. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  2951. idat.set(literals.subarray(pos), pi);
  2952. pi += literals.length - pos;
  2953. var adler = adler32(literals, 0, literals.length); // checksum
  2954. idat[pi++] = adler >> 24 & 0xff;
  2955. idat[pi++] = adler >> 16 & 0xff;
  2956. idat[pi++] = adler >> 8 & 0xff;
  2957. idat[pi++] = adler & 0xff;
  2958. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  2959. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  2960. ihdr.length + idat.length;
  2961. var data = new Uint8Array(pngLength);
  2962. var offset = 0;
  2963. data.set(PNG_HEADER, offset);
  2964. offset += PNG_HEADER.length;
  2965. writePngChunk('IHDR', ihdr, data, offset);
  2966. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  2967. writePngChunk('IDATA', idat, data, offset);
  2968. offset += CHUNK_WRAPPER_SIZE + idat.length;
  2969. writePngChunk('IEND', new Uint8Array(0), data, offset);
  2970. return createObjectURL(data, 'image/png', forceDataSchema);
  2971. }
  2972. return function convertImgDataToPng(imgData, forceDataSchema) {
  2973. var kind = (imgData.kind === undefined ?
  2974. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  2975. return encode(imgData, kind, forceDataSchema);
  2976. };
  2977. })();
  2978. var SVGExtraState = (function SVGExtraStateClosure() {
  2979. function SVGExtraState() {
  2980. this.fontSizeScale = 1;
  2981. this.fontWeight = SVG_DEFAULTS.fontWeight;
  2982. this.fontSize = 0;
  2983. this.textMatrix = IDENTITY_MATRIX;
  2984. this.fontMatrix = FONT_IDENTITY_MATRIX;
  2985. this.leading = 0;
  2986. // Current point (in user coordinates)
  2987. this.x = 0;
  2988. this.y = 0;
  2989. // Start of text line (in text coordinates)
  2990. this.lineX = 0;
  2991. this.lineY = 0;
  2992. // Character and word spacing
  2993. this.charSpacing = 0;
  2994. this.wordSpacing = 0;
  2995. this.textHScale = 1;
  2996. this.textRise = 0;
  2997. // Default foreground and background colors
  2998. this.fillColor = SVG_DEFAULTS.fillColor;
  2999. this.strokeColor = '#000000';
  3000. this.fillAlpha = 1;
  3001. this.strokeAlpha = 1;
  3002. this.lineWidth = 1;
  3003. this.lineJoin = '';
  3004. this.lineCap = '';
  3005. this.miterLimit = 0;
  3006. this.dashArray = [];
  3007. this.dashPhase = 0;
  3008. this.dependencies = [];
  3009. // Clipping
  3010. this.clipId = '';
  3011. this.pendingClip = false;
  3012. this.maskId = '';
  3013. }
  3014. SVGExtraState.prototype = {
  3015. clone: function SVGExtraState_clone() {
  3016. return Object.create(this);
  3017. },
  3018. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3019. this.x = x;
  3020. this.y = y;
  3021. }
  3022. };
  3023. return SVGExtraState;
  3024. })();
  3025. var SVGGraphics = (function SVGGraphicsClosure() {
  3026. function createScratchSVG(width, height) {
  3027. var NS = 'http://www.w3.org/2000/svg';
  3028. var svg = document.createElementNS(NS, 'svg:svg');
  3029. svg.setAttributeNS(null, 'version', '1.1');
  3030. svg.setAttributeNS(null, 'width', width + 'px');
  3031. svg.setAttributeNS(null, 'height', height + 'px');
  3032. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3033. return svg;
  3034. }
  3035. function opListToTree(opList) {
  3036. var opTree = [];
  3037. var tmp = [];
  3038. var opListLen = opList.length;
  3039. for (var x = 0; x < opListLen; x++) {
  3040. if (opList[x].fn === 'save') {
  3041. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3042. tmp.push(opTree);
  3043. opTree = opTree[opTree.length - 1].items;
  3044. continue;
  3045. }
  3046. if(opList[x].fn === 'restore') {
  3047. opTree = tmp.pop();
  3048. } else {
  3049. opTree.push(opList[x]);
  3050. }
  3051. }
  3052. return opTree;
  3053. }
  3054. /**
  3055. * Formats float number.
  3056. * @param value {number} number to format.
  3057. * @returns {string}
  3058. */
  3059. function pf(value) {
  3060. if (value === (value | 0)) { // integer number
  3061. return value.toString();
  3062. }
  3063. var s = value.toFixed(10);
  3064. var i = s.length - 1;
  3065. if (s[i] !== '0') {
  3066. return s;
  3067. }
  3068. // removing trailing zeros
  3069. do {
  3070. i--;
  3071. } while (s[i] === '0');
  3072. return s.substr(0, s[i] === '.' ? i : i + 1);
  3073. }
  3074. /**
  3075. * Formats transform matrix. The standard rotation, scale and translate
  3076. * matrices are replaced by their shorter forms, and for identity matrix
  3077. * returns empty string to save the memory.
  3078. * @param m {Array} matrix to format.
  3079. * @returns {string}
  3080. */
  3081. function pm(m) {
  3082. if (m[4] === 0 && m[5] === 0) {
  3083. if (m[1] === 0 && m[2] === 0) {
  3084. if (m[0] === 1 && m[3] === 1) {
  3085. return '';
  3086. }
  3087. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3088. }
  3089. if (m[0] === m[3] && m[1] === -m[2]) {
  3090. var a = Math.acos(m[0]) * 180 / Math.PI;
  3091. return 'rotate(' + pf(a) + ')';
  3092. }
  3093. } else {
  3094. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3095. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3096. }
  3097. }
  3098. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3099. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3100. }
  3101. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3102. this.current = new SVGExtraState();
  3103. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3104. this.transformStack = [];
  3105. this.extraStack = [];
  3106. this.commonObjs = commonObjs;
  3107. this.objs = objs;
  3108. this.pendingEOFill = false;
  3109. this.embedFonts = false;
  3110. this.embeddedFonts = Object.create(null);
  3111. this.cssStyle = null;
  3112. this.forceDataSchema = !!forceDataSchema;
  3113. }
  3114. var NS = 'http://www.w3.org/2000/svg';
  3115. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3116. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3117. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3118. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3119. var clipCount = 0;
  3120. var maskCount = 0;
  3121. SVGGraphics.prototype = {
  3122. save: function SVGGraphics_save() {
  3123. this.transformStack.push(this.transformMatrix);
  3124. var old = this.current;
  3125. this.extraStack.push(old);
  3126. this.current = old.clone();
  3127. },
  3128. restore: function SVGGraphics_restore() {
  3129. this.transformMatrix = this.transformStack.pop();
  3130. this.current = this.extraStack.pop();
  3131. this.tgrp = document.createElementNS(NS, 'svg:g');
  3132. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3133. this.pgrp.appendChild(this.tgrp);
  3134. },
  3135. group: function SVGGraphics_group(items) {
  3136. this.save();
  3137. this.executeOpTree(items);
  3138. this.restore();
  3139. },
  3140. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3141. var fnArray = operatorList.fnArray;
  3142. var fnArrayLen = fnArray.length;
  3143. var argsArray = operatorList.argsArray;
  3144. var self = this;
  3145. for (var i = 0; i < fnArrayLen; i++) {
  3146. if (OPS.dependency === fnArray[i]) {
  3147. var deps = argsArray[i];
  3148. for (var n = 0, nn = deps.length; n < nn; n++) {
  3149. var obj = deps[n];
  3150. var common = obj.substring(0, 2) === 'g_';
  3151. var promise;
  3152. if (common) {
  3153. promise = new Promise(function(resolve) {
  3154. self.commonObjs.get(obj, resolve);
  3155. });
  3156. } else {
  3157. promise = new Promise(function(resolve) {
  3158. self.objs.get(obj, resolve);
  3159. });
  3160. }
  3161. this.current.dependencies.push(promise);
  3162. }
  3163. }
  3164. }
  3165. return Promise.all(this.current.dependencies);
  3166. },
  3167. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3168. var transformMatrix = [a, b, c, d, e, f];
  3169. this.transformMatrix = Util.transform(this.transformMatrix,
  3170. transformMatrix);
  3171. this.tgrp = document.createElementNS(NS, 'svg:g');
  3172. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3173. },
  3174. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3175. this.svg = createScratchSVG(viewport.width, viewport.height);
  3176. this.viewport = viewport;
  3177. return this.loadDependencies(operatorList).then(function () {
  3178. this.transformMatrix = IDENTITY_MATRIX;
  3179. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3180. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3181. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3182. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3183. this.defs = document.createElementNS(NS, 'svg:defs');
  3184. this.pgrp.appendChild(this.defs);
  3185. this.pgrp.appendChild(this.tgrp);
  3186. this.svg.appendChild(this.pgrp);
  3187. var opTree = this.convertOpList(operatorList);
  3188. this.executeOpTree(opTree);
  3189. return this.svg;
  3190. }.bind(this));
  3191. },
  3192. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3193. var argsArray = operatorList.argsArray;
  3194. var fnArray = operatorList.fnArray;
  3195. var fnArrayLen = fnArray.length;
  3196. var REVOPS = [];
  3197. var opList = [];
  3198. for (var op in OPS) {
  3199. REVOPS[OPS[op]] = op;
  3200. }
  3201. for (var x = 0; x < fnArrayLen; x++) {
  3202. var fnId = fnArray[x];
  3203. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3204. }
  3205. return opListToTree(opList);
  3206. },
  3207. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3208. var opTreeLen = opTree.length;
  3209. for(var x = 0; x < opTreeLen; x++) {
  3210. var fn = opTree[x].fn;
  3211. var fnId = opTree[x].fnId;
  3212. var args = opTree[x].args;
  3213. switch (fnId | 0) {
  3214. case OPS.beginText:
  3215. this.beginText();
  3216. break;
  3217. case OPS.setLeading:
  3218. this.setLeading(args);
  3219. break;
  3220. case OPS.setLeadingMoveText:
  3221. this.setLeadingMoveText(args[0], args[1]);
  3222. break;
  3223. case OPS.setFont:
  3224. this.setFont(args);
  3225. break;
  3226. case OPS.showText:
  3227. this.showText(args[0]);
  3228. break;
  3229. case OPS.showSpacedText:
  3230. this.showText(args[0]);
  3231. break;
  3232. case OPS.endText:
  3233. this.endText();
  3234. break;
  3235. case OPS.moveText:
  3236. this.moveText(args[0], args[1]);
  3237. break;
  3238. case OPS.setCharSpacing:
  3239. this.setCharSpacing(args[0]);
  3240. break;
  3241. case OPS.setWordSpacing:
  3242. this.setWordSpacing(args[0]);
  3243. break;
  3244. case OPS.setHScale:
  3245. this.setHScale(args[0]);
  3246. break;
  3247. case OPS.setTextMatrix:
  3248. this.setTextMatrix(args[0], args[1], args[2],
  3249. args[3], args[4], args[5]);
  3250. break;
  3251. case OPS.setLineWidth:
  3252. this.setLineWidth(args[0]);
  3253. break;
  3254. case OPS.setLineJoin:
  3255. this.setLineJoin(args[0]);
  3256. break;
  3257. case OPS.setLineCap:
  3258. this.setLineCap(args[0]);
  3259. break;
  3260. case OPS.setMiterLimit:
  3261. this.setMiterLimit(args[0]);
  3262. break;
  3263. case OPS.setFillRGBColor:
  3264. this.setFillRGBColor(args[0], args[1], args[2]);
  3265. break;
  3266. case OPS.setStrokeRGBColor:
  3267. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3268. break;
  3269. case OPS.setDash:
  3270. this.setDash(args[0], args[1]);
  3271. break;
  3272. case OPS.setGState:
  3273. this.setGState(args[0]);
  3274. break;
  3275. case OPS.fill:
  3276. this.fill();
  3277. break;
  3278. case OPS.eoFill:
  3279. this.eoFill();
  3280. break;
  3281. case OPS.stroke:
  3282. this.stroke();
  3283. break;
  3284. case OPS.fillStroke:
  3285. this.fillStroke();
  3286. break;
  3287. case OPS.eoFillStroke:
  3288. this.eoFillStroke();
  3289. break;
  3290. case OPS.clip:
  3291. this.clip('nonzero');
  3292. break;
  3293. case OPS.eoClip:
  3294. this.clip('evenodd');
  3295. break;
  3296. case OPS.paintSolidColorImageMask:
  3297. this.paintSolidColorImageMask();
  3298. break;
  3299. case OPS.paintJpegXObject:
  3300. this.paintJpegXObject(args[0], args[1], args[2]);
  3301. break;
  3302. case OPS.paintImageXObject:
  3303. this.paintImageXObject(args[0]);
  3304. break;
  3305. case OPS.paintInlineImageXObject:
  3306. this.paintInlineImageXObject(args[0]);
  3307. break;
  3308. case OPS.paintImageMaskXObject:
  3309. this.paintImageMaskXObject(args[0]);
  3310. break;
  3311. case OPS.paintFormXObjectBegin:
  3312. this.paintFormXObjectBegin(args[0], args[1]);
  3313. break;
  3314. case OPS.paintFormXObjectEnd:
  3315. this.paintFormXObjectEnd();
  3316. break;
  3317. case OPS.closePath:
  3318. this.closePath();
  3319. break;
  3320. case OPS.closeStroke:
  3321. this.closeStroke();
  3322. break;
  3323. case OPS.closeFillStroke:
  3324. this.closeFillStroke();
  3325. break;
  3326. case OPS.nextLine:
  3327. this.nextLine();
  3328. break;
  3329. case OPS.transform:
  3330. this.transform(args[0], args[1], args[2], args[3],
  3331. args[4], args[5]);
  3332. break;
  3333. case OPS.constructPath:
  3334. this.constructPath(args[0], args[1]);
  3335. break;
  3336. case OPS.endPath:
  3337. this.endPath();
  3338. break;
  3339. case 92:
  3340. this.group(opTree[x].items);
  3341. break;
  3342. default:
  3343. warn('Unimplemented method '+ fn);
  3344. break;
  3345. }
  3346. }
  3347. },
  3348. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3349. this.current.wordSpacing = wordSpacing;
  3350. },
  3351. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3352. this.current.charSpacing = charSpacing;
  3353. },
  3354. nextLine: function SVGGraphics_nextLine() {
  3355. this.moveText(0, this.current.leading);
  3356. },
  3357. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3358. var current = this.current;
  3359. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3360. this.current.x = this.current.lineX = 0;
  3361. this.current.y = this.current.lineY = 0;
  3362. current.xcoords = [];
  3363. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3364. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3365. current.tspan.setAttributeNS(null, 'font-size',
  3366. pf(current.fontSize) + 'px');
  3367. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3368. current.txtElement = document.createElementNS(NS, 'svg:text');
  3369. current.txtElement.appendChild(current.tspan);
  3370. },
  3371. beginText: function SVGGraphics_beginText() {
  3372. this.current.x = this.current.lineX = 0;
  3373. this.current.y = this.current.lineY = 0;
  3374. this.current.textMatrix = IDENTITY_MATRIX;
  3375. this.current.lineMatrix = IDENTITY_MATRIX;
  3376. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3377. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3378. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3379. this.current.xcoords = [];
  3380. },
  3381. moveText: function SVGGraphics_moveText(x, y) {
  3382. var current = this.current;
  3383. this.current.x = this.current.lineX += x;
  3384. this.current.y = this.current.lineY += y;
  3385. current.xcoords = [];
  3386. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3387. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3388. current.tspan.setAttributeNS(null, 'font-size',
  3389. pf(current.fontSize) + 'px');
  3390. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3391. },
  3392. showText: function SVGGraphics_showText(glyphs) {
  3393. var current = this.current;
  3394. var font = current.font;
  3395. var fontSize = current.fontSize;
  3396. if (fontSize === 0) {
  3397. return;
  3398. }
  3399. var charSpacing = current.charSpacing;
  3400. var wordSpacing = current.wordSpacing;
  3401. var fontDirection = current.fontDirection;
  3402. var textHScale = current.textHScale * fontDirection;
  3403. var glyphsLength = glyphs.length;
  3404. var vertical = font.vertical;
  3405. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3406. var x = 0, i;
  3407. for (i = 0; i < glyphsLength; ++i) {
  3408. var glyph = glyphs[i];
  3409. if (glyph === null) {
  3410. // word break
  3411. x += fontDirection * wordSpacing;
  3412. continue;
  3413. } else if (isNum(glyph)) {
  3414. x += -glyph * fontSize * 0.001;
  3415. continue;
  3416. }
  3417. current.xcoords.push(current.x + x * textHScale);
  3418. var width = glyph.width;
  3419. var character = glyph.fontChar;
  3420. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3421. x += charWidth;
  3422. current.tspan.textContent += character;
  3423. }
  3424. if (vertical) {
  3425. current.y -= x * textHScale;
  3426. } else {
  3427. current.x += x * textHScale;
  3428. }
  3429. current.tspan.setAttributeNS(null, 'x',
  3430. current.xcoords.map(pf).join(' '));
  3431. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3432. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3433. current.tspan.setAttributeNS(null, 'font-size',
  3434. pf(current.fontSize) + 'px');
  3435. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3436. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3437. }
  3438. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3439. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3440. }
  3441. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3442. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3443. }
  3444. current.txtElement.setAttributeNS(null, 'transform',
  3445. pm(current.textMatrix) +
  3446. ' scale(1, -1)' );
  3447. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3448. current.txtElement.appendChild(current.tspan);
  3449. current.txtgrp.appendChild(current.txtElement);
  3450. this.tgrp.appendChild(current.txtElement);
  3451. },
  3452. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3453. this.setLeading(-y);
  3454. this.moveText(x, y);
  3455. },
  3456. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3457. if (!this.cssStyle) {
  3458. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3459. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3460. this.defs.appendChild(this.cssStyle);
  3461. }
  3462. var url = createObjectURL(fontObj.data, fontObj.mimetype,
  3463. this.forceDataSchema);
  3464. this.cssStyle.textContent +=
  3465. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3466. ' src: url(' + url + '); }\n';
  3467. },
  3468. setFont: function SVGGraphics_setFont(details) {
  3469. var current = this.current;
  3470. var fontObj = this.commonObjs.get(details[0]);
  3471. var size = details[1];
  3472. this.current.font = fontObj;
  3473. if (this.embedFonts && fontObj.data &&
  3474. !this.embeddedFonts[fontObj.loadedName]) {
  3475. this.addFontStyle(fontObj);
  3476. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3477. }
  3478. current.fontMatrix = (fontObj.fontMatrix ?
  3479. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3480. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3481. (fontObj.bold ? 'bold' : 'normal');
  3482. var italic = fontObj.italic ? 'italic' : 'normal';
  3483. if (size < 0) {
  3484. size = -size;
  3485. current.fontDirection = -1;
  3486. } else {
  3487. current.fontDirection = 1;
  3488. }
  3489. current.fontSize = size;
  3490. current.fontFamily = fontObj.loadedName;
  3491. current.fontWeight = bold;
  3492. current.fontStyle = italic;
  3493. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3494. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3495. current.xcoords = [];
  3496. },
  3497. endText: function SVGGraphics_endText() {
  3498. if (this.current.pendingClip) {
  3499. this.cgrp.appendChild(this.tgrp);
  3500. this.pgrp.appendChild(this.cgrp);
  3501. } else {
  3502. this.pgrp.appendChild(this.tgrp);
  3503. }
  3504. this.tgrp = document.createElementNS(NS, 'svg:g');
  3505. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3506. },
  3507. // Path properties
  3508. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3509. this.current.lineWidth = width;
  3510. },
  3511. setLineCap: function SVGGraphics_setLineCap(style) {
  3512. this.current.lineCap = LINE_CAP_STYLES[style];
  3513. },
  3514. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3515. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3516. },
  3517. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3518. this.current.miterLimit = limit;
  3519. },
  3520. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3521. var color = Util.makeCssRgb(r, g, b);
  3522. this.current.strokeColor = color;
  3523. },
  3524. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3525. var color = Util.makeCssRgb(r, g, b);
  3526. this.current.fillColor = color;
  3527. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3528. this.current.xcoords = [];
  3529. },
  3530. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3531. this.current.dashArray = dashArray;
  3532. this.current.dashPhase = dashPhase;
  3533. },
  3534. constructPath: function SVGGraphics_constructPath(ops, args) {
  3535. var current = this.current;
  3536. var x = current.x, y = current.y;
  3537. current.path = document.createElementNS(NS, 'svg:path');
  3538. var d = [];
  3539. var opLength = ops.length;
  3540. for (var i = 0, j = 0; i < opLength; i++) {
  3541. switch (ops[i] | 0) {
  3542. case OPS.rectangle:
  3543. x = args[j++];
  3544. y = args[j++];
  3545. var width = args[j++];
  3546. var height = args[j++];
  3547. var xw = x + width;
  3548. var yh = y + height;
  3549. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  3550. 'L', pf(x), pf(yh), 'Z');
  3551. break;
  3552. case OPS.moveTo:
  3553. x = args[j++];
  3554. y = args[j++];
  3555. d.push('M', pf(x), pf(y));
  3556. break;
  3557. case OPS.lineTo:
  3558. x = args[j++];
  3559. y = args[j++];
  3560. d.push('L', pf(x) , pf(y));
  3561. break;
  3562. case OPS.curveTo:
  3563. x = args[j + 4];
  3564. y = args[j + 5];
  3565. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  3566. pf(args[j + 3]), pf(x), pf(y));
  3567. j += 6;
  3568. break;
  3569. case OPS.curveTo2:
  3570. x = args[j + 2];
  3571. y = args[j + 3];
  3572. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  3573. pf(args[j + 2]), pf(args[j + 3]));
  3574. j += 4;
  3575. break;
  3576. case OPS.curveTo3:
  3577. x = args[j + 2];
  3578. y = args[j + 3];
  3579. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  3580. pf(x), pf(y));
  3581. j += 4;
  3582. break;
  3583. case OPS.closePath:
  3584. d.push('Z');
  3585. break;
  3586. }
  3587. }
  3588. current.path.setAttributeNS(null, 'd', d.join(' '));
  3589. current.path.setAttributeNS(null, 'stroke-miterlimit',
  3590. pf(current.miterLimit));
  3591. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3592. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3593. current.path.setAttributeNS(null, 'stroke-width',
  3594. pf(current.lineWidth) + 'px');
  3595. current.path.setAttributeNS(null, 'stroke-dasharray',
  3596. current.dashArray.map(pf).join(' '));
  3597. current.path.setAttributeNS(null, 'stroke-dashoffset',
  3598. pf(current.dashPhase) + 'px');
  3599. current.path.setAttributeNS(null, 'fill', 'none');
  3600. this.tgrp.appendChild(current.path);
  3601. if (current.pendingClip) {
  3602. this.cgrp.appendChild(this.tgrp);
  3603. this.pgrp.appendChild(this.cgrp);
  3604. } else {
  3605. this.pgrp.appendChild(this.tgrp);
  3606. }
  3607. // Saving a reference in current.element so that it can be addressed
  3608. // in 'fill' and 'stroke'
  3609. current.element = current.path;
  3610. current.setCurrentPoint(x, y);
  3611. },
  3612. endPath: function SVGGraphics_endPath() {
  3613. var current = this.current;
  3614. if (current.pendingClip) {
  3615. this.cgrp.appendChild(this.tgrp);
  3616. this.pgrp.appendChild(this.cgrp);
  3617. } else {
  3618. this.pgrp.appendChild(this.tgrp);
  3619. }
  3620. this.tgrp = document.createElementNS(NS, 'svg:g');
  3621. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3622. },
  3623. clip: function SVGGraphics_clip(type) {
  3624. var current = this.current;
  3625. // Add current path to clipping path
  3626. current.clipId = 'clippath' + clipCount;
  3627. clipCount++;
  3628. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3629. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3630. var clipElement = current.element.cloneNode();
  3631. if (type === 'evenodd') {
  3632. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3633. } else {
  3634. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3635. }
  3636. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3637. this.clippath.appendChild(clipElement);
  3638. this.defs.appendChild(this.clippath);
  3639. // Create a new group with that attribute
  3640. current.pendingClip = true;
  3641. this.cgrp = document.createElementNS(NS, 'svg:g');
  3642. this.cgrp.setAttributeNS(null, 'clip-path',
  3643. 'url(#' + current.clipId + ')');
  3644. this.pgrp.appendChild(this.cgrp);
  3645. },
  3646. closePath: function SVGGraphics_closePath() {
  3647. var current = this.current;
  3648. var d = current.path.getAttributeNS(null, 'd');
  3649. d += 'Z';
  3650. current.path.setAttributeNS(null, 'd', d);
  3651. },
  3652. setLeading: function SVGGraphics_setLeading(leading) {
  3653. this.current.leading = -leading;
  3654. },
  3655. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3656. this.current.textRise = textRise;
  3657. },
  3658. setHScale: function SVGGraphics_setHScale(scale) {
  3659. this.current.textHScale = scale / 100;
  3660. },
  3661. setGState: function SVGGraphics_setGState(states) {
  3662. for (var i = 0, ii = states.length; i < ii; i++) {
  3663. var state = states[i];
  3664. var key = state[0];
  3665. var value = state[1];
  3666. switch (key) {
  3667. case 'LW':
  3668. this.setLineWidth(value);
  3669. break;
  3670. case 'LC':
  3671. this.setLineCap(value);
  3672. break;
  3673. case 'LJ':
  3674. this.setLineJoin(value);
  3675. break;
  3676. case 'ML':
  3677. this.setMiterLimit(value);
  3678. break;
  3679. case 'D':
  3680. this.setDash(value[0], value[1]);
  3681. break;
  3682. case 'RI':
  3683. break;
  3684. case 'FL':
  3685. break;
  3686. case 'Font':
  3687. this.setFont(value);
  3688. break;
  3689. case 'CA':
  3690. break;
  3691. case 'ca':
  3692. break;
  3693. case 'BM':
  3694. break;
  3695. case 'SMask':
  3696. break;
  3697. }
  3698. }
  3699. },
  3700. fill: function SVGGraphics_fill() {
  3701. var current = this.current;
  3702. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3703. },
  3704. stroke: function SVGGraphics_stroke() {
  3705. var current = this.current;
  3706. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3707. current.element.setAttributeNS(null, 'fill', 'none');
  3708. },
  3709. eoFill: function SVGGraphics_eoFill() {
  3710. var current = this.current;
  3711. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3712. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3713. },
  3714. fillStroke: function SVGGraphics_fillStroke() {
  3715. // Order is important since stroke wants fill to be none.
  3716. // First stroke, then if fill needed, it will be overwritten.
  3717. this.stroke();
  3718. this.fill();
  3719. },
  3720. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3721. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3722. this.fillStroke();
  3723. },
  3724. closeStroke: function SVGGraphics_closeStroke() {
  3725. this.closePath();
  3726. this.stroke();
  3727. },
  3728. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3729. this.closePath();
  3730. this.fillStroke();
  3731. },
  3732. paintSolidColorImageMask:
  3733. function SVGGraphics_paintSolidColorImageMask() {
  3734. var current = this.current;
  3735. var rect = document.createElementNS(NS, 'svg:rect');
  3736. rect.setAttributeNS(null, 'x', '0');
  3737. rect.setAttributeNS(null, 'y', '0');
  3738. rect.setAttributeNS(null, 'width', '1px');
  3739. rect.setAttributeNS(null, 'height', '1px');
  3740. rect.setAttributeNS(null, 'fill', current.fillColor);
  3741. this.tgrp.appendChild(rect);
  3742. },
  3743. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3744. var current = this.current;
  3745. var imgObj = this.objs.get(objId);
  3746. var imgEl = document.createElementNS(NS, 'svg:image');
  3747. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3748. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3749. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3750. imgEl.setAttributeNS(null, 'x', '0');
  3751. imgEl.setAttributeNS(null, 'y', pf(-h));
  3752. imgEl.setAttributeNS(null, 'transform',
  3753. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3754. this.tgrp.appendChild(imgEl);
  3755. if (current.pendingClip) {
  3756. this.cgrp.appendChild(this.tgrp);
  3757. this.pgrp.appendChild(this.cgrp);
  3758. } else {
  3759. this.pgrp.appendChild(this.tgrp);
  3760. }
  3761. },
  3762. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3763. var imgData = this.objs.get(objId);
  3764. if (!imgData) {
  3765. warn('Dependent image isn\'t ready yet');
  3766. return;
  3767. }
  3768. this.paintInlineImageXObject(imgData);
  3769. },
  3770. paintInlineImageXObject:
  3771. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3772. var current = this.current;
  3773. var width = imgData.width;
  3774. var height = imgData.height;
  3775. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3776. var cliprect = document.createElementNS(NS, 'svg:rect');
  3777. cliprect.setAttributeNS(null, 'x', '0');
  3778. cliprect.setAttributeNS(null, 'y', '0');
  3779. cliprect.setAttributeNS(null, 'width', pf(width));
  3780. cliprect.setAttributeNS(null, 'height', pf(height));
  3781. current.element = cliprect;
  3782. this.clip('nonzero');
  3783. var imgEl = document.createElementNS(NS, 'svg:image');
  3784. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3785. imgEl.setAttributeNS(null, 'x', '0');
  3786. imgEl.setAttributeNS(null, 'y', pf(-height));
  3787. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3788. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3789. imgEl.setAttributeNS(null, 'transform',
  3790. 'scale(' + pf(1 / width) + ' ' +
  3791. pf(-1 / height) + ')');
  3792. if (mask) {
  3793. mask.appendChild(imgEl);
  3794. } else {
  3795. this.tgrp.appendChild(imgEl);
  3796. }
  3797. if (current.pendingClip) {
  3798. this.cgrp.appendChild(this.tgrp);
  3799. this.pgrp.appendChild(this.cgrp);
  3800. } else {
  3801. this.pgrp.appendChild(this.tgrp);
  3802. }
  3803. },
  3804. paintImageMaskXObject:
  3805. function SVGGraphics_paintImageMaskXObject(imgData) {
  3806. var current = this.current;
  3807. var width = imgData.width;
  3808. var height = imgData.height;
  3809. var fillColor = current.fillColor;
  3810. current.maskId = 'mask' + maskCount++;
  3811. var mask = document.createElementNS(NS, 'svg:mask');
  3812. mask.setAttributeNS(null, 'id', current.maskId);
  3813. var rect = document.createElementNS(NS, 'svg:rect');
  3814. rect.setAttributeNS(null, 'x', '0');
  3815. rect.setAttributeNS(null, 'y', '0');
  3816. rect.setAttributeNS(null, 'width', pf(width));
  3817. rect.setAttributeNS(null, 'height', pf(height));
  3818. rect.setAttributeNS(null, 'fill', fillColor);
  3819. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  3820. this.defs.appendChild(mask);
  3821. this.tgrp.appendChild(rect);
  3822. this.paintInlineImageXObject(imgData, mask);
  3823. },
  3824. paintFormXObjectBegin:
  3825. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3826. this.save();
  3827. if (isArray(matrix) && matrix.length === 6) {
  3828. this.transform(matrix[0], matrix[1], matrix[2],
  3829. matrix[3], matrix[4], matrix[5]);
  3830. }
  3831. if (isArray(bbox) && bbox.length === 4) {
  3832. var width = bbox[2] - bbox[0];
  3833. var height = bbox[3] - bbox[1];
  3834. var cliprect = document.createElementNS(NS, 'svg:rect');
  3835. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3836. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3837. cliprect.setAttributeNS(null, 'width', pf(width));
  3838. cliprect.setAttributeNS(null, 'height', pf(height));
  3839. this.current.element = cliprect;
  3840. this.clip('nonzero');
  3841. this.endPath();
  3842. }
  3843. },
  3844. paintFormXObjectEnd:
  3845. function SVGGraphics_paintFormXObjectEnd() {
  3846. this.restore();
  3847. }
  3848. };
  3849. return SVGGraphics;
  3850. })();
  3851. exports.SVGGraphics = SVGGraphics;
  3852. }));
  3853. (function (root, factory) {
  3854. {
  3855. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  3856. root.pdfjsDisplayDOMUtils);
  3857. }
  3858. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3859. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3860. var AnnotationType = sharedUtil.AnnotationType;
  3861. var isInt = sharedUtil.isInt;
  3862. var Util = sharedUtil.Util;
  3863. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3864. var LinkTarget = displayDOMUtils.LinkTarget;
  3865. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3866. var warn = sharedUtil.warn;
  3867. var CustomStyle = displayDOMUtils.CustomStyle;
  3868. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3869. /**
  3870. * @typedef {Object} AnnotationElementParameters
  3871. * @property {Object} data
  3872. * @property {HTMLDivElement} layer
  3873. * @property {PDFPage} page
  3874. * @property {PageViewport} viewport
  3875. * @property {IPDFLinkService} linkService
  3876. * @property {DownloadManager} downloadManager
  3877. * @property {string} imageResourcesPath
  3878. * @property {boolean} renderInteractiveForms
  3879. */
  3880. /**
  3881. * @class
  3882. * @alias AnnotationElementFactory
  3883. */
  3884. function AnnotationElementFactory() {}
  3885. AnnotationElementFactory.prototype =
  3886. /** @lends AnnotationElementFactory.prototype */ {
  3887. /**
  3888. * @param {AnnotationElementParameters} parameters
  3889. * @returns {AnnotationElement}
  3890. */
  3891. create: function AnnotationElementFactory_create(parameters) {
  3892. var subtype = parameters.data.annotationType;
  3893. switch (subtype) {
  3894. case AnnotationType.LINK:
  3895. return new LinkAnnotationElement(parameters);
  3896. case AnnotationType.TEXT:
  3897. return new TextAnnotationElement(parameters);
  3898. case AnnotationType.WIDGET:
  3899. var fieldType = parameters.data.fieldType;
  3900. switch (fieldType) {
  3901. case 'Tx':
  3902. return new TextWidgetAnnotationElement(parameters);
  3903. }
  3904. return new WidgetAnnotationElement(parameters);
  3905. case AnnotationType.POPUP:
  3906. return new PopupAnnotationElement(parameters);
  3907. case AnnotationType.HIGHLIGHT:
  3908. return new HighlightAnnotationElement(parameters);
  3909. case AnnotationType.UNDERLINE:
  3910. return new UnderlineAnnotationElement(parameters);
  3911. case AnnotationType.SQUIGGLY:
  3912. return new SquigglyAnnotationElement(parameters);
  3913. case AnnotationType.STRIKEOUT:
  3914. return new StrikeOutAnnotationElement(parameters);
  3915. case AnnotationType.FILEATTACHMENT:
  3916. return new FileAttachmentAnnotationElement(parameters);
  3917. default:
  3918. return new AnnotationElement(parameters);
  3919. }
  3920. }
  3921. };
  3922. /**
  3923. * @class
  3924. * @alias AnnotationElement
  3925. */
  3926. var AnnotationElement = (function AnnotationElementClosure() {
  3927. function AnnotationElement(parameters, isRenderable) {
  3928. this.isRenderable = isRenderable || false;
  3929. this.data = parameters.data;
  3930. this.layer = parameters.layer;
  3931. this.page = parameters.page;
  3932. this.viewport = parameters.viewport;
  3933. this.linkService = parameters.linkService;
  3934. this.downloadManager = parameters.downloadManager;
  3935. this.imageResourcesPath = parameters.imageResourcesPath;
  3936. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3937. if (isRenderable) {
  3938. this.container = this._createContainer();
  3939. }
  3940. }
  3941. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3942. /**
  3943. * Create an empty container for the annotation's HTML element.
  3944. *
  3945. * @private
  3946. * @memberof AnnotationElement
  3947. * @returns {HTMLSectionElement}
  3948. */
  3949. _createContainer: function AnnotationElement_createContainer() {
  3950. var data = this.data, page = this.page, viewport = this.viewport;
  3951. var container = document.createElement('section');
  3952. var width = data.rect[2] - data.rect[0];
  3953. var height = data.rect[3] - data.rect[1];
  3954. container.setAttribute('data-annotation-id', data.id);
  3955. // Do *not* modify `data.rect`, since that will corrupt the annotation
  3956. // position on subsequent calls to `_createContainer` (see issue 6804).
  3957. var rect = Util.normalizeRect([
  3958. data.rect[0],
  3959. page.view[3] - data.rect[1] + page.view[1],
  3960. data.rect[2],
  3961. page.view[3] - data.rect[3] + page.view[1]
  3962. ]);
  3963. CustomStyle.setProp('transform', container,
  3964. 'matrix(' + viewport.transform.join(',') + ')');
  3965. CustomStyle.setProp('transformOrigin', container,
  3966. -rect[0] + 'px ' + -rect[1] + 'px');
  3967. if (data.borderStyle.width > 0) {
  3968. container.style.borderWidth = data.borderStyle.width + 'px';
  3969. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  3970. // Underline styles only have a bottom border, so we do not need
  3971. // to adjust for all borders. This yields a similar result as
  3972. // Adobe Acrobat/Reader.
  3973. width = width - 2 * data.borderStyle.width;
  3974. height = height - 2 * data.borderStyle.width;
  3975. }
  3976. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  3977. var verticalRadius = data.borderStyle.verticalCornerRadius;
  3978. if (horizontalRadius > 0 || verticalRadius > 0) {
  3979. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  3980. CustomStyle.setProp('borderRadius', container, radius);
  3981. }
  3982. switch (data.borderStyle.style) {
  3983. case AnnotationBorderStyleType.SOLID:
  3984. container.style.borderStyle = 'solid';
  3985. break;
  3986. case AnnotationBorderStyleType.DASHED:
  3987. container.style.borderStyle = 'dashed';
  3988. break;
  3989. case AnnotationBorderStyleType.BEVELED:
  3990. warn('Unimplemented border style: beveled');
  3991. break;
  3992. case AnnotationBorderStyleType.INSET:
  3993. warn('Unimplemented border style: inset');
  3994. break;
  3995. case AnnotationBorderStyleType.UNDERLINE:
  3996. container.style.borderBottomStyle = 'solid';
  3997. break;
  3998. default:
  3999. break;
  4000. }
  4001. if (data.color) {
  4002. container.style.borderColor =
  4003. Util.makeCssRgb(data.color[0] | 0,
  4004. data.color[1] | 0,
  4005. data.color[2] | 0);
  4006. } else {
  4007. // Transparent (invisible) border, so do not draw it at all.
  4008. container.style.borderWidth = 0;
  4009. }
  4010. }
  4011. container.style.left = rect[0] + 'px';
  4012. container.style.top = rect[1] + 'px';
  4013. container.style.width = width + 'px';
  4014. container.style.height = height + 'px';
  4015. return container;
  4016. },
  4017. /**
  4018. * Create a popup for the annotation's HTML element. This is used for
  4019. * annotations that do not have a Popup entry in the dictionary, but
  4020. * are of a type that works with popups (such as Highlight annotations).
  4021. *
  4022. * @private
  4023. * @param {HTMLSectionElement} container
  4024. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4025. * @param {Object} data
  4026. * @memberof AnnotationElement
  4027. */
  4028. _createPopup:
  4029. function AnnotationElement_createPopup(container, trigger, data) {
  4030. // If no trigger element is specified, create it.
  4031. if (!trigger) {
  4032. trigger = document.createElement('div');
  4033. trigger.style.height = container.style.height;
  4034. trigger.style.width = container.style.width;
  4035. container.appendChild(trigger);
  4036. }
  4037. var popupElement = new PopupElement({
  4038. container: container,
  4039. trigger: trigger,
  4040. color: data.color,
  4041. title: data.title,
  4042. contents: data.contents,
  4043. hideWrapper: true
  4044. });
  4045. var popup = popupElement.render();
  4046. // Position the popup next to the annotation's container.
  4047. popup.style.left = container.style.width;
  4048. container.appendChild(popup);
  4049. },
  4050. /**
  4051. * Render the annotation's HTML element in the empty container.
  4052. *
  4053. * @public
  4054. * @memberof AnnotationElement
  4055. */
  4056. render: function AnnotationElement_render() {
  4057. throw new Error('Abstract method AnnotationElement.render called');
  4058. }
  4059. };
  4060. return AnnotationElement;
  4061. })();
  4062. /**
  4063. * @class
  4064. * @alias LinkAnnotationElement
  4065. */
  4066. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4067. function LinkAnnotationElement(parameters) {
  4068. AnnotationElement.call(this, parameters, true);
  4069. }
  4070. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4071. /**
  4072. * Render the link annotation's HTML element in the empty container.
  4073. *
  4074. * @public
  4075. * @memberof LinkAnnotationElement
  4076. * @returns {HTMLSectionElement}
  4077. */
  4078. render: function LinkAnnotationElement_render() {
  4079. this.container.className = 'linkAnnotation';
  4080. var link = document.createElement('a');
  4081. addLinkAttributes(link, {
  4082. url: this.data.url,
  4083. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4084. });
  4085. if (!this.data.url) {
  4086. if (this.data.action) {
  4087. this._bindNamedAction(link, this.data.action);
  4088. } else {
  4089. this._bindLink(link, (this.data.dest || null));
  4090. }
  4091. }
  4092. this.container.appendChild(link);
  4093. return this.container;
  4094. },
  4095. /**
  4096. * Bind internal links to the link element.
  4097. *
  4098. * @private
  4099. * @param {Object} link
  4100. * @param {Object} destination
  4101. * @memberof LinkAnnotationElement
  4102. */
  4103. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4104. var self = this;
  4105. link.href = this.linkService.getDestinationHash(destination);
  4106. link.onclick = function() {
  4107. if (destination) {
  4108. self.linkService.navigateTo(destination);
  4109. }
  4110. return false;
  4111. };
  4112. if (destination) {
  4113. link.className = 'internalLink';
  4114. }
  4115. },
  4116. /**
  4117. * Bind named actions to the link element.
  4118. *
  4119. * @private
  4120. * @param {Object} link
  4121. * @param {Object} action
  4122. * @memberof LinkAnnotationElement
  4123. */
  4124. _bindNamedAction:
  4125. function LinkAnnotationElement_bindNamedAction(link, action) {
  4126. var self = this;
  4127. link.href = this.linkService.getAnchorUrl('');
  4128. link.onclick = function() {
  4129. self.linkService.executeNamedAction(action);
  4130. return false;
  4131. };
  4132. link.className = 'internalLink';
  4133. }
  4134. });
  4135. return LinkAnnotationElement;
  4136. })();
  4137. /**
  4138. * @class
  4139. * @alias TextAnnotationElement
  4140. */
  4141. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4142. function TextAnnotationElement(parameters) {
  4143. var isRenderable = !!(parameters.data.hasPopup ||
  4144. parameters.data.title || parameters.data.contents);
  4145. AnnotationElement.call(this, parameters, isRenderable);
  4146. }
  4147. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4148. /**
  4149. * Render the text annotation's HTML element in the empty container.
  4150. *
  4151. * @public
  4152. * @memberof TextAnnotationElement
  4153. * @returns {HTMLSectionElement}
  4154. */
  4155. render: function TextAnnotationElement_render() {
  4156. this.container.className = 'textAnnotation';
  4157. var image = document.createElement('img');
  4158. image.style.height = this.container.style.height;
  4159. image.style.width = this.container.style.width;
  4160. image.src = this.imageResourcesPath + 'annotation-' +
  4161. this.data.name.toLowerCase() + '.svg';
  4162. image.alt = '[{{type}} Annotation]';
  4163. image.dataset.l10nId = 'text_annotation_type';
  4164. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4165. if (!this.data.hasPopup) {
  4166. this._createPopup(this.container, image, this.data);
  4167. }
  4168. this.container.appendChild(image);
  4169. return this.container;
  4170. }
  4171. });
  4172. return TextAnnotationElement;
  4173. })();
  4174. /**
  4175. * @class
  4176. * @alias WidgetAnnotationElement
  4177. */
  4178. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4179. function WidgetAnnotationElement(parameters) {
  4180. AnnotationElement.call(this, parameters, true);
  4181. }
  4182. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4183. /**
  4184. * Render the widget annotation's HTML element in the empty container.
  4185. *
  4186. * @public
  4187. * @memberof WidgetAnnotationElement
  4188. * @returns {HTMLSectionElement}
  4189. */
  4190. render: function WidgetAnnotationElement_render() {
  4191. // Show only the container for unsupported field types.
  4192. return this.container;
  4193. }
  4194. });
  4195. return WidgetAnnotationElement;
  4196. })();
  4197. /**
  4198. * @class
  4199. * @alias TextWidgetAnnotationElement
  4200. */
  4201. var TextWidgetAnnotationElement = (
  4202. function TextWidgetAnnotationElementClosure() {
  4203. var TEXT_ALIGNMENT = ['left', 'center', 'right'];
  4204. function TextWidgetAnnotationElement(parameters) {
  4205. WidgetAnnotationElement.call(this, parameters);
  4206. }
  4207. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4208. /**
  4209. * Render the text widget annotation's HTML element in the empty container.
  4210. *
  4211. * @public
  4212. * @memberof TextWidgetAnnotationElement
  4213. * @returns {HTMLSectionElement}
  4214. */
  4215. render: function TextWidgetAnnotationElement_render() {
  4216. this.container.className = 'textWidgetAnnotation';
  4217. var element = null;
  4218. if (this.renderInteractiveForms) {
  4219. element = document.createElement('input');
  4220. element.type = 'text';
  4221. element.value = this.data.fieldValue;
  4222. if (isInt(this.data.maxLen)) {
  4223. element.maxLength = this.data.maxLen;
  4224. }
  4225. } else {
  4226. element = document.createElement('div');
  4227. element.textContent = this.data.fieldValue;
  4228. element.style.verticalAlign = 'middle';
  4229. element.style.display = 'table-cell';
  4230. var font = null;
  4231. if (this.data.fontRefName) {
  4232. font = this.page.commonObjs.getData(this.data.fontRefName);
  4233. }
  4234. this._setTextStyle(element, font);
  4235. }
  4236. if (isInt(this.data.textAlignment)) {
  4237. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4238. }
  4239. this.container.appendChild(element);
  4240. return this.container;
  4241. },
  4242. /**
  4243. * Apply text styles to the text in the element.
  4244. *
  4245. * @private
  4246. * @param {HTMLDivElement} element
  4247. * @param {Object} font
  4248. * @memberof TextWidgetAnnotationElement
  4249. */
  4250. _setTextStyle:
  4251. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4252. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4253. var style = element.style;
  4254. style.fontSize = this.data.fontSize + 'px';
  4255. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4256. if (!font) {
  4257. return;
  4258. }
  4259. style.fontWeight = (font.black ?
  4260. (font.bold ? '900' : 'bold') :
  4261. (font.bold ? 'bold' : 'normal'));
  4262. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4263. // Use a reasonable default font if the font doesn't specify a fallback.
  4264. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4265. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4266. style.fontFamily = fontFamily + fallbackName;
  4267. }
  4268. });
  4269. return TextWidgetAnnotationElement;
  4270. })();
  4271. /**
  4272. * @class
  4273. * @alias PopupAnnotationElement
  4274. */
  4275. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4276. function PopupAnnotationElement(parameters) {
  4277. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4278. AnnotationElement.call(this, parameters, isRenderable);
  4279. }
  4280. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4281. /**
  4282. * Render the popup annotation's HTML element in the empty container.
  4283. *
  4284. * @public
  4285. * @memberof PopupAnnotationElement
  4286. * @returns {HTMLSectionElement}
  4287. */
  4288. render: function PopupAnnotationElement_render() {
  4289. this.container.className = 'popupAnnotation';
  4290. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4291. var parentElement = this.layer.querySelector(selector);
  4292. if (!parentElement) {
  4293. return this.container;
  4294. }
  4295. var popup = new PopupElement({
  4296. container: this.container,
  4297. trigger: parentElement,
  4298. color: this.data.color,
  4299. title: this.data.title,
  4300. contents: this.data.contents
  4301. });
  4302. // Position the popup next to the parent annotation's container.
  4303. // PDF viewers ignore a popup annotation's rectangle.
  4304. var parentLeft = parseFloat(parentElement.style.left);
  4305. var parentWidth = parseFloat(parentElement.style.width);
  4306. CustomStyle.setProp('transformOrigin', this.container,
  4307. -(parentLeft + parentWidth) + 'px -' +
  4308. parentElement.style.top);
  4309. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4310. this.container.appendChild(popup.render());
  4311. return this.container;
  4312. }
  4313. });
  4314. return PopupAnnotationElement;
  4315. })();
  4316. /**
  4317. * @class
  4318. * @alias PopupElement
  4319. */
  4320. var PopupElement = (function PopupElementClosure() {
  4321. var BACKGROUND_ENLIGHT = 0.7;
  4322. function PopupElement(parameters) {
  4323. this.container = parameters.container;
  4324. this.trigger = parameters.trigger;
  4325. this.color = parameters.color;
  4326. this.title = parameters.title;
  4327. this.contents = parameters.contents;
  4328. this.hideWrapper = parameters.hideWrapper || false;
  4329. this.pinned = false;
  4330. }
  4331. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4332. /**
  4333. * Render the popup's HTML element.
  4334. *
  4335. * @public
  4336. * @memberof PopupElement
  4337. * @returns {HTMLSectionElement}
  4338. */
  4339. render: function PopupElement_render() {
  4340. var wrapper = document.createElement('div');
  4341. wrapper.className = 'popupWrapper';
  4342. // For Popup annotations we hide the entire section because it contains
  4343. // only the popup. However, for Text annotations without a separate Popup
  4344. // annotation, we cannot hide the entire container as the image would
  4345. // disappear too. In that special case, hiding the wrapper suffices.
  4346. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4347. this.hideElement.setAttribute('hidden', true);
  4348. var popup = document.createElement('div');
  4349. popup.className = 'popup';
  4350. var color = this.color;
  4351. if (color) {
  4352. // Enlighten the color.
  4353. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4354. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4355. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4356. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4357. }
  4358. var contents = this._formatContents(this.contents);
  4359. var title = document.createElement('h1');
  4360. title.textContent = this.title;
  4361. // Attach the event listeners to the trigger element.
  4362. this.trigger.addEventListener('click', this._toggle.bind(this));
  4363. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4364. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4365. popup.addEventListener('click', this._hide.bind(this, true));
  4366. popup.appendChild(title);
  4367. popup.appendChild(contents);
  4368. wrapper.appendChild(popup);
  4369. return wrapper;
  4370. },
  4371. /**
  4372. * Format the contents of the popup by adding newlines where necessary.
  4373. *
  4374. * @private
  4375. * @param {string} contents
  4376. * @memberof PopupElement
  4377. * @returns {HTMLParagraphElement}
  4378. */
  4379. _formatContents: function PopupElement_formatContents(contents) {
  4380. var p = document.createElement('p');
  4381. var lines = contents.split(/(?:\r\n?|\n)/);
  4382. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4383. var line = lines[i];
  4384. p.appendChild(document.createTextNode(line));
  4385. if (i < (ii - 1)) {
  4386. p.appendChild(document.createElement('br'));
  4387. }
  4388. }
  4389. return p;
  4390. },
  4391. /**
  4392. * Toggle the visibility of the popup.
  4393. *
  4394. * @private
  4395. * @memberof PopupElement
  4396. */
  4397. _toggle: function PopupElement_toggle() {
  4398. if (this.pinned) {
  4399. this._hide(true);
  4400. } else {
  4401. this._show(true);
  4402. }
  4403. },
  4404. /**
  4405. * Show the popup.
  4406. *
  4407. * @private
  4408. * @param {boolean} pin
  4409. * @memberof PopupElement
  4410. */
  4411. _show: function PopupElement_show(pin) {
  4412. if (pin) {
  4413. this.pinned = true;
  4414. }
  4415. if (this.hideElement.hasAttribute('hidden')) {
  4416. this.hideElement.removeAttribute('hidden');
  4417. this.container.style.zIndex += 1;
  4418. }
  4419. },
  4420. /**
  4421. * Hide the popup.
  4422. *
  4423. * @private
  4424. * @param {boolean} unpin
  4425. * @memberof PopupElement
  4426. */
  4427. _hide: function PopupElement_hide(unpin) {
  4428. if (unpin) {
  4429. this.pinned = false;
  4430. }
  4431. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4432. this.hideElement.setAttribute('hidden', true);
  4433. this.container.style.zIndex -= 1;
  4434. }
  4435. }
  4436. };
  4437. return PopupElement;
  4438. })();
  4439. /**
  4440. * @class
  4441. * @alias HighlightAnnotationElement
  4442. */
  4443. var HighlightAnnotationElement = (
  4444. function HighlightAnnotationElementClosure() {
  4445. function HighlightAnnotationElement(parameters) {
  4446. var isRenderable = !!(parameters.data.hasPopup ||
  4447. parameters.data.title || parameters.data.contents);
  4448. AnnotationElement.call(this, parameters, isRenderable);
  4449. }
  4450. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4451. /**
  4452. * Render the highlight annotation's HTML element in the empty container.
  4453. *
  4454. * @public
  4455. * @memberof HighlightAnnotationElement
  4456. * @returns {HTMLSectionElement}
  4457. */
  4458. render: function HighlightAnnotationElement_render() {
  4459. this.container.className = 'highlightAnnotation';
  4460. if (!this.data.hasPopup) {
  4461. this._createPopup(this.container, null, this.data);
  4462. }
  4463. return this.container;
  4464. }
  4465. });
  4466. return HighlightAnnotationElement;
  4467. })();
  4468. /**
  4469. * @class
  4470. * @alias UnderlineAnnotationElement
  4471. */
  4472. var UnderlineAnnotationElement = (
  4473. function UnderlineAnnotationElementClosure() {
  4474. function UnderlineAnnotationElement(parameters) {
  4475. var isRenderable = !!(parameters.data.hasPopup ||
  4476. parameters.data.title || parameters.data.contents);
  4477. AnnotationElement.call(this, parameters, isRenderable);
  4478. }
  4479. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4480. /**
  4481. * Render the underline annotation's HTML element in the empty container.
  4482. *
  4483. * @public
  4484. * @memberof UnderlineAnnotationElement
  4485. * @returns {HTMLSectionElement}
  4486. */
  4487. render: function UnderlineAnnotationElement_render() {
  4488. this.container.className = 'underlineAnnotation';
  4489. if (!this.data.hasPopup) {
  4490. this._createPopup(this.container, null, this.data);
  4491. }
  4492. return this.container;
  4493. }
  4494. });
  4495. return UnderlineAnnotationElement;
  4496. })();
  4497. /**
  4498. * @class
  4499. * @alias SquigglyAnnotationElement
  4500. */
  4501. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4502. function SquigglyAnnotationElement(parameters) {
  4503. var isRenderable = !!(parameters.data.hasPopup ||
  4504. parameters.data.title || parameters.data.contents);
  4505. AnnotationElement.call(this, parameters, isRenderable);
  4506. }
  4507. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4508. /**
  4509. * Render the squiggly annotation's HTML element in the empty container.
  4510. *
  4511. * @public
  4512. * @memberof SquigglyAnnotationElement
  4513. * @returns {HTMLSectionElement}
  4514. */
  4515. render: function SquigglyAnnotationElement_render() {
  4516. this.container.className = 'squigglyAnnotation';
  4517. if (!this.data.hasPopup) {
  4518. this._createPopup(this.container, null, this.data);
  4519. }
  4520. return this.container;
  4521. }
  4522. });
  4523. return SquigglyAnnotationElement;
  4524. })();
  4525. /**
  4526. * @class
  4527. * @alias StrikeOutAnnotationElement
  4528. */
  4529. var StrikeOutAnnotationElement = (
  4530. function StrikeOutAnnotationElementClosure() {
  4531. function StrikeOutAnnotationElement(parameters) {
  4532. var isRenderable = !!(parameters.data.hasPopup ||
  4533. parameters.data.title || parameters.data.contents);
  4534. AnnotationElement.call(this, parameters, isRenderable);
  4535. }
  4536. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4537. /**
  4538. * Render the strikeout annotation's HTML element in the empty container.
  4539. *
  4540. * @public
  4541. * @memberof StrikeOutAnnotationElement
  4542. * @returns {HTMLSectionElement}
  4543. */
  4544. render: function StrikeOutAnnotationElement_render() {
  4545. this.container.className = 'strikeoutAnnotation';
  4546. if (!this.data.hasPopup) {
  4547. this._createPopup(this.container, null, this.data);
  4548. }
  4549. return this.container;
  4550. }
  4551. });
  4552. return StrikeOutAnnotationElement;
  4553. })();
  4554. /**
  4555. * @class
  4556. * @alias FileAttachmentAnnotationElement
  4557. */
  4558. var FileAttachmentAnnotationElement = (
  4559. function FileAttachmentAnnotationElementClosure() {
  4560. function FileAttachmentAnnotationElement(parameters) {
  4561. AnnotationElement.call(this, parameters, true);
  4562. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4563. this.content = parameters.data.file.content;
  4564. }
  4565. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4566. /**
  4567. * Render the file attachment annotation's HTML element in the empty
  4568. * container.
  4569. *
  4570. * @public
  4571. * @memberof FileAttachmentAnnotationElement
  4572. * @returns {HTMLSectionElement}
  4573. */
  4574. render: function FileAttachmentAnnotationElement_render() {
  4575. this.container.className = 'fileAttachmentAnnotation';
  4576. var trigger = document.createElement('div');
  4577. trigger.style.height = this.container.style.height;
  4578. trigger.style.width = this.container.style.width;
  4579. trigger.addEventListener('dblclick', this._download.bind(this));
  4580. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4581. this._createPopup(this.container, trigger, this.data);
  4582. }
  4583. this.container.appendChild(trigger);
  4584. return this.container;
  4585. },
  4586. /**
  4587. * Download the file attachment associated with this annotation.
  4588. *
  4589. * @private
  4590. * @memberof FileAttachmentAnnotationElement
  4591. */
  4592. _download: function FileAttachmentAnnotationElement_download() {
  4593. if (!this.downloadManager) {
  4594. warn('Download cannot be started due to unavailable download manager');
  4595. return;
  4596. }
  4597. this.downloadManager.downloadData(this.content, this.filename, '');
  4598. }
  4599. });
  4600. return FileAttachmentAnnotationElement;
  4601. })();
  4602. /**
  4603. * @typedef {Object} AnnotationLayerParameters
  4604. * @property {PageViewport} viewport
  4605. * @property {HTMLDivElement} div
  4606. * @property {Array} annotations
  4607. * @property {PDFPage} page
  4608. * @property {IPDFLinkService} linkService
  4609. * @property {string} imageResourcesPath
  4610. * @property {boolean} renderInteractiveForms
  4611. */
  4612. /**
  4613. * @class
  4614. * @alias AnnotationLayer
  4615. */
  4616. var AnnotationLayer = (function AnnotationLayerClosure() {
  4617. return {
  4618. /**
  4619. * Render a new annotation layer with all annotation elements.
  4620. *
  4621. * @public
  4622. * @param {AnnotationLayerParameters} parameters
  4623. * @memberof AnnotationLayer
  4624. */
  4625. render: function AnnotationLayer_render(parameters) {
  4626. var annotationElementFactory = new AnnotationElementFactory();
  4627. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4628. var data = parameters.annotations[i];
  4629. if (!data) {
  4630. continue;
  4631. }
  4632. var properties = {
  4633. data: data,
  4634. layer: parameters.div,
  4635. page: parameters.page,
  4636. viewport: parameters.viewport,
  4637. linkService: parameters.linkService,
  4638. downloadManager: parameters.downloadManager,
  4639. imageResourcesPath: parameters.imageResourcesPath ||
  4640. getDefaultSetting('imageResourcesPath'),
  4641. renderInteractiveForms: parameters.renderInteractiveForms || false,
  4642. };
  4643. var element = annotationElementFactory.create(properties);
  4644. if (element.isRenderable) {
  4645. parameters.div.appendChild(element.render());
  4646. }
  4647. }
  4648. },
  4649. /**
  4650. * Update the annotation elements on existing annotation layer.
  4651. *
  4652. * @public
  4653. * @param {AnnotationLayerParameters} parameters
  4654. * @memberof AnnotationLayer
  4655. */
  4656. update: function AnnotationLayer_update(parameters) {
  4657. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4658. var data = parameters.annotations[i];
  4659. var element = parameters.div.querySelector(
  4660. '[data-annotation-id="' + data.id + '"]');
  4661. if (element) {
  4662. CustomStyle.setProp('transform', element,
  4663. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4664. }
  4665. }
  4666. parameters.div.removeAttribute('hidden');
  4667. }
  4668. };
  4669. })();
  4670. exports.AnnotationLayer = AnnotationLayer;
  4671. }));
  4672. (function (root, factory) {
  4673. {
  4674. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4675. root.pdfjsDisplayDOMUtils);
  4676. }
  4677. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4678. var Util = sharedUtil.Util;
  4679. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4680. var CustomStyle = displayDOMUtils.CustomStyle;
  4681. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4682. /**
  4683. * Text layer render parameters.
  4684. *
  4685. * @typedef {Object} TextLayerRenderParameters
  4686. * @property {TextContent} textContent - Text content to render (the object is
  4687. * returned by the page's getTextContent() method).
  4688. * @property {HTMLElement} container - HTML element that will contain text runs.
  4689. * @property {PageViewport} viewport - The target viewport to properly
  4690. * layout the text runs.
  4691. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4692. * the text items of the textContent input. This is output and shall be
  4693. * initially be set to empty array.
  4694. * @property {number} timeout - (optional) Delay in milliseconds before
  4695. * rendering of the text runs occurs.
  4696. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4697. * text selection enhancement.
  4698. */
  4699. var renderTextLayer = (function renderTextLayerClosure() {
  4700. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4701. var NonWhitespaceRegexp = /\S/;
  4702. function isAllWhitespace(str) {
  4703. return !NonWhitespaceRegexp.test(str);
  4704. }
  4705. function appendText(task, geom, styles) {
  4706. // Initialize all used properties to keep the caches monomorphic.
  4707. var textDiv = document.createElement('div');
  4708. var textDivProperties = {
  4709. angle: 0,
  4710. canvasWidth: 0,
  4711. isWhitespace: false,
  4712. originalTransform: '',
  4713. paddingBottom: 0,
  4714. paddingLeft: 0,
  4715. paddingRight: 0,
  4716. paddingTop: 0,
  4717. scale: 1,
  4718. };
  4719. task._textDivs.push(textDiv);
  4720. if (isAllWhitespace(geom.str)) {
  4721. textDivProperties.isWhitespace = true;
  4722. task._textDivProperties.set(textDiv, textDivProperties);
  4723. return;
  4724. }
  4725. var tx = Util.transform(task._viewport.transform, geom.transform);
  4726. var angle = Math.atan2(tx[1], tx[0]);
  4727. var style = styles[geom.fontName];
  4728. if (style.vertical) {
  4729. angle += Math.PI / 2;
  4730. }
  4731. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4732. var fontAscent = fontHeight;
  4733. if (style.ascent) {
  4734. fontAscent = style.ascent * fontAscent;
  4735. } else if (style.descent) {
  4736. fontAscent = (1 + style.descent) * fontAscent;
  4737. }
  4738. var left;
  4739. var top;
  4740. if (angle === 0) {
  4741. left = tx[4];
  4742. top = tx[5] - fontAscent;
  4743. } else {
  4744. left = tx[4] + (fontAscent * Math.sin(angle));
  4745. top = tx[5] - (fontAscent * Math.cos(angle));
  4746. }
  4747. textDiv.style.left = left + 'px';
  4748. textDiv.style.top = top + 'px';
  4749. textDiv.style.fontSize = fontHeight + 'px';
  4750. textDiv.style.fontFamily = style.fontFamily;
  4751. textDiv.textContent = geom.str;
  4752. // |fontName| is only used by the Font Inspector. This test will succeed
  4753. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4754. // not worth the effort to do a more accurate test. We only use `dataset`
  4755. // here to make the font name available for the debugger.
  4756. if (getDefaultSetting('pdfBug')) {
  4757. textDiv.dataset.fontName = geom.fontName;
  4758. }
  4759. if (angle !== 0) {
  4760. textDivProperties.angle = angle * (180 / Math.PI);
  4761. }
  4762. // We don't bother scaling single-char text divs, because it has very
  4763. // little effect on text highlighting. This makes scrolling on docs with
  4764. // lots of such divs a lot faster.
  4765. if (geom.str.length > 1) {
  4766. if (style.vertical) {
  4767. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4768. } else {
  4769. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4770. }
  4771. }
  4772. task._textDivProperties.set(textDiv, textDivProperties);
  4773. if (task._enhanceTextSelection) {
  4774. var angleCos = 1, angleSin = 0;
  4775. if (angle !== 0) {
  4776. angleCos = Math.cos(angle);
  4777. angleSin = Math.sin(angle);
  4778. }
  4779. var divWidth = (style.vertical ? geom.height : geom.width) *
  4780. task._viewport.scale;
  4781. var divHeight = fontHeight;
  4782. var m, b;
  4783. if (angle !== 0) {
  4784. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4785. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4786. } else {
  4787. b = [left, top, left + divWidth, top + divHeight];
  4788. }
  4789. task._bounds.push({
  4790. left: b[0],
  4791. top: b[1],
  4792. right: b[2],
  4793. bottom: b[3],
  4794. div: textDiv,
  4795. size: [divWidth, divHeight],
  4796. m: m
  4797. });
  4798. }
  4799. }
  4800. function render(task) {
  4801. if (task._canceled) {
  4802. return;
  4803. }
  4804. var textLayerFrag = task._container;
  4805. var textDivs = task._textDivs;
  4806. var capability = task._capability;
  4807. var textDivsLength = textDivs.length;
  4808. // No point in rendering many divs as it would make the browser
  4809. // unusable even after the divs are rendered.
  4810. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4811. task._renderingDone = true;
  4812. capability.resolve();
  4813. return;
  4814. }
  4815. var canvas = document.createElement('canvas');
  4816. canvas.mozOpaque = true;
  4817. var ctx = canvas.getContext('2d', {alpha: false});
  4818. var lastFontSize;
  4819. var lastFontFamily;
  4820. for (var i = 0; i < textDivsLength; i++) {
  4821. var textDiv = textDivs[i];
  4822. var textDivProperties = task._textDivProperties.get(textDiv);
  4823. if (textDivProperties.isWhitespace) {
  4824. continue;
  4825. }
  4826. var fontSize = textDiv.style.fontSize;
  4827. var fontFamily = textDiv.style.fontFamily;
  4828. // Only build font string and set to context if different from last.
  4829. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4830. ctx.font = fontSize + ' ' + fontFamily;
  4831. lastFontSize = fontSize;
  4832. lastFontFamily = fontFamily;
  4833. }
  4834. var width = ctx.measureText(textDiv.textContent).width;
  4835. textLayerFrag.appendChild(textDiv);
  4836. var transform = '';
  4837. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4838. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4839. transform = 'scaleX(' + textDivProperties.scale + ')';
  4840. }
  4841. if (textDivProperties.angle !== 0) {
  4842. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4843. }
  4844. if (transform !== '') {
  4845. textDivProperties.originalTransform = transform;
  4846. CustomStyle.setProp('transform', textDiv, transform);
  4847. }
  4848. task._textDivProperties.set(textDiv, textDivProperties);
  4849. }
  4850. task._renderingDone = true;
  4851. capability.resolve();
  4852. }
  4853. function expand(task) {
  4854. var bounds = task._bounds;
  4855. var viewport = task._viewport;
  4856. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4857. for (var i = 0; i < expanded.length; i++) {
  4858. var div = bounds[i].div;
  4859. var divProperties = task._textDivProperties.get(div);
  4860. if (divProperties.angle === 0) {
  4861. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4862. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4863. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4864. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4865. task._textDivProperties.set(div, divProperties);
  4866. continue;
  4867. }
  4868. // Box is rotated -- trying to find padding so rotated div will not
  4869. // exceed its expanded bounds.
  4870. var e = expanded[i], b = bounds[i];
  4871. var m = b.m, c = m[0], s = m[1];
  4872. // Finding intersections with expanded box.
  4873. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4874. var ts = new Float64Array(64);
  4875. points.forEach(function (p, i) {
  4876. var t = Util.applyTransform(p, m);
  4877. ts[i + 0] = c && (e.left - t[0]) / c;
  4878. ts[i + 4] = s && (e.top - t[1]) / s;
  4879. ts[i + 8] = c && (e.right - t[0]) / c;
  4880. ts[i + 12] = s && (e.bottom - t[1]) / s;
  4881. ts[i + 16] = s && (e.left - t[0]) / -s;
  4882. ts[i + 20] = c && (e.top - t[1]) / c;
  4883. ts[i + 24] = s && (e.right - t[0]) / -s;
  4884. ts[i + 28] = c && (e.bottom - t[1]) / c;
  4885. ts[i + 32] = c && (e.left - t[0]) / -c;
  4886. ts[i + 36] = s && (e.top - t[1]) / -s;
  4887. ts[i + 40] = c && (e.right - t[0]) / -c;
  4888. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  4889. ts[i + 48] = s && (e.left - t[0]) / s;
  4890. ts[i + 52] = c && (e.top - t[1]) / -c;
  4891. ts[i + 56] = s && (e.right - t[0]) / s;
  4892. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  4893. });
  4894. var findPositiveMin = function (ts, offset, count) {
  4895. var result = 0;
  4896. for (var i = 0; i < count; i++) {
  4897. var t = ts[offset++];
  4898. if (t > 0) {
  4899. result = result ? Math.min(t, result) : t;
  4900. }
  4901. }
  4902. return result;
  4903. };
  4904. // Not based on math, but to simplify calculations, using cos and sin
  4905. // absolute values to not exceed the box (it can but insignificantly).
  4906. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  4907. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  4908. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  4909. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  4910. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  4911. task._textDivProperties.set(div, divProperties);
  4912. }
  4913. }
  4914. function expandBounds(width, height, boxes) {
  4915. var bounds = boxes.map(function (box, i) {
  4916. return {
  4917. x1: box.left,
  4918. y1: box.top,
  4919. x2: box.right,
  4920. y2: box.bottom,
  4921. index: i,
  4922. x1New: undefined,
  4923. x2New: undefined
  4924. };
  4925. });
  4926. expandBoundsLTR(width, bounds);
  4927. var expanded = new Array(boxes.length);
  4928. bounds.forEach(function (b) {
  4929. var i = b.index;
  4930. expanded[i] = {
  4931. left: b.x1New,
  4932. top: 0,
  4933. right: b.x2New,
  4934. bottom: 0
  4935. };
  4936. });
  4937. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  4938. // array and objects.
  4939. boxes.map(function (box, i) {
  4940. var e = expanded[i], b = bounds[i];
  4941. b.x1 = box.top;
  4942. b.y1 = width - e.right;
  4943. b.x2 = box.bottom;
  4944. b.y2 = width - e.left;
  4945. b.index = i;
  4946. b.x1New = undefined;
  4947. b.x2New = undefined;
  4948. });
  4949. expandBoundsLTR(height, bounds);
  4950. bounds.forEach(function (b) {
  4951. var i = b.index;
  4952. expanded[i].top = b.x1New;
  4953. expanded[i].bottom = b.x2New;
  4954. });
  4955. return expanded;
  4956. }
  4957. function expandBoundsLTR(width, bounds) {
  4958. // Sorting by x1 coordinate and walk by the bounds in the same order.
  4959. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  4960. // First we see on the horizon is a fake boundary.
  4961. var fakeBoundary = {
  4962. x1: -Infinity,
  4963. y1: -Infinity,
  4964. x2: 0,
  4965. y2: Infinity,
  4966. index: -1,
  4967. x1New: 0,
  4968. x2New: 0
  4969. };
  4970. var horizon = [{
  4971. start: -Infinity,
  4972. end: Infinity,
  4973. boundary: fakeBoundary
  4974. }];
  4975. bounds.forEach(function (boundary) {
  4976. // Searching for the affected part of horizon.
  4977. // TODO red-black tree or simple binary search
  4978. var i = 0;
  4979. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  4980. i++;
  4981. }
  4982. var j = horizon.length - 1;
  4983. while(j >= 0 && horizon[j].start >= boundary.y2) {
  4984. j--;
  4985. }
  4986. var horizonPart, affectedBoundary;
  4987. var q, k, maxXNew = -Infinity;
  4988. for (q = i; q <= j; q++) {
  4989. horizonPart = horizon[q];
  4990. affectedBoundary = horizonPart.boundary;
  4991. var xNew;
  4992. if (affectedBoundary.x2 > boundary.x1) {
  4993. // In the middle of the previous element, new x shall be at the
  4994. // boundary start. Extending if further if the affected bondary
  4995. // placed on top of the current one.
  4996. xNew = affectedBoundary.index > boundary.index ?
  4997. affectedBoundary.x1New : boundary.x1;
  4998. } else if (affectedBoundary.x2New === undefined) {
  4999. // We have some space in between, new x in middle will be a fair
  5000. // choice.
  5001. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5002. } else {
  5003. // Affected boundary has x2new set, using it as new x.
  5004. xNew = affectedBoundary.x2New;
  5005. }
  5006. if (xNew > maxXNew) {
  5007. maxXNew = xNew;
  5008. }
  5009. }
  5010. // Set new x1 for current boundary.
  5011. boundary.x1New = maxXNew;
  5012. // Adjusts new x2 for the affected boundaries.
  5013. for (q = i; q <= j; q++) {
  5014. horizonPart = horizon[q];
  5015. affectedBoundary = horizonPart.boundary;
  5016. if (affectedBoundary.x2New === undefined) {
  5017. // Was not set yet, choosing new x if possible.
  5018. if (affectedBoundary.x2 > boundary.x1) {
  5019. // Current and affected boundaries intersect. If affected boundary
  5020. // is placed on top of the current, shrinking the affected.
  5021. if (affectedBoundary.index > boundary.index) {
  5022. affectedBoundary.x2New = affectedBoundary.x2;
  5023. }
  5024. } else {
  5025. affectedBoundary.x2New = maxXNew;
  5026. }
  5027. } else if (affectedBoundary.x2New > maxXNew) {
  5028. // Affected boundary is touching new x, pushing it back.
  5029. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5030. }
  5031. }
  5032. // Fixing the horizon.
  5033. var changedHorizon = [], lastBoundary = null;
  5034. for (q = i; q <= j; q++) {
  5035. horizonPart = horizon[q];
  5036. affectedBoundary = horizonPart.boundary;
  5037. // Checking which boundary will be visible.
  5038. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5039. affectedBoundary : boundary;
  5040. if (lastBoundary === useBoundary) {
  5041. // Merging with previous.
  5042. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5043. } else {
  5044. changedHorizon.push({
  5045. start: horizonPart.start,
  5046. end: horizonPart.end,
  5047. boundary: useBoundary
  5048. });
  5049. lastBoundary = useBoundary;
  5050. }
  5051. }
  5052. if (horizon[i].start < boundary.y1) {
  5053. changedHorizon[0].start = boundary.y1;
  5054. changedHorizon.unshift({
  5055. start: horizon[i].start,
  5056. end: boundary.y1,
  5057. boundary: horizon[i].boundary
  5058. });
  5059. }
  5060. if (boundary.y2 < horizon[j].end) {
  5061. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5062. changedHorizon.push({
  5063. start: boundary.y2,
  5064. end: horizon[j].end,
  5065. boundary: horizon[j].boundary
  5066. });
  5067. }
  5068. // Set x2 new of boundary that is no longer visible (see overlapping case
  5069. // above).
  5070. // TODO more efficient, e.g. via reference counting.
  5071. for (q = i; q <= j; q++) {
  5072. horizonPart = horizon[q];
  5073. affectedBoundary = horizonPart.boundary;
  5074. if (affectedBoundary.x2New !== undefined) {
  5075. continue;
  5076. }
  5077. var used = false;
  5078. for (k = i - 1; !used && k >= 0 &&
  5079. horizon[k].start >= affectedBoundary.y1; k--) {
  5080. used = horizon[k].boundary === affectedBoundary;
  5081. }
  5082. for (k = j + 1; !used && k < horizon.length &&
  5083. horizon[k].end <= affectedBoundary.y2; k++) {
  5084. used = horizon[k].boundary === affectedBoundary;
  5085. }
  5086. for (k = 0; !used && k < changedHorizon.length; k++) {
  5087. used = changedHorizon[k].boundary === affectedBoundary;
  5088. }
  5089. if (!used) {
  5090. affectedBoundary.x2New = maxXNew;
  5091. }
  5092. }
  5093. Array.prototype.splice.apply(horizon,
  5094. [i, j - i + 1].concat(changedHorizon));
  5095. });
  5096. // Set new x2 for all unset boundaries.
  5097. horizon.forEach(function (horizonPart) {
  5098. var affectedBoundary = horizonPart.boundary;
  5099. if (affectedBoundary.x2New === undefined) {
  5100. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5101. }
  5102. });
  5103. }
  5104. /**
  5105. * Text layer rendering task.
  5106. *
  5107. * @param {TextContent} textContent
  5108. * @param {HTMLElement} container
  5109. * @param {PageViewport} viewport
  5110. * @param {Array} textDivs
  5111. * @param {boolean} enhanceTextSelection
  5112. * @private
  5113. */
  5114. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5115. enhanceTextSelection) {
  5116. this._textContent = textContent;
  5117. this._container = container;
  5118. this._viewport = viewport;
  5119. this._textDivs = textDivs || [];
  5120. this._textDivProperties = new WeakMap();
  5121. this._renderingDone = false;
  5122. this._canceled = false;
  5123. this._capability = createPromiseCapability();
  5124. this._renderTimer = null;
  5125. this._bounds = [];
  5126. this._enhanceTextSelection = !!enhanceTextSelection;
  5127. this._expanded = false;
  5128. }
  5129. TextLayerRenderTask.prototype = {
  5130. get promise() {
  5131. return this._capability.promise;
  5132. },
  5133. cancel: function TextLayer_cancel() {
  5134. this._canceled = true;
  5135. if (this._renderTimer !== null) {
  5136. clearTimeout(this._renderTimer);
  5137. this._renderTimer = null;
  5138. }
  5139. this._capability.reject('canceled');
  5140. },
  5141. _render: function TextLayer_render(timeout) {
  5142. var textItems = this._textContent.items;
  5143. var textStyles = this._textContent.styles;
  5144. for (var i = 0, len = textItems.length; i < len; i++) {
  5145. appendText(this, textItems[i], textStyles);
  5146. }
  5147. if (!timeout) { // Render right away
  5148. render(this);
  5149. } else { // Schedule
  5150. var self = this;
  5151. this._renderTimer = setTimeout(function() {
  5152. render(self);
  5153. self._renderTimer = null;
  5154. }, timeout);
  5155. }
  5156. },
  5157. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5158. if (!this._enhanceTextSelection || !this._renderingDone) {
  5159. return;
  5160. }
  5161. if (!this._expanded) {
  5162. expand(this);
  5163. this._expanded = true;
  5164. this._bounds.length = 0;
  5165. }
  5166. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5167. var div = this._textDivs[i];
  5168. var divProperties = this._textDivProperties.get(div);
  5169. if (expandDivs) {
  5170. var transform = '';
  5171. if (divProperties.scale !== 1) {
  5172. transform = 'scaleX(' + divProperties.scale + ')';
  5173. }
  5174. if (divProperties.angle !== 0) {
  5175. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5176. }
  5177. if (divProperties.paddingLeft !== 0) {
  5178. div.style.paddingLeft =
  5179. (divProperties.paddingLeft / divProperties.scale) + 'px';
  5180. transform += ' translateX(' +
  5181. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5182. }
  5183. if (divProperties.paddingTop !== 0) {
  5184. div.style.paddingTop = divProperties.paddingTop + 'px';
  5185. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5186. }
  5187. if (divProperties.paddingRight !== 0) {
  5188. div.style.paddingRight =
  5189. (divProperties.paddingRight / divProperties.scale) + 'px';
  5190. }
  5191. if (divProperties.paddingBottom !== 0) {
  5192. div.style.paddingBottom = divProperties.paddingBottom + 'px';
  5193. }
  5194. if (transform !== '') {
  5195. CustomStyle.setProp('transform', div, transform);
  5196. }
  5197. } else {
  5198. div.style.padding = 0;
  5199. CustomStyle.setProp('transform', div,
  5200. divProperties.originalTransform);
  5201. }
  5202. }
  5203. },
  5204. };
  5205. /**
  5206. * Starts rendering of the text layer.
  5207. *
  5208. * @param {TextLayerRenderParameters} renderParameters
  5209. * @returns {TextLayerRenderTask}
  5210. */
  5211. function renderTextLayer(renderParameters) {
  5212. var task = new TextLayerRenderTask(renderParameters.textContent,
  5213. renderParameters.container,
  5214. renderParameters.viewport,
  5215. renderParameters.textDivs,
  5216. renderParameters.enhanceTextSelection);
  5217. task._render(renderParameters.timeout);
  5218. return task;
  5219. }
  5220. return renderTextLayer;
  5221. })();
  5222. exports.renderTextLayer = renderTextLayer;
  5223. }));
  5224. (function (root, factory) {
  5225. {
  5226. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5227. root.pdfjsDisplayDOMUtils);
  5228. }
  5229. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5230. var shadow = sharedUtil.shadow;
  5231. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5232. var WebGLUtils = (function WebGLUtilsClosure() {
  5233. function loadShader(gl, code, shaderType) {
  5234. var shader = gl.createShader(shaderType);
  5235. gl.shaderSource(shader, code);
  5236. gl.compileShader(shader);
  5237. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5238. if (!compiled) {
  5239. var errorMsg = gl.getShaderInfoLog(shader);
  5240. throw new Error('Error during shader compilation: ' + errorMsg);
  5241. }
  5242. return shader;
  5243. }
  5244. function createVertexShader(gl, code) {
  5245. return loadShader(gl, code, gl.VERTEX_SHADER);
  5246. }
  5247. function createFragmentShader(gl, code) {
  5248. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5249. }
  5250. function createProgram(gl, shaders) {
  5251. var program = gl.createProgram();
  5252. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5253. gl.attachShader(program, shaders[i]);
  5254. }
  5255. gl.linkProgram(program);
  5256. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5257. if (!linked) {
  5258. var errorMsg = gl.getProgramInfoLog(program);
  5259. throw new Error('Error during program linking: ' + errorMsg);
  5260. }
  5261. return program;
  5262. }
  5263. function createTexture(gl, image, textureId) {
  5264. gl.activeTexture(textureId);
  5265. var texture = gl.createTexture();
  5266. gl.bindTexture(gl.TEXTURE_2D, texture);
  5267. // Set the parameters so we can render any size image.
  5268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5272. // Upload the image into the texture.
  5273. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5274. return texture;
  5275. }
  5276. var currentGL, currentCanvas;
  5277. function generateGL() {
  5278. if (currentGL) {
  5279. return;
  5280. }
  5281. currentCanvas = document.createElement('canvas');
  5282. currentGL = currentCanvas.getContext('webgl',
  5283. { premultipliedalpha: false });
  5284. }
  5285. var smaskVertexShaderCode = '\
  5286. attribute vec2 a_position; \
  5287. attribute vec2 a_texCoord; \
  5288. \
  5289. uniform vec2 u_resolution; \
  5290. \
  5291. varying vec2 v_texCoord; \
  5292. \
  5293. void main() { \
  5294. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5295. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5296. \
  5297. v_texCoord = a_texCoord; \
  5298. } ';
  5299. var smaskFragmentShaderCode = '\
  5300. precision mediump float; \
  5301. \
  5302. uniform vec4 u_backdrop; \
  5303. uniform int u_subtype; \
  5304. uniform sampler2D u_image; \
  5305. uniform sampler2D u_mask; \
  5306. \
  5307. varying vec2 v_texCoord; \
  5308. \
  5309. void main() { \
  5310. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5311. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5312. if (u_backdrop.a > 0.0) { \
  5313. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5314. u_backdrop.rgb * (1.0 - maskColor.a); \
  5315. } \
  5316. float lum; \
  5317. if (u_subtype == 0) { \
  5318. lum = maskColor.a; \
  5319. } else { \
  5320. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5321. maskColor.b * 0.11; \
  5322. } \
  5323. imageColor.a *= lum; \
  5324. imageColor.rgb *= imageColor.a; \
  5325. gl_FragColor = imageColor; \
  5326. } ';
  5327. var smaskCache = null;
  5328. function initSmaskGL() {
  5329. var canvas, gl;
  5330. generateGL();
  5331. canvas = currentCanvas;
  5332. currentCanvas = null;
  5333. gl = currentGL;
  5334. currentGL = null;
  5335. // setup a GLSL program
  5336. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5337. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5338. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5339. gl.useProgram(program);
  5340. var cache = {};
  5341. cache.gl = gl;
  5342. cache.canvas = canvas;
  5343. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5344. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5345. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5346. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5347. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5348. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5349. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5350. // provide texture coordinates for the rectangle.
  5351. var texCoordBuffer = gl.createBuffer();
  5352. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5353. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5354. 0.0, 0.0,
  5355. 1.0, 0.0,
  5356. 0.0, 1.0,
  5357. 0.0, 1.0,
  5358. 1.0, 0.0,
  5359. 1.0, 1.0]), gl.STATIC_DRAW);
  5360. gl.enableVertexAttribArray(texCoordLocation);
  5361. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5362. gl.uniform1i(texLayerLocation, 0);
  5363. gl.uniform1i(texMaskLocation, 1);
  5364. smaskCache = cache;
  5365. }
  5366. function composeSMask(layer, mask, properties) {
  5367. var width = layer.width, height = layer.height;
  5368. if (!smaskCache) {
  5369. initSmaskGL();
  5370. }
  5371. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5372. canvas.width = width;
  5373. canvas.height = height;
  5374. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5375. gl.uniform2f(cache.resolutionLocation, width, height);
  5376. if (properties.backdrop) {
  5377. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5378. properties.backdrop[1], properties.backdrop[2], 1);
  5379. } else {
  5380. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5381. }
  5382. gl.uniform1i(cache.subtypeLocation,
  5383. properties.subtype === 'Luminosity' ? 1 : 0);
  5384. // Create a textures
  5385. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5386. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5387. // Create a buffer and put a single clipspace rectangle in
  5388. // it (2 triangles)
  5389. var buffer = gl.createBuffer();
  5390. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5391. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5392. 0, 0,
  5393. width, 0,
  5394. 0, height,
  5395. 0, height,
  5396. width, 0,
  5397. width, height]), gl.STATIC_DRAW);
  5398. gl.enableVertexAttribArray(cache.positionLocation);
  5399. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5400. // draw
  5401. gl.clearColor(0, 0, 0, 0);
  5402. gl.enable(gl.BLEND);
  5403. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5404. gl.clear(gl.COLOR_BUFFER_BIT);
  5405. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5406. gl.flush();
  5407. gl.deleteTexture(texture);
  5408. gl.deleteTexture(maskTexture);
  5409. gl.deleteBuffer(buffer);
  5410. return canvas;
  5411. }
  5412. var figuresVertexShaderCode = '\
  5413. attribute vec2 a_position; \
  5414. attribute vec3 a_color; \
  5415. \
  5416. uniform vec2 u_resolution; \
  5417. uniform vec2 u_scale; \
  5418. uniform vec2 u_offset; \
  5419. \
  5420. varying vec4 v_color; \
  5421. \
  5422. void main() { \
  5423. vec2 position = (a_position + u_offset) * u_scale; \
  5424. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5425. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5426. \
  5427. v_color = vec4(a_color / 255.0, 1.0); \
  5428. } ';
  5429. var figuresFragmentShaderCode = '\
  5430. precision mediump float; \
  5431. \
  5432. varying vec4 v_color; \
  5433. \
  5434. void main() { \
  5435. gl_FragColor = v_color; \
  5436. } ';
  5437. var figuresCache = null;
  5438. function initFiguresGL() {
  5439. var canvas, gl;
  5440. generateGL();
  5441. canvas = currentCanvas;
  5442. currentCanvas = null;
  5443. gl = currentGL;
  5444. currentGL = null;
  5445. // setup a GLSL program
  5446. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5447. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5448. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5449. gl.useProgram(program);
  5450. var cache = {};
  5451. cache.gl = gl;
  5452. cache.canvas = canvas;
  5453. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5454. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5455. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5456. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5457. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5458. figuresCache = cache;
  5459. }
  5460. function drawFigures(width, height, backgroundColor, figures, context) {
  5461. if (!figuresCache) {
  5462. initFiguresGL();
  5463. }
  5464. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5465. canvas.width = width;
  5466. canvas.height = height;
  5467. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5468. gl.uniform2f(cache.resolutionLocation, width, height);
  5469. // count triangle points
  5470. var count = 0;
  5471. var i, ii, rows;
  5472. for (i = 0, ii = figures.length; i < ii; i++) {
  5473. switch (figures[i].type) {
  5474. case 'lattice':
  5475. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5476. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5477. break;
  5478. case 'triangles':
  5479. count += figures[i].coords.length;
  5480. break;
  5481. }
  5482. }
  5483. // transfer data
  5484. var coords = new Float32Array(count * 2);
  5485. var colors = new Uint8Array(count * 3);
  5486. var coordsMap = context.coords, colorsMap = context.colors;
  5487. var pIndex = 0, cIndex = 0;
  5488. for (i = 0, ii = figures.length; i < ii; i++) {
  5489. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5490. switch (figure.type) {
  5491. case 'lattice':
  5492. var cols = figure.verticesPerRow;
  5493. rows = (ps.length / cols) | 0;
  5494. for (var row = 1; row < rows; row++) {
  5495. var offset = row * cols + 1;
  5496. for (var col = 1; col < cols; col++, offset++) {
  5497. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5498. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5499. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5500. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5501. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5502. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5503. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5504. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5505. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5506. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5507. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5508. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5509. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5510. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5511. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5512. coords[pIndex + 6] = coords[pIndex + 2];
  5513. coords[pIndex + 7] = coords[pIndex + 3];
  5514. coords[pIndex + 8] = coords[pIndex + 4];
  5515. coords[pIndex + 9] = coords[pIndex + 5];
  5516. coords[pIndex + 10] = coordsMap[ps[offset]];
  5517. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5518. colors[cIndex + 9] = colors[cIndex + 3];
  5519. colors[cIndex + 10] = colors[cIndex + 4];
  5520. colors[cIndex + 11] = colors[cIndex + 5];
  5521. colors[cIndex + 12] = colors[cIndex + 6];
  5522. colors[cIndex + 13] = colors[cIndex + 7];
  5523. colors[cIndex + 14] = colors[cIndex + 8];
  5524. colors[cIndex + 15] = colorsMap[cs[offset]];
  5525. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5526. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5527. pIndex += 12;
  5528. cIndex += 18;
  5529. }
  5530. }
  5531. break;
  5532. case 'triangles':
  5533. for (var j = 0, jj = ps.length; j < jj; j++) {
  5534. coords[pIndex] = coordsMap[ps[j]];
  5535. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5536. colors[cIndex] = colorsMap[cs[j]];
  5537. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5538. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5539. pIndex += 2;
  5540. cIndex += 3;
  5541. }
  5542. break;
  5543. }
  5544. }
  5545. // draw
  5546. if (backgroundColor) {
  5547. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5548. backgroundColor[2] / 255, 1.0);
  5549. } else {
  5550. gl.clearColor(0, 0, 0, 0);
  5551. }
  5552. gl.clear(gl.COLOR_BUFFER_BIT);
  5553. var coordsBuffer = gl.createBuffer();
  5554. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5555. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5556. gl.enableVertexAttribArray(cache.positionLocation);
  5557. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5558. var colorsBuffer = gl.createBuffer();
  5559. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5560. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5561. gl.enableVertexAttribArray(cache.colorLocation);
  5562. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5563. 0, 0);
  5564. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5565. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5566. gl.drawArrays(gl.TRIANGLES, 0, count);
  5567. gl.flush();
  5568. gl.deleteBuffer(coordsBuffer);
  5569. gl.deleteBuffer(colorsBuffer);
  5570. return canvas;
  5571. }
  5572. function cleanup() {
  5573. if (smaskCache && smaskCache.canvas) {
  5574. smaskCache.canvas.width = 0;
  5575. smaskCache.canvas.height = 0;
  5576. }
  5577. if (figuresCache && figuresCache.canvas) {
  5578. figuresCache.canvas.width = 0;
  5579. figuresCache.canvas.height = 0;
  5580. }
  5581. smaskCache = null;
  5582. figuresCache = null;
  5583. }
  5584. return {
  5585. get isEnabled() {
  5586. if (getDefaultSetting('disableWebGL')) {
  5587. return false;
  5588. }
  5589. var enabled = false;
  5590. try {
  5591. generateGL();
  5592. enabled = !!currentGL;
  5593. } catch (e) { }
  5594. return shadow(this, 'isEnabled', enabled);
  5595. },
  5596. composeSMask: composeSMask,
  5597. drawFigures: drawFigures,
  5598. clear: cleanup
  5599. };
  5600. })();
  5601. exports.WebGLUtils = WebGLUtils;
  5602. }));
  5603. (function (root, factory) {
  5604. {
  5605. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5606. root.pdfjsDisplayWebGL);
  5607. }
  5608. }(this, function (exports, sharedUtil, displayWebGL) {
  5609. var Util = sharedUtil.Util;
  5610. var info = sharedUtil.info;
  5611. var isArray = sharedUtil.isArray;
  5612. var error = sharedUtil.error;
  5613. var WebGLUtils = displayWebGL.WebGLUtils;
  5614. var ShadingIRs = {};
  5615. ShadingIRs.RadialAxial = {
  5616. fromIR: function RadialAxial_fromIR(raw) {
  5617. var type = raw[1];
  5618. var colorStops = raw[2];
  5619. var p0 = raw[3];
  5620. var p1 = raw[4];
  5621. var r0 = raw[5];
  5622. var r1 = raw[6];
  5623. return {
  5624. type: 'Pattern',
  5625. getPattern: function RadialAxial_getPattern(ctx) {
  5626. var grad;
  5627. if (type === 'axial') {
  5628. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5629. } else if (type === 'radial') {
  5630. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5631. }
  5632. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5633. var c = colorStops[i];
  5634. grad.addColorStop(c[0], c[1]);
  5635. }
  5636. return grad;
  5637. }
  5638. };
  5639. }
  5640. };
  5641. var createMeshCanvas = (function createMeshCanvasClosure() {
  5642. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5643. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5644. var coords = context.coords, colors = context.colors;
  5645. var bytes = data.data, rowSize = data.width * 4;
  5646. var tmp;
  5647. if (coords[p1 + 1] > coords[p2 + 1]) {
  5648. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5649. }
  5650. if (coords[p2 + 1] > coords[p3 + 1]) {
  5651. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5652. }
  5653. if (coords[p1 + 1] > coords[p2 + 1]) {
  5654. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5655. }
  5656. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5657. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5658. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5659. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5660. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5661. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5662. if (y1 >= y3) {
  5663. return;
  5664. }
  5665. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5666. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5667. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5668. var minY = Math.round(y1), maxY = Math.round(y3);
  5669. var xa, car, cag, cab;
  5670. var xb, cbr, cbg, cbb;
  5671. var k;
  5672. for (var y = minY; y <= maxY; y++) {
  5673. if (y < y2) {
  5674. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5675. xa = x1 - (x1 - x2) * k;
  5676. car = c1r - (c1r - c2r) * k;
  5677. cag = c1g - (c1g - c2g) * k;
  5678. cab = c1b - (c1b - c2b) * k;
  5679. } else {
  5680. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5681. xa = x2 - (x2 - x3) * k;
  5682. car = c2r - (c2r - c3r) * k;
  5683. cag = c2g - (c2g - c3g) * k;
  5684. cab = c2b - (c2b - c3b) * k;
  5685. }
  5686. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5687. xb = x1 - (x1 - x3) * k;
  5688. cbr = c1r - (c1r - c3r) * k;
  5689. cbg = c1g - (c1g - c3g) * k;
  5690. cbb = c1b - (c1b - c3b) * k;
  5691. var x1_ = Math.round(Math.min(xa, xb));
  5692. var x2_ = Math.round(Math.max(xa, xb));
  5693. var j = rowSize * y + x1_ * 4;
  5694. for (var x = x1_; x <= x2_; x++) {
  5695. k = (xa - x) / (xa - xb);
  5696. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5697. bytes[j++] = (car - (car - cbr) * k) | 0;
  5698. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5699. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5700. bytes[j++] = 255;
  5701. }
  5702. }
  5703. }
  5704. function drawFigure(data, figure, context) {
  5705. var ps = figure.coords;
  5706. var cs = figure.colors;
  5707. var i, ii;
  5708. switch (figure.type) {
  5709. case 'lattice':
  5710. var verticesPerRow = figure.verticesPerRow;
  5711. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5712. var cols = verticesPerRow - 1;
  5713. for (i = 0; i < rows; i++) {
  5714. var q = i * verticesPerRow;
  5715. for (var j = 0; j < cols; j++, q++) {
  5716. drawTriangle(data, context,
  5717. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5718. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5719. drawTriangle(data, context,
  5720. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5721. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5722. }
  5723. }
  5724. break;
  5725. case 'triangles':
  5726. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5727. drawTriangle(data, context,
  5728. ps[i], ps[i + 1], ps[i + 2],
  5729. cs[i], cs[i + 1], cs[i + 2]);
  5730. }
  5731. break;
  5732. default:
  5733. error('illigal figure');
  5734. break;
  5735. }
  5736. }
  5737. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5738. backgroundColor, cachedCanvases) {
  5739. // we will increase scale on some weird factor to let antialiasing take
  5740. // care of "rough" edges
  5741. var EXPECTED_SCALE = 1.1;
  5742. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5743. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5744. // We need to keep transparent border around our pattern for fill():
  5745. // createPattern with 'no-repeat' will bleed edges across entire area.
  5746. var BORDER_SIZE = 2;
  5747. var offsetX = Math.floor(bounds[0]);
  5748. var offsetY = Math.floor(bounds[1]);
  5749. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5750. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5751. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5752. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5753. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5754. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5755. var scaleX = boundsWidth / width;
  5756. var scaleY = boundsHeight / height;
  5757. var context = {
  5758. coords: coords,
  5759. colors: colors,
  5760. offsetX: -offsetX,
  5761. offsetY: -offsetY,
  5762. scaleX: 1 / scaleX,
  5763. scaleY: 1 / scaleY
  5764. };
  5765. var paddedWidth = width + BORDER_SIZE * 2;
  5766. var paddedHeight = height + BORDER_SIZE * 2;
  5767. var canvas, tmpCanvas, i, ii;
  5768. if (WebGLUtils.isEnabled) {
  5769. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5770. figures, context);
  5771. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5772. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5773. false);
  5774. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5775. canvas = tmpCanvas.canvas;
  5776. } else {
  5777. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5778. false);
  5779. var tmpCtx = tmpCanvas.context;
  5780. var data = tmpCtx.createImageData(width, height);
  5781. if (backgroundColor) {
  5782. var bytes = data.data;
  5783. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5784. bytes[i] = backgroundColor[0];
  5785. bytes[i + 1] = backgroundColor[1];
  5786. bytes[i + 2] = backgroundColor[2];
  5787. bytes[i + 3] = 255;
  5788. }
  5789. }
  5790. for (i = 0; i < figures.length; i++) {
  5791. drawFigure(data, figures[i], context);
  5792. }
  5793. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5794. canvas = tmpCanvas.canvas;
  5795. }
  5796. return {canvas: canvas,
  5797. offsetX: offsetX - BORDER_SIZE * scaleX,
  5798. offsetY: offsetY - BORDER_SIZE * scaleY,
  5799. scaleX: scaleX, scaleY: scaleY};
  5800. }
  5801. return createMeshCanvas;
  5802. })();
  5803. ShadingIRs.Mesh = {
  5804. fromIR: function Mesh_fromIR(raw) {
  5805. //var type = raw[1];
  5806. var coords = raw[2];
  5807. var colors = raw[3];
  5808. var figures = raw[4];
  5809. var bounds = raw[5];
  5810. var matrix = raw[6];
  5811. //var bbox = raw[7];
  5812. var background = raw[8];
  5813. return {
  5814. type: 'Pattern',
  5815. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5816. var scale;
  5817. if (shadingFill) {
  5818. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5819. } else {
  5820. // Obtain scale from matrix and current transformation matrix.
  5821. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5822. if (matrix) {
  5823. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5824. scale = [scale[0] * matrixScale[0],
  5825. scale[1] * matrixScale[1]];
  5826. }
  5827. }
  5828. // Rasterizing on the main thread since sending/queue large canvases
  5829. // might cause OOM.
  5830. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5831. colors, figures, shadingFill ? null : background,
  5832. owner.cachedCanvases);
  5833. if (!shadingFill) {
  5834. ctx.setTransform.apply(ctx, owner.baseTransform);
  5835. if (matrix) {
  5836. ctx.transform.apply(ctx, matrix);
  5837. }
  5838. }
  5839. ctx.translate(temporaryPatternCanvas.offsetX,
  5840. temporaryPatternCanvas.offsetY);
  5841. ctx.scale(temporaryPatternCanvas.scaleX,
  5842. temporaryPatternCanvas.scaleY);
  5843. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5844. }
  5845. };
  5846. }
  5847. };
  5848. ShadingIRs.Dummy = {
  5849. fromIR: function Dummy_fromIR() {
  5850. return {
  5851. type: 'Pattern',
  5852. getPattern: function Dummy_fromIR_getPattern() {
  5853. return 'hotpink';
  5854. }
  5855. };
  5856. }
  5857. };
  5858. function getShadingPatternFromIR(raw) {
  5859. var shadingIR = ShadingIRs[raw[0]];
  5860. if (!shadingIR) {
  5861. error('Unknown IR type: ' + raw[0]);
  5862. }
  5863. return shadingIR.fromIR(raw);
  5864. }
  5865. var TilingPattern = (function TilingPatternClosure() {
  5866. var PaintType = {
  5867. COLORED: 1,
  5868. UNCOLORED: 2
  5869. };
  5870. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5871. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5872. this.operatorList = IR[2];
  5873. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5874. this.bbox = IR[4];
  5875. this.xstep = IR[5];
  5876. this.ystep = IR[6];
  5877. this.paintType = IR[7];
  5878. this.tilingType = IR[8];
  5879. this.color = color;
  5880. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5881. this.baseTransform = baseTransform;
  5882. this.type = 'Pattern';
  5883. this.ctx = ctx;
  5884. }
  5885. TilingPattern.prototype = {
  5886. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5887. var operatorList = this.operatorList;
  5888. var bbox = this.bbox;
  5889. var xstep = this.xstep;
  5890. var ystep = this.ystep;
  5891. var paintType = this.paintType;
  5892. var tilingType = this.tilingType;
  5893. var color = this.color;
  5894. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5895. info('TilingType: ' + tilingType);
  5896. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5897. var topLeft = [x0, y0];
  5898. // we want the canvas to be as large as the step size
  5899. var botRight = [x0 + xstep, y0 + ystep];
  5900. var width = botRight[0] - topLeft[0];
  5901. var height = botRight[1] - topLeft[1];
  5902. // Obtain scale from matrix and current transformation matrix.
  5903. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5904. var curMatrixScale = Util.singularValueDecompose2dScale(
  5905. this.baseTransform);
  5906. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5907. matrixScale[1] * curMatrixScale[1]];
  5908. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5909. // Use width and height values that are as close as possible to the end
  5910. // result when the pattern is used. Too low value makes the pattern look
  5911. // blurry. Too large value makes it look too crispy.
  5912. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5913. MAX_PATTERN_SIZE);
  5914. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5915. MAX_PATTERN_SIZE);
  5916. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5917. width, height, true);
  5918. var tmpCtx = tmpCanvas.context;
  5919. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5920. graphics.groupLevel = owner.groupLevel;
  5921. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5922. this.setScale(width, height, xstep, ystep);
  5923. this.transformToScale(graphics);
  5924. // transform coordinates to pattern space
  5925. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5926. graphics.transform.apply(graphics, tmpTranslate);
  5927. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5928. graphics.executeOperatorList(operatorList);
  5929. return tmpCanvas.canvas;
  5930. },
  5931. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5932. this.scale = [width / xstep, height / ystep];
  5933. },
  5934. transformToScale: function TilingPattern_transformToScale(graphics) {
  5935. var scale = this.scale;
  5936. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5937. graphics.transform.apply(graphics, tmpScale);
  5938. },
  5939. scaleToContext: function TilingPattern_scaleToContext() {
  5940. var scale = this.scale;
  5941. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5942. },
  5943. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5944. if (bbox && isArray(bbox) && bbox.length === 4) {
  5945. var bboxWidth = x1 - x0;
  5946. var bboxHeight = y1 - y0;
  5947. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5948. graphics.clip();
  5949. graphics.endPath();
  5950. }
  5951. },
  5952. setFillAndStrokeStyleToContext:
  5953. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5954. switch (paintType) {
  5955. case PaintType.COLORED:
  5956. var ctx = this.ctx;
  5957. context.fillStyle = ctx.fillStyle;
  5958. context.strokeStyle = ctx.strokeStyle;
  5959. break;
  5960. case PaintType.UNCOLORED:
  5961. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5962. context.fillStyle = cssColor;
  5963. context.strokeStyle = cssColor;
  5964. break;
  5965. default:
  5966. error('Unsupported paint type: ' + paintType);
  5967. }
  5968. },
  5969. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5970. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5971. ctx = this.ctx;
  5972. ctx.setTransform.apply(ctx, this.baseTransform);
  5973. ctx.transform.apply(ctx, this.matrix);
  5974. this.scaleToContext();
  5975. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5976. }
  5977. };
  5978. return TilingPattern;
  5979. })();
  5980. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  5981. exports.TilingPattern = TilingPattern;
  5982. }));
  5983. (function (root, factory) {
  5984. {
  5985. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  5986. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  5987. root.pdfjsDisplayWebGL);
  5988. }
  5989. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  5990. displayWebGL) {
  5991. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  5992. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  5993. var ImageKind = sharedUtil.ImageKind;
  5994. var OPS = sharedUtil.OPS;
  5995. var TextRenderingMode = sharedUtil.TextRenderingMode;
  5996. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  5997. var Util = sharedUtil.Util;
  5998. var assert = sharedUtil.assert;
  5999. var info = sharedUtil.info;
  6000. var isNum = sharedUtil.isNum;
  6001. var isArray = sharedUtil.isArray;
  6002. var isLittleEndian = sharedUtil.isLittleEndian;
  6003. var error = sharedUtil.error;
  6004. var shadow = sharedUtil.shadow;
  6005. var warn = sharedUtil.warn;
  6006. var TilingPattern = displayPatternHelper.TilingPattern;
  6007. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6008. var WebGLUtils = displayWebGL.WebGLUtils;
  6009. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6010. // <canvas> contexts store most of the state we need natively.
  6011. // However, PDF needs a bit more state, which we store here.
  6012. // Minimal font size that would be used during canvas fillText operations.
  6013. var MIN_FONT_SIZE = 16;
  6014. // Maximum font size that would be used during canvas fillText operations.
  6015. var MAX_FONT_SIZE = 100;
  6016. var MAX_GROUP_SIZE = 4096;
  6017. // Heuristic value used when enforcing minimum line widths.
  6018. var MIN_WIDTH_FACTOR = 0.65;
  6019. var COMPILE_TYPE3_GLYPHS = true;
  6020. var MAX_SIZE_TO_COMPILE = 1000;
  6021. var FULL_CHUNK_HEIGHT = 16;
  6022. var HasCanvasTypedArraysCached = {
  6023. get value() {
  6024. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6025. }
  6026. };
  6027. var IsLittleEndianCached = {
  6028. get value() {
  6029. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6030. }
  6031. };
  6032. function createScratchCanvas(width, height) {
  6033. var canvas = document.createElement('canvas');
  6034. canvas.width = width;
  6035. canvas.height = height;
  6036. return canvas;
  6037. }
  6038. function addContextCurrentTransform(ctx) {
  6039. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6040. if (!ctx.mozCurrentTransform) {
  6041. ctx._originalSave = ctx.save;
  6042. ctx._originalRestore = ctx.restore;
  6043. ctx._originalRotate = ctx.rotate;
  6044. ctx._originalScale = ctx.scale;
  6045. ctx._originalTranslate = ctx.translate;
  6046. ctx._originalTransform = ctx.transform;
  6047. ctx._originalSetTransform = ctx.setTransform;
  6048. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6049. ctx._transformStack = [];
  6050. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6051. get: function getCurrentTransform() {
  6052. return this._transformMatrix;
  6053. }
  6054. });
  6055. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6056. get: function getCurrentTransformInverse() {
  6057. // Calculation done using WolframAlpha:
  6058. // http://www.wolframalpha.com/input/?
  6059. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6060. var m = this._transformMatrix;
  6061. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6062. var ad_bc = a * d - b * c;
  6063. var bc_ad = b * c - a * d;
  6064. return [
  6065. d / ad_bc,
  6066. b / bc_ad,
  6067. c / bc_ad,
  6068. a / ad_bc,
  6069. (d * e - c * f) / bc_ad,
  6070. (b * e - a * f) / ad_bc
  6071. ];
  6072. }
  6073. });
  6074. ctx.save = function ctxSave() {
  6075. var old = this._transformMatrix;
  6076. this._transformStack.push(old);
  6077. this._transformMatrix = old.slice(0, 6);
  6078. this._originalSave();
  6079. };
  6080. ctx.restore = function ctxRestore() {
  6081. var prev = this._transformStack.pop();
  6082. if (prev) {
  6083. this._transformMatrix = prev;
  6084. this._originalRestore();
  6085. }
  6086. };
  6087. ctx.translate = function ctxTranslate(x, y) {
  6088. var m = this._transformMatrix;
  6089. m[4] = m[0] * x + m[2] * y + m[4];
  6090. m[5] = m[1] * x + m[3] * y + m[5];
  6091. this._originalTranslate(x, y);
  6092. };
  6093. ctx.scale = function ctxScale(x, y) {
  6094. var m = this._transformMatrix;
  6095. m[0] = m[0] * x;
  6096. m[1] = m[1] * x;
  6097. m[2] = m[2] * y;
  6098. m[3] = m[3] * y;
  6099. this._originalScale(x, y);
  6100. };
  6101. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6102. var m = this._transformMatrix;
  6103. this._transformMatrix = [
  6104. m[0] * a + m[2] * b,
  6105. m[1] * a + m[3] * b,
  6106. m[0] * c + m[2] * d,
  6107. m[1] * c + m[3] * d,
  6108. m[0] * e + m[2] * f + m[4],
  6109. m[1] * e + m[3] * f + m[5]
  6110. ];
  6111. ctx._originalTransform(a, b, c, d, e, f);
  6112. };
  6113. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6114. this._transformMatrix = [a, b, c, d, e, f];
  6115. ctx._originalSetTransform(a, b, c, d, e, f);
  6116. };
  6117. ctx.rotate = function ctxRotate(angle) {
  6118. var cosValue = Math.cos(angle);
  6119. var sinValue = Math.sin(angle);
  6120. var m = this._transformMatrix;
  6121. this._transformMatrix = [
  6122. m[0] * cosValue + m[2] * sinValue,
  6123. m[1] * cosValue + m[3] * sinValue,
  6124. m[0] * (-sinValue) + m[2] * cosValue,
  6125. m[1] * (-sinValue) + m[3] * cosValue,
  6126. m[4],
  6127. m[5]
  6128. ];
  6129. this._originalRotate(angle);
  6130. };
  6131. }
  6132. }
  6133. var CachedCanvases = (function CachedCanvasesClosure() {
  6134. function CachedCanvases() {
  6135. this.cache = Object.create(null);
  6136. }
  6137. CachedCanvases.prototype = {
  6138. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6139. trackTransform) {
  6140. var canvasEntry;
  6141. if (this.cache[id] !== undefined) {
  6142. canvasEntry = this.cache[id];
  6143. canvasEntry.canvas.width = width;
  6144. canvasEntry.canvas.height = height;
  6145. // reset canvas transform for emulated mozCurrentTransform, if needed
  6146. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6147. } else {
  6148. var canvas = createScratchCanvas(width, height);
  6149. var ctx = canvas.getContext('2d');
  6150. if (trackTransform) {
  6151. addContextCurrentTransform(ctx);
  6152. }
  6153. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6154. }
  6155. return canvasEntry;
  6156. },
  6157. clear: function () {
  6158. for (var id in this.cache) {
  6159. var canvasEntry = this.cache[id];
  6160. // Zeroing the width and height causes Firefox to release graphics
  6161. // resources immediately, which can greatly reduce memory consumption.
  6162. canvasEntry.canvas.width = 0;
  6163. canvasEntry.canvas.height = 0;
  6164. delete this.cache[id];
  6165. }
  6166. }
  6167. };
  6168. return CachedCanvases;
  6169. })();
  6170. function compileType3Glyph(imgData) {
  6171. var POINT_TO_PROCESS_LIMIT = 1000;
  6172. var width = imgData.width, height = imgData.height;
  6173. var i, j, j0, width1 = width + 1;
  6174. var points = new Uint8Array(width1 * (height + 1));
  6175. var POINT_TYPES =
  6176. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6177. // decodes bit-packed mask data
  6178. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6179. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6180. for (i = 0, ii = data0.length; i < ii; i++) {
  6181. var mask = 128, elem = data0[i];
  6182. while (mask > 0) {
  6183. data[pos++] = (elem & mask) ? 0 : 255;
  6184. mask >>= 1;
  6185. }
  6186. }
  6187. // finding iteresting points: every point is located between mask pixels,
  6188. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6189. // will have flags assigned based on neighboring mask pixels:
  6190. // 4 | 8
  6191. // --P--
  6192. // 2 | 1
  6193. // We are interested only in points with the flags:
  6194. // - outside corners: 1, 2, 4, 8;
  6195. // - inside corners: 7, 11, 13, 14;
  6196. // - and, intersections: 5, 10.
  6197. var count = 0;
  6198. pos = 0;
  6199. if (data[pos] !== 0) {
  6200. points[0] = 1;
  6201. ++count;
  6202. }
  6203. for (j = 1; j < width; j++) {
  6204. if (data[pos] !== data[pos + 1]) {
  6205. points[j] = data[pos] ? 2 : 1;
  6206. ++count;
  6207. }
  6208. pos++;
  6209. }
  6210. if (data[pos] !== 0) {
  6211. points[j] = 2;
  6212. ++count;
  6213. }
  6214. for (i = 1; i < height; i++) {
  6215. pos = i * lineSize;
  6216. j0 = i * width1;
  6217. if (data[pos - lineSize] !== data[pos]) {
  6218. points[j0] = data[pos] ? 1 : 8;
  6219. ++count;
  6220. }
  6221. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6222. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6223. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6224. for (j = 1; j < width; j++) {
  6225. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6226. (data[pos - lineSize + 1] ? 8 : 0);
  6227. if (POINT_TYPES[sum]) {
  6228. points[j0 + j] = POINT_TYPES[sum];
  6229. ++count;
  6230. }
  6231. pos++;
  6232. }
  6233. if (data[pos - lineSize] !== data[pos]) {
  6234. points[j0 + j] = data[pos] ? 2 : 4;
  6235. ++count;
  6236. }
  6237. if (count > POINT_TO_PROCESS_LIMIT) {
  6238. return null;
  6239. }
  6240. }
  6241. pos = lineSize * (height - 1);
  6242. j0 = i * width1;
  6243. if (data[pos] !== 0) {
  6244. points[j0] = 8;
  6245. ++count;
  6246. }
  6247. for (j = 1; j < width; j++) {
  6248. if (data[pos] !== data[pos + 1]) {
  6249. points[j0 + j] = data[pos] ? 4 : 8;
  6250. ++count;
  6251. }
  6252. pos++;
  6253. }
  6254. if (data[pos] !== 0) {
  6255. points[j0 + j] = 4;
  6256. ++count;
  6257. }
  6258. if (count > POINT_TO_PROCESS_LIMIT) {
  6259. return null;
  6260. }
  6261. // building outlines
  6262. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6263. var outlines = [];
  6264. for (i = 0; count && i <= height; i++) {
  6265. var p = i * width1;
  6266. var end = p + width;
  6267. while (p < end && !points[p]) {
  6268. p++;
  6269. }
  6270. if (p === end) {
  6271. continue;
  6272. }
  6273. var coords = [p % width1, i];
  6274. var type = points[p], p0 = p, pp;
  6275. do {
  6276. var step = steps[type];
  6277. do {
  6278. p += step;
  6279. } while (!points[p]);
  6280. pp = points[p];
  6281. if (pp !== 5 && pp !== 10) {
  6282. // set new direction
  6283. type = pp;
  6284. // delete mark
  6285. points[p] = 0;
  6286. } else { // type is 5 or 10, ie, a crossing
  6287. // set new direction
  6288. type = pp & ((0x33 * type) >> 4);
  6289. // set new type for "future hit"
  6290. points[p] &= (type >> 2 | type << 2);
  6291. }
  6292. coords.push(p % width1);
  6293. coords.push((p / width1) | 0);
  6294. --count;
  6295. } while (p0 !== p);
  6296. outlines.push(coords);
  6297. --i;
  6298. }
  6299. var drawOutline = function(c) {
  6300. c.save();
  6301. // the path shall be painted in [0..1]x[0..1] space
  6302. c.scale(1 / width, -1 / height);
  6303. c.translate(0, -height);
  6304. c.beginPath();
  6305. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6306. var o = outlines[i];
  6307. c.moveTo(o[0], o[1]);
  6308. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6309. c.lineTo(o[j], o[j+1]);
  6310. }
  6311. }
  6312. c.fill();
  6313. c.beginPath();
  6314. c.restore();
  6315. };
  6316. return drawOutline;
  6317. }
  6318. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6319. function CanvasExtraState(old) {
  6320. // Are soft masks and alpha values shapes or opacities?
  6321. this.alphaIsShape = false;
  6322. this.fontSize = 0;
  6323. this.fontSizeScale = 1;
  6324. this.textMatrix = IDENTITY_MATRIX;
  6325. this.textMatrixScale = 1;
  6326. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6327. this.leading = 0;
  6328. // Current point (in user coordinates)
  6329. this.x = 0;
  6330. this.y = 0;
  6331. // Start of text line (in text coordinates)
  6332. this.lineX = 0;
  6333. this.lineY = 0;
  6334. // Character and word spacing
  6335. this.charSpacing = 0;
  6336. this.wordSpacing = 0;
  6337. this.textHScale = 1;
  6338. this.textRenderingMode = TextRenderingMode.FILL;
  6339. this.textRise = 0;
  6340. // Default fore and background colors
  6341. this.fillColor = '#000000';
  6342. this.strokeColor = '#000000';
  6343. this.patternFill = false;
  6344. // Note: fill alpha applies to all non-stroking operations
  6345. this.fillAlpha = 1;
  6346. this.strokeAlpha = 1;
  6347. this.lineWidth = 1;
  6348. this.activeSMask = null;
  6349. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6350. this.old = old;
  6351. }
  6352. CanvasExtraState.prototype = {
  6353. clone: function CanvasExtraState_clone() {
  6354. return Object.create(this);
  6355. },
  6356. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6357. this.x = x;
  6358. this.y = y;
  6359. }
  6360. };
  6361. return CanvasExtraState;
  6362. })();
  6363. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6364. // Defines the time the executeOperatorList is going to be executing
  6365. // before it stops and shedules a continue of execution.
  6366. var EXECUTION_TIME = 15;
  6367. // Defines the number of steps before checking the execution time
  6368. var EXECUTION_STEPS = 10;
  6369. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6370. this.ctx = canvasCtx;
  6371. this.current = new CanvasExtraState();
  6372. this.stateStack = [];
  6373. this.pendingClip = null;
  6374. this.pendingEOFill = false;
  6375. this.res = null;
  6376. this.xobjs = null;
  6377. this.commonObjs = commonObjs;
  6378. this.objs = objs;
  6379. this.imageLayer = imageLayer;
  6380. this.groupStack = [];
  6381. this.processingType3 = null;
  6382. // Patterns are painted relative to the initial page/form transform, see pdf
  6383. // spec 8.7.2 NOTE 1.
  6384. this.baseTransform = null;
  6385. this.baseTransformStack = [];
  6386. this.groupLevel = 0;
  6387. this.smaskStack = [];
  6388. this.smaskCounter = 0;
  6389. this.tempSMask = null;
  6390. this.cachedCanvases = new CachedCanvases();
  6391. if (canvasCtx) {
  6392. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6393. // the transformation must already be set in canvasCtx._transformMatrix.
  6394. addContextCurrentTransform(canvasCtx);
  6395. }
  6396. this.cachedGetSinglePixelWidth = null;
  6397. }
  6398. function putBinaryImageData(ctx, imgData) {
  6399. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6400. ctx.putImageData(imgData, 0, 0);
  6401. return;
  6402. }
  6403. // Put the image data to the canvas in chunks, rather than putting the
  6404. // whole image at once. This saves JS memory, because the ImageData object
  6405. // is smaller. It also possibly saves C++ memory within the implementation
  6406. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6407. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6408. // because too many putImageData() calls will slow things down.
  6409. //
  6410. // Note: as written, if the last chunk is partial, the putImageData() call
  6411. // will (conceptually) put pixels past the bounds of the canvas. But
  6412. // that's ok; any such pixels are ignored.
  6413. var height = imgData.height, width = imgData.width;
  6414. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6415. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6416. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6417. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6418. var srcPos = 0, destPos;
  6419. var src = imgData.data;
  6420. var dest = chunkImgData.data;
  6421. var i, j, thisChunkHeight, elemsInThisChunk;
  6422. // There are multiple forms in which the pixel data can be passed, and
  6423. // imgData.kind tells us which one this is.
  6424. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6425. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6426. var srcLength = src.byteLength;
  6427. var dest32 = HasCanvasTypedArraysCached.value ?
  6428. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6429. var dest32DataLength = dest32.length;
  6430. var fullSrcDiff = (width + 7) >> 3;
  6431. var white = 0xFFFFFFFF;
  6432. var black = (IsLittleEndianCached.value ||
  6433. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6434. for (i = 0; i < totalChunks; i++) {
  6435. thisChunkHeight =
  6436. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6437. destPos = 0;
  6438. for (j = 0; j < thisChunkHeight; j++) {
  6439. var srcDiff = srcLength - srcPos;
  6440. var k = 0;
  6441. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6442. var kEndUnrolled = kEnd & ~7;
  6443. var mask = 0;
  6444. var srcByte = 0;
  6445. for (; k < kEndUnrolled; k += 8) {
  6446. srcByte = src[srcPos++];
  6447. dest32[destPos++] = (srcByte & 128) ? white : black;
  6448. dest32[destPos++] = (srcByte & 64) ? white : black;
  6449. dest32[destPos++] = (srcByte & 32) ? white : black;
  6450. dest32[destPos++] = (srcByte & 16) ? white : black;
  6451. dest32[destPos++] = (srcByte & 8) ? white : black;
  6452. dest32[destPos++] = (srcByte & 4) ? white : black;
  6453. dest32[destPos++] = (srcByte & 2) ? white : black;
  6454. dest32[destPos++] = (srcByte & 1) ? white : black;
  6455. }
  6456. for (; k < kEnd; k++) {
  6457. if (mask === 0) {
  6458. srcByte = src[srcPos++];
  6459. mask = 128;
  6460. }
  6461. dest32[destPos++] = (srcByte & mask) ? white : black;
  6462. mask >>= 1;
  6463. }
  6464. }
  6465. // We ran out of input. Make all remaining pixels transparent.
  6466. while (destPos < dest32DataLength) {
  6467. dest32[destPos++] = 0;
  6468. }
  6469. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6470. }
  6471. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6472. // RGBA, 32-bits per pixel.
  6473. j = 0;
  6474. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6475. for (i = 0; i < fullChunks; i++) {
  6476. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6477. srcPos += elemsInThisChunk;
  6478. ctx.putImageData(chunkImgData, 0, j);
  6479. j += FULL_CHUNK_HEIGHT;
  6480. }
  6481. if (i < totalChunks) {
  6482. elemsInThisChunk = width * partialChunkHeight * 4;
  6483. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6484. ctx.putImageData(chunkImgData, 0, j);
  6485. }
  6486. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6487. // RGB, 24-bits per pixel.
  6488. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6489. elemsInThisChunk = width * thisChunkHeight;
  6490. for (i = 0; i < totalChunks; i++) {
  6491. if (i >= fullChunks) {
  6492. thisChunkHeight = partialChunkHeight;
  6493. elemsInThisChunk = width * thisChunkHeight;
  6494. }
  6495. destPos = 0;
  6496. for (j = elemsInThisChunk; j--;) {
  6497. dest[destPos++] = src[srcPos++];
  6498. dest[destPos++] = src[srcPos++];
  6499. dest[destPos++] = src[srcPos++];
  6500. dest[destPos++] = 255;
  6501. }
  6502. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6503. }
  6504. } else {
  6505. error('bad image kind: ' + imgData.kind);
  6506. }
  6507. }
  6508. function putBinaryImageMask(ctx, imgData) {
  6509. var height = imgData.height, width = imgData.width;
  6510. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6511. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6512. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6513. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6514. var srcPos = 0;
  6515. var src = imgData.data;
  6516. var dest = chunkImgData.data;
  6517. for (var i = 0; i < totalChunks; i++) {
  6518. var thisChunkHeight =
  6519. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6520. // Expand the mask so it can be used by the canvas. Any required
  6521. // inversion has already been handled.
  6522. var destPos = 3; // alpha component offset
  6523. for (var j = 0; j < thisChunkHeight; j++) {
  6524. var mask = 0;
  6525. for (var k = 0; k < width; k++) {
  6526. if (!mask) {
  6527. var elem = src[srcPos++];
  6528. mask = 128;
  6529. }
  6530. dest[destPos] = (elem & mask) ? 0 : 255;
  6531. destPos += 4;
  6532. mask >>= 1;
  6533. }
  6534. }
  6535. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6536. }
  6537. }
  6538. function copyCtxState(sourceCtx, destCtx) {
  6539. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6540. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6541. 'globalCompositeOperation', 'font'];
  6542. for (var i = 0, ii = properties.length; i < ii; i++) {
  6543. var property = properties[i];
  6544. if (sourceCtx[property] !== undefined) {
  6545. destCtx[property] = sourceCtx[property];
  6546. }
  6547. }
  6548. if (sourceCtx.setLineDash !== undefined) {
  6549. destCtx.setLineDash(sourceCtx.getLineDash());
  6550. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6551. } else if (sourceCtx.mozDashOffset !== undefined) {
  6552. destCtx.mozDash = sourceCtx.mozDash;
  6553. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  6554. }
  6555. }
  6556. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6557. var length = bytes.length;
  6558. for (var i = 3; i < length; i += 4) {
  6559. var alpha = bytes[i];
  6560. if (alpha === 0) {
  6561. bytes[i - 3] = r0;
  6562. bytes[i - 2] = g0;
  6563. bytes[i - 1] = b0;
  6564. } else if (alpha < 255) {
  6565. var alpha_ = 255 - alpha;
  6566. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6567. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6568. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6569. }
  6570. }
  6571. }
  6572. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6573. var length = maskData.length;
  6574. var scale = 1 / 255;
  6575. for (var i = 3; i < length; i += 4) {
  6576. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6577. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6578. }
  6579. }
  6580. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6581. var length = maskData.length;
  6582. for (var i = 3; i < length; i += 4) {
  6583. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6584. (maskData[i - 2] * 152) + // * 0.59 ....
  6585. (maskData[i - 1] * 28); // * 0.11 ....
  6586. layerData[i] = transferMap ?
  6587. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6588. (layerData[i] * y) >> 16;
  6589. }
  6590. }
  6591. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6592. subtype, backdrop, transferMap) {
  6593. var hasBackdrop = !!backdrop;
  6594. var r0 = hasBackdrop ? backdrop[0] : 0;
  6595. var g0 = hasBackdrop ? backdrop[1] : 0;
  6596. var b0 = hasBackdrop ? backdrop[2] : 0;
  6597. var composeFn;
  6598. if (subtype === 'Luminosity') {
  6599. composeFn = composeSMaskLuminosity;
  6600. } else {
  6601. composeFn = composeSMaskAlpha;
  6602. }
  6603. // processing image in chunks to save memory
  6604. var PIXELS_TO_PROCESS = 1048576;
  6605. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6606. for (var row = 0; row < height; row += chunkSize) {
  6607. var chunkHeight = Math.min(chunkSize, height - row);
  6608. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6609. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6610. if (hasBackdrop) {
  6611. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6612. }
  6613. composeFn(maskData.data, layerData.data, transferMap);
  6614. maskCtx.putImageData(layerData, 0, row);
  6615. }
  6616. }
  6617. function composeSMask(ctx, smask, layerCtx) {
  6618. var mask = smask.canvas;
  6619. var maskCtx = smask.context;
  6620. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6621. smask.offsetX, smask.offsetY);
  6622. var backdrop = smask.backdrop || null;
  6623. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6624. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6625. {subtype: smask.subtype, backdrop: backdrop});
  6626. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6627. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6628. return;
  6629. }
  6630. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6631. smask.subtype, backdrop, smask.transferMap);
  6632. ctx.drawImage(mask, 0, 0);
  6633. }
  6634. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6635. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6636. var NORMAL_CLIP = {};
  6637. var EO_CLIP = {};
  6638. CanvasGraphics.prototype = {
  6639. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6640. transparency) {
  6641. // For pdfs that use blend modes we have to clear the canvas else certain
  6642. // blend modes can look wrong since we'd be blending with a white
  6643. // backdrop. The problem with a transparent backdrop though is we then
  6644. // don't get sub pixel anti aliasing on text, creating temporary
  6645. // transparent canvas when we have blend modes.
  6646. var width = this.ctx.canvas.width;
  6647. var height = this.ctx.canvas.height;
  6648. this.ctx.save();
  6649. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6650. this.ctx.fillRect(0, 0, width, height);
  6651. this.ctx.restore();
  6652. if (transparency) {
  6653. var transparentCanvas = this.cachedCanvases.getCanvas(
  6654. 'transparent', width, height, true);
  6655. this.compositeCtx = this.ctx;
  6656. this.transparentCanvas = transparentCanvas.canvas;
  6657. this.ctx = transparentCanvas.context;
  6658. this.ctx.save();
  6659. // The transform can be applied before rendering, transferring it to
  6660. // the new canvas.
  6661. this.ctx.transform.apply(this.ctx,
  6662. this.compositeCtx.mozCurrentTransform);
  6663. }
  6664. this.ctx.save();
  6665. if (transform) {
  6666. this.ctx.transform.apply(this.ctx, transform);
  6667. }
  6668. this.ctx.transform.apply(this.ctx, viewport.transform);
  6669. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6670. if (this.imageLayer) {
  6671. this.imageLayer.beginLayout();
  6672. }
  6673. },
  6674. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6675. operatorList,
  6676. executionStartIdx, continueCallback,
  6677. stepper) {
  6678. var argsArray = operatorList.argsArray;
  6679. var fnArray = operatorList.fnArray;
  6680. var i = executionStartIdx || 0;
  6681. var argsArrayLen = argsArray.length;
  6682. // Sometimes the OperatorList to execute is empty.
  6683. if (argsArrayLen === i) {
  6684. return i;
  6685. }
  6686. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6687. typeof continueCallback === 'function');
  6688. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6689. var steps = 0;
  6690. var commonObjs = this.commonObjs;
  6691. var objs = this.objs;
  6692. var fnId;
  6693. while (true) {
  6694. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6695. stepper.breakIt(i, continueCallback);
  6696. return i;
  6697. }
  6698. fnId = fnArray[i];
  6699. if (fnId !== OPS.dependency) {
  6700. this[fnId].apply(this, argsArray[i]);
  6701. } else {
  6702. var deps = argsArray[i];
  6703. for (var n = 0, nn = deps.length; n < nn; n++) {
  6704. var depObjId = deps[n];
  6705. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6706. var objsPool = common ? commonObjs : objs;
  6707. // If the promise isn't resolved yet, add the continueCallback
  6708. // to the promise and bail out.
  6709. if (!objsPool.isResolved(depObjId)) {
  6710. objsPool.get(depObjId, continueCallback);
  6711. return i;
  6712. }
  6713. }
  6714. }
  6715. i++;
  6716. // If the entire operatorList was executed, stop as were done.
  6717. if (i === argsArrayLen) {
  6718. return i;
  6719. }
  6720. // If the execution took longer then a certain amount of time and
  6721. // `continueCallback` is specified, interrupt the execution.
  6722. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6723. if (Date.now() > endTime) {
  6724. continueCallback();
  6725. return i;
  6726. }
  6727. steps = 0;
  6728. }
  6729. // If the operatorList isn't executed completely yet OR the execution
  6730. // time was short enough, do another execution round.
  6731. }
  6732. },
  6733. endDrawing: function CanvasGraphics_endDrawing() {
  6734. // Finishing all opened operations such as SMask group painting.
  6735. if (this.current.activeSMask !== null) {
  6736. this.endSMaskGroup();
  6737. }
  6738. this.ctx.restore();
  6739. if (this.transparentCanvas) {
  6740. this.ctx = this.compositeCtx;
  6741. this.ctx.save();
  6742. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6743. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6744. this.ctx.restore();
  6745. this.transparentCanvas = null;
  6746. }
  6747. this.cachedCanvases.clear();
  6748. WebGLUtils.clear();
  6749. if (this.imageLayer) {
  6750. this.imageLayer.endLayout();
  6751. }
  6752. },
  6753. // Graphics state
  6754. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6755. this.current.lineWidth = width;
  6756. this.ctx.lineWidth = width;
  6757. },
  6758. setLineCap: function CanvasGraphics_setLineCap(style) {
  6759. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6760. },
  6761. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6762. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6763. },
  6764. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6765. this.ctx.miterLimit = limit;
  6766. },
  6767. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6768. var ctx = this.ctx;
  6769. if (ctx.setLineDash !== undefined) {
  6770. ctx.setLineDash(dashArray);
  6771. ctx.lineDashOffset = dashPhase;
  6772. } else {
  6773. ctx.mozDash = dashArray;
  6774. ctx.mozDashOffset = dashPhase;
  6775. }
  6776. },
  6777. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6778. // Maybe if we one day fully support color spaces this will be important
  6779. // for now we can ignore.
  6780. // TODO set rendering intent?
  6781. },
  6782. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6783. // There's no way to control this with canvas, but we can safely ignore.
  6784. // TODO set flatness?
  6785. },
  6786. setGState: function CanvasGraphics_setGState(states) {
  6787. for (var i = 0, ii = states.length; i < ii; i++) {
  6788. var state = states[i];
  6789. var key = state[0];
  6790. var value = state[1];
  6791. switch (key) {
  6792. case 'LW':
  6793. this.setLineWidth(value);
  6794. break;
  6795. case 'LC':
  6796. this.setLineCap(value);
  6797. break;
  6798. case 'LJ':
  6799. this.setLineJoin(value);
  6800. break;
  6801. case 'ML':
  6802. this.setMiterLimit(value);
  6803. break;
  6804. case 'D':
  6805. this.setDash(value[0], value[1]);
  6806. break;
  6807. case 'RI':
  6808. this.setRenderingIntent(value);
  6809. break;
  6810. case 'FL':
  6811. this.setFlatness(value);
  6812. break;
  6813. case 'Font':
  6814. this.setFont(value[0], value[1]);
  6815. break;
  6816. case 'CA':
  6817. this.current.strokeAlpha = state[1];
  6818. break;
  6819. case 'ca':
  6820. this.current.fillAlpha = state[1];
  6821. this.ctx.globalAlpha = state[1];
  6822. break;
  6823. case 'BM':
  6824. if (value && value.name && (value.name !== 'Normal')) {
  6825. var mode = value.name.replace(/([A-Z])/g,
  6826. function(c) {
  6827. return '-' + c.toLowerCase();
  6828. }
  6829. ).substring(1);
  6830. this.ctx.globalCompositeOperation = mode;
  6831. if (this.ctx.globalCompositeOperation !== mode) {
  6832. warn('globalCompositeOperation "' + mode +
  6833. '" is not supported');
  6834. }
  6835. } else {
  6836. this.ctx.globalCompositeOperation = 'source-over';
  6837. }
  6838. break;
  6839. case 'SMask':
  6840. if (this.current.activeSMask) {
  6841. // If SMask is currrenly used, it needs to be suspended or
  6842. // finished. Suspend only makes sense when at least one save()
  6843. // was performed and state needs to be reverted on restore().
  6844. if (this.stateStack.length > 0 &&
  6845. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6846. this.current.activeSMask)) {
  6847. this.suspendSMaskGroup();
  6848. } else {
  6849. this.endSMaskGroup();
  6850. }
  6851. }
  6852. this.current.activeSMask = value ? this.tempSMask : null;
  6853. if (this.current.activeSMask) {
  6854. this.beginSMaskGroup();
  6855. }
  6856. this.tempSMask = null;
  6857. break;
  6858. }
  6859. }
  6860. },
  6861. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6862. var activeSMask = this.current.activeSMask;
  6863. var drawnWidth = activeSMask.canvas.width;
  6864. var drawnHeight = activeSMask.canvas.height;
  6865. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6866. var scratchCanvas = this.cachedCanvases.getCanvas(
  6867. cacheId, drawnWidth, drawnHeight, true);
  6868. var currentCtx = this.ctx;
  6869. var currentTransform = currentCtx.mozCurrentTransform;
  6870. this.ctx.save();
  6871. var groupCtx = scratchCanvas.context;
  6872. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6873. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6874. groupCtx.transform.apply(groupCtx, currentTransform);
  6875. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6876. copyCtxState(currentCtx, groupCtx);
  6877. this.ctx = groupCtx;
  6878. this.setGState([
  6879. ['BM', 'Normal'],
  6880. ['ca', 1],
  6881. ['CA', 1]
  6882. ]);
  6883. this.groupStack.push(currentCtx);
  6884. this.groupLevel++;
  6885. },
  6886. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6887. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  6888. // and future ctx state restored.
  6889. var groupCtx = this.ctx;
  6890. this.groupLevel--;
  6891. this.ctx = this.groupStack.pop();
  6892. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6893. this.ctx.restore();
  6894. this.ctx.save(); // save is needed since SMask will be resumed.
  6895. copyCtxState(groupCtx, this.ctx);
  6896. // Saving state for resuming.
  6897. this.current.resumeSMaskCtx = groupCtx;
  6898. // Transform was changed in the SMask canvas, reflecting this change on
  6899. // this.ctx.
  6900. var deltaTransform = Util.transform(
  6901. this.current.activeSMask.startTransformInverse,
  6902. groupCtx.mozCurrentTransform);
  6903. this.ctx.transform.apply(this.ctx, deltaTransform);
  6904. // SMask was composed, the results at the groupCtx can be cleared.
  6905. groupCtx.save();
  6906. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  6907. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  6908. groupCtx.restore();
  6909. },
  6910. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6911. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  6912. // any groupCtx state since restore() command (the only caller) will do
  6913. // that for us. See also beginSMaskGroup.
  6914. var groupCtx = this.current.resumeSMaskCtx;
  6915. var currentCtx = this.ctx;
  6916. this.ctx = groupCtx;
  6917. this.groupStack.push(currentCtx);
  6918. this.groupLevel++;
  6919. },
  6920. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6921. var groupCtx = this.ctx;
  6922. this.groupLevel--;
  6923. this.ctx = this.groupStack.pop();
  6924. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6925. this.ctx.restore();
  6926. copyCtxState(groupCtx, this.ctx);
  6927. // Transform was changed in the SMask canvas, reflecting this change on
  6928. // this.ctx.
  6929. var deltaTransform = Util.transform(
  6930. this.current.activeSMask.startTransformInverse,
  6931. groupCtx.mozCurrentTransform);
  6932. this.ctx.transform.apply(this.ctx, deltaTransform);
  6933. },
  6934. save: function CanvasGraphics_save() {
  6935. this.ctx.save();
  6936. var old = this.current;
  6937. this.stateStack.push(old);
  6938. this.current = old.clone();
  6939. this.current.resumeSMaskCtx = null;
  6940. },
  6941. restore: function CanvasGraphics_restore() {
  6942. // SMask was suspended, we just need to resume it.
  6943. if (this.current.resumeSMaskCtx) {
  6944. this.resumeSMaskGroup();
  6945. }
  6946. // SMask has to be finished once there is no states that are using the
  6947. // same SMask.
  6948. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  6949. this.stateStack[this.stateStack.length - 1].activeSMask !==
  6950. this.current.activeSMask)) {
  6951. this.endSMaskGroup();
  6952. }
  6953. if (this.stateStack.length !== 0) {
  6954. this.current = this.stateStack.pop();
  6955. this.ctx.restore();
  6956. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  6957. this.pendingClip = null;
  6958. this.cachedGetSinglePixelWidth = null;
  6959. }
  6960. },
  6961. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  6962. this.ctx.transform(a, b, c, d, e, f);
  6963. this.cachedGetSinglePixelWidth = null;
  6964. },
  6965. // Path
  6966. constructPath: function CanvasGraphics_constructPath(ops, args) {
  6967. var ctx = this.ctx;
  6968. var current = this.current;
  6969. var x = current.x, y = current.y;
  6970. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6971. switch (ops[i] | 0) {
  6972. case OPS.rectangle:
  6973. x = args[j++];
  6974. y = args[j++];
  6975. var width = args[j++];
  6976. var height = args[j++];
  6977. if (width === 0) {
  6978. width = this.getSinglePixelWidth();
  6979. }
  6980. if (height === 0) {
  6981. height = this.getSinglePixelWidth();
  6982. }
  6983. var xw = x + width;
  6984. var yh = y + height;
  6985. this.ctx.moveTo(x, y);
  6986. this.ctx.lineTo(xw, y);
  6987. this.ctx.lineTo(xw, yh);
  6988. this.ctx.lineTo(x, yh);
  6989. this.ctx.lineTo(x, y);
  6990. this.ctx.closePath();
  6991. break;
  6992. case OPS.moveTo:
  6993. x = args[j++];
  6994. y = args[j++];
  6995. ctx.moveTo(x, y);
  6996. break;
  6997. case OPS.lineTo:
  6998. x = args[j++];
  6999. y = args[j++];
  7000. ctx.lineTo(x, y);
  7001. break;
  7002. case OPS.curveTo:
  7003. x = args[j + 4];
  7004. y = args[j + 5];
  7005. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  7006. x, y);
  7007. j += 6;
  7008. break;
  7009. case OPS.curveTo2:
  7010. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  7011. args[j + 2], args[j + 3]);
  7012. x = args[j + 2];
  7013. y = args[j + 3];
  7014. j += 4;
  7015. break;
  7016. case OPS.curveTo3:
  7017. x = args[j + 2];
  7018. y = args[j + 3];
  7019. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7020. j += 4;
  7021. break;
  7022. case OPS.closePath:
  7023. ctx.closePath();
  7024. break;
  7025. }
  7026. }
  7027. current.setCurrentPoint(x, y);
  7028. },
  7029. closePath: function CanvasGraphics_closePath() {
  7030. this.ctx.closePath();
  7031. },
  7032. stroke: function CanvasGraphics_stroke(consumePath) {
  7033. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7034. var ctx = this.ctx;
  7035. var strokeColor = this.current.strokeColor;
  7036. // Prevent drawing too thin lines by enforcing a minimum line width.
  7037. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7038. this.current.lineWidth);
  7039. // For stroke we want to temporarily change the global alpha to the
  7040. // stroking alpha.
  7041. ctx.globalAlpha = this.current.strokeAlpha;
  7042. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7043. strokeColor.type === 'Pattern') {
  7044. // for patterns, we transform to pattern space, calculate
  7045. // the pattern, call stroke, and restore to user space
  7046. ctx.save();
  7047. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7048. ctx.stroke();
  7049. ctx.restore();
  7050. } else {
  7051. ctx.stroke();
  7052. }
  7053. if (consumePath) {
  7054. this.consumePath();
  7055. }
  7056. // Restore the global alpha to the fill alpha
  7057. ctx.globalAlpha = this.current.fillAlpha;
  7058. },
  7059. closeStroke: function CanvasGraphics_closeStroke() {
  7060. this.closePath();
  7061. this.stroke();
  7062. },
  7063. fill: function CanvasGraphics_fill(consumePath) {
  7064. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7065. var ctx = this.ctx;
  7066. var fillColor = this.current.fillColor;
  7067. var isPatternFill = this.current.patternFill;
  7068. var needRestore = false;
  7069. if (isPatternFill) {
  7070. ctx.save();
  7071. if (this.baseTransform) {
  7072. ctx.setTransform.apply(ctx, this.baseTransform);
  7073. }
  7074. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7075. needRestore = true;
  7076. }
  7077. if (this.pendingEOFill) {
  7078. if (ctx.mozFillRule !== undefined) {
  7079. ctx.mozFillRule = 'evenodd';
  7080. ctx.fill();
  7081. ctx.mozFillRule = 'nonzero';
  7082. } else {
  7083. ctx.fill('evenodd');
  7084. }
  7085. this.pendingEOFill = false;
  7086. } else {
  7087. ctx.fill();
  7088. }
  7089. if (needRestore) {
  7090. ctx.restore();
  7091. }
  7092. if (consumePath) {
  7093. this.consumePath();
  7094. }
  7095. },
  7096. eoFill: function CanvasGraphics_eoFill() {
  7097. this.pendingEOFill = true;
  7098. this.fill();
  7099. },
  7100. fillStroke: function CanvasGraphics_fillStroke() {
  7101. this.fill(false);
  7102. this.stroke(false);
  7103. this.consumePath();
  7104. },
  7105. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7106. this.pendingEOFill = true;
  7107. this.fillStroke();
  7108. },
  7109. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7110. this.closePath();
  7111. this.fillStroke();
  7112. },
  7113. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7114. this.pendingEOFill = true;
  7115. this.closePath();
  7116. this.fillStroke();
  7117. },
  7118. endPath: function CanvasGraphics_endPath() {
  7119. this.consumePath();
  7120. },
  7121. // Clipping
  7122. clip: function CanvasGraphics_clip() {
  7123. this.pendingClip = NORMAL_CLIP;
  7124. },
  7125. eoClip: function CanvasGraphics_eoClip() {
  7126. this.pendingClip = EO_CLIP;
  7127. },
  7128. // Text
  7129. beginText: function CanvasGraphics_beginText() {
  7130. this.current.textMatrix = IDENTITY_MATRIX;
  7131. this.current.textMatrixScale = 1;
  7132. this.current.x = this.current.lineX = 0;
  7133. this.current.y = this.current.lineY = 0;
  7134. },
  7135. endText: function CanvasGraphics_endText() {
  7136. var paths = this.pendingTextPaths;
  7137. var ctx = this.ctx;
  7138. if (paths === undefined) {
  7139. ctx.beginPath();
  7140. return;
  7141. }
  7142. ctx.save();
  7143. ctx.beginPath();
  7144. for (var i = 0; i < paths.length; i++) {
  7145. var path = paths[i];
  7146. ctx.setTransform.apply(ctx, path.transform);
  7147. ctx.translate(path.x, path.y);
  7148. path.addToPath(ctx, path.fontSize);
  7149. }
  7150. ctx.restore();
  7151. ctx.clip();
  7152. ctx.beginPath();
  7153. delete this.pendingTextPaths;
  7154. },
  7155. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7156. this.current.charSpacing = spacing;
  7157. },
  7158. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7159. this.current.wordSpacing = spacing;
  7160. },
  7161. setHScale: function CanvasGraphics_setHScale(scale) {
  7162. this.current.textHScale = scale / 100;
  7163. },
  7164. setLeading: function CanvasGraphics_setLeading(leading) {
  7165. this.current.leading = -leading;
  7166. },
  7167. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7168. var fontObj = this.commonObjs.get(fontRefName);
  7169. var current = this.current;
  7170. if (!fontObj) {
  7171. error('Can\'t find font for ' + fontRefName);
  7172. }
  7173. current.fontMatrix = (fontObj.fontMatrix ?
  7174. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7175. // A valid matrix needs all main diagonal elements to be non-zero
  7176. // This also ensures we bypass FF bugzilla bug #719844.
  7177. if (current.fontMatrix[0] === 0 ||
  7178. current.fontMatrix[3] === 0) {
  7179. warn('Invalid font matrix for font ' + fontRefName);
  7180. }
  7181. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7182. // and in some docs this can be negative (inverted x-y axes).
  7183. if (size < 0) {
  7184. size = -size;
  7185. current.fontDirection = -1;
  7186. } else {
  7187. current.fontDirection = 1;
  7188. }
  7189. this.current.font = fontObj;
  7190. this.current.fontSize = size;
  7191. if (fontObj.isType3Font) {
  7192. return; // we don't need ctx.font for Type3 fonts
  7193. }
  7194. var name = fontObj.loadedName || 'sans-serif';
  7195. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7196. (fontObj.bold ? 'bold' : 'normal');
  7197. var italic = fontObj.italic ? 'italic' : 'normal';
  7198. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7199. // Some font backends cannot handle fonts below certain size.
  7200. // Keeping the font at minimal size and using the fontSizeScale to change
  7201. // the current transformation matrix before the fillText/strokeText.
  7202. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7203. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7204. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7205. this.current.fontSizeScale = size / browserFontSize;
  7206. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7207. this.ctx.font = rule;
  7208. },
  7209. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7210. this.current.textRenderingMode = mode;
  7211. },
  7212. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7213. this.current.textRise = rise;
  7214. },
  7215. moveText: function CanvasGraphics_moveText(x, y) {
  7216. this.current.x = this.current.lineX += x;
  7217. this.current.y = this.current.lineY += y;
  7218. },
  7219. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7220. this.setLeading(-y);
  7221. this.moveText(x, y);
  7222. },
  7223. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7224. this.current.textMatrix = [a, b, c, d, e, f];
  7225. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7226. this.current.x = this.current.lineX = 0;
  7227. this.current.y = this.current.lineY = 0;
  7228. },
  7229. nextLine: function CanvasGraphics_nextLine() {
  7230. this.moveText(0, this.current.leading);
  7231. },
  7232. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7233. var ctx = this.ctx;
  7234. var current = this.current;
  7235. var font = current.font;
  7236. var textRenderingMode = current.textRenderingMode;
  7237. var fontSize = current.fontSize / current.fontSizeScale;
  7238. var fillStrokeMode = textRenderingMode &
  7239. TextRenderingMode.FILL_STROKE_MASK;
  7240. var isAddToPathSet = !!(textRenderingMode &
  7241. TextRenderingMode.ADD_TO_PATH_FLAG);
  7242. var addToPath;
  7243. if (font.disableFontFace || isAddToPathSet) {
  7244. addToPath = font.getPathGenerator(this.commonObjs, character);
  7245. }
  7246. if (font.disableFontFace) {
  7247. ctx.save();
  7248. ctx.translate(x, y);
  7249. ctx.beginPath();
  7250. addToPath(ctx, fontSize);
  7251. if (fillStrokeMode === TextRenderingMode.FILL ||
  7252. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7253. ctx.fill();
  7254. }
  7255. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7256. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7257. ctx.stroke();
  7258. }
  7259. ctx.restore();
  7260. } else {
  7261. if (fillStrokeMode === TextRenderingMode.FILL ||
  7262. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7263. ctx.fillText(character, x, y);
  7264. }
  7265. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7266. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7267. ctx.strokeText(character, x, y);
  7268. }
  7269. }
  7270. if (isAddToPathSet) {
  7271. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7272. paths.push({
  7273. transform: ctx.mozCurrentTransform,
  7274. x: x,
  7275. y: y,
  7276. fontSize: fontSize,
  7277. addToPath: addToPath
  7278. });
  7279. }
  7280. },
  7281. get isFontSubpixelAAEnabled() {
  7282. // Checks if anti-aliasing is enabled when scaled text is painted.
  7283. // On Windows GDI scaled fonts looks bad.
  7284. var ctx = document.createElement('canvas').getContext('2d');
  7285. ctx.scale(1.5, 1);
  7286. ctx.fillText('I', 0, 10);
  7287. var data = ctx.getImageData(0, 0, 10, 10).data;
  7288. var enabled = false;
  7289. for (var i = 3; i < data.length; i += 4) {
  7290. if (data[i] > 0 && data[i] < 255) {
  7291. enabled = true;
  7292. break;
  7293. }
  7294. }
  7295. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7296. },
  7297. showText: function CanvasGraphics_showText(glyphs) {
  7298. var current = this.current;
  7299. var font = current.font;
  7300. if (font.isType3Font) {
  7301. return this.showType3Text(glyphs);
  7302. }
  7303. var fontSize = current.fontSize;
  7304. if (fontSize === 0) {
  7305. return;
  7306. }
  7307. var ctx = this.ctx;
  7308. var fontSizeScale = current.fontSizeScale;
  7309. var charSpacing = current.charSpacing;
  7310. var wordSpacing = current.wordSpacing;
  7311. var fontDirection = current.fontDirection;
  7312. var textHScale = current.textHScale * fontDirection;
  7313. var glyphsLength = glyphs.length;
  7314. var vertical = font.vertical;
  7315. var spacingDir = vertical ? 1 : -1;
  7316. var defaultVMetrics = font.defaultVMetrics;
  7317. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7318. var simpleFillText =
  7319. current.textRenderingMode === TextRenderingMode.FILL &&
  7320. !font.disableFontFace;
  7321. ctx.save();
  7322. ctx.transform.apply(ctx, current.textMatrix);
  7323. ctx.translate(current.x, current.y + current.textRise);
  7324. if (current.patternFill) {
  7325. // TODO: Some shading patterns are not applied correctly to text,
  7326. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7327. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7328. }
  7329. if (fontDirection > 0) {
  7330. ctx.scale(textHScale, -1);
  7331. } else {
  7332. ctx.scale(textHScale, 1);
  7333. }
  7334. var lineWidth = current.lineWidth;
  7335. var scale = current.textMatrixScale;
  7336. if (scale === 0 || lineWidth === 0) {
  7337. var fillStrokeMode = current.textRenderingMode &
  7338. TextRenderingMode.FILL_STROKE_MASK;
  7339. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7340. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7341. this.cachedGetSinglePixelWidth = null;
  7342. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7343. }
  7344. } else {
  7345. lineWidth /= scale;
  7346. }
  7347. if (fontSizeScale !== 1.0) {
  7348. ctx.scale(fontSizeScale, fontSizeScale);
  7349. lineWidth /= fontSizeScale;
  7350. }
  7351. ctx.lineWidth = lineWidth;
  7352. var x = 0, i;
  7353. for (i = 0; i < glyphsLength; ++i) {
  7354. var glyph = glyphs[i];
  7355. if (isNum(glyph)) {
  7356. x += spacingDir * glyph * fontSize / 1000;
  7357. continue;
  7358. }
  7359. var restoreNeeded = false;
  7360. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7361. var character = glyph.fontChar;
  7362. var accent = glyph.accent;
  7363. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7364. var width = glyph.width;
  7365. if (vertical) {
  7366. var vmetric, vx, vy;
  7367. vmetric = glyph.vmetric || defaultVMetrics;
  7368. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7369. vx = -vx * widthAdvanceScale;
  7370. vy = vmetric[2] * widthAdvanceScale;
  7371. width = vmetric ? -vmetric[0] : width;
  7372. scaledX = vx / fontSizeScale;
  7373. scaledY = (x + vy) / fontSizeScale;
  7374. } else {
  7375. scaledX = x / fontSizeScale;
  7376. scaledY = 0;
  7377. }
  7378. if (font.remeasure && width > 0) {
  7379. // Some standard fonts may not have the exact width: rescale per
  7380. // character if measured width is greater than expected glyph width
  7381. // and subpixel-aa is enabled, otherwise just center the glyph.
  7382. var measuredWidth = ctx.measureText(character).width * 1000 /
  7383. fontSize * fontSizeScale;
  7384. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7385. var characterScaleX = width / measuredWidth;
  7386. restoreNeeded = true;
  7387. ctx.save();
  7388. ctx.scale(characterScaleX, 1);
  7389. scaledX /= characterScaleX;
  7390. } else if (width !== measuredWidth) {
  7391. scaledX += (width - measuredWidth) / 2000 *
  7392. fontSize / fontSizeScale;
  7393. }
  7394. }
  7395. // Only attempt to draw the glyph if it is actually in the embedded font
  7396. // file or if there isn't a font file so the fallback font is shown.
  7397. if (glyph.isInFont || font.missingFile) {
  7398. if (simpleFillText && !accent) {
  7399. // common case
  7400. ctx.fillText(character, scaledX, scaledY);
  7401. } else {
  7402. this.paintChar(character, scaledX, scaledY);
  7403. if (accent) {
  7404. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7405. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7406. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7407. }
  7408. }
  7409. }
  7410. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7411. x += charWidth;
  7412. if (restoreNeeded) {
  7413. ctx.restore();
  7414. }
  7415. }
  7416. if (vertical) {
  7417. current.y -= x * textHScale;
  7418. } else {
  7419. current.x += x * textHScale;
  7420. }
  7421. ctx.restore();
  7422. },
  7423. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7424. // Type3 fonts - each glyph is a "mini-PDF"
  7425. var ctx = this.ctx;
  7426. var current = this.current;
  7427. var font = current.font;
  7428. var fontSize = current.fontSize;
  7429. var fontDirection = current.fontDirection;
  7430. var spacingDir = font.vertical ? 1 : -1;
  7431. var charSpacing = current.charSpacing;
  7432. var wordSpacing = current.wordSpacing;
  7433. var textHScale = current.textHScale * fontDirection;
  7434. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7435. var glyphsLength = glyphs.length;
  7436. var isTextInvisible =
  7437. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7438. var i, glyph, width, spacingLength;
  7439. if (isTextInvisible || fontSize === 0) {
  7440. return;
  7441. }
  7442. this.cachedGetSinglePixelWidth = null;
  7443. ctx.save();
  7444. ctx.transform.apply(ctx, current.textMatrix);
  7445. ctx.translate(current.x, current.y);
  7446. ctx.scale(textHScale, fontDirection);
  7447. for (i = 0; i < glyphsLength; ++i) {
  7448. glyph = glyphs[i];
  7449. if (isNum(glyph)) {
  7450. spacingLength = spacingDir * glyph * fontSize / 1000;
  7451. this.ctx.translate(spacingLength, 0);
  7452. current.x += spacingLength * textHScale;
  7453. continue;
  7454. }
  7455. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7456. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7457. if (!operatorList) {
  7458. warn('Type3 character \"' + glyph.operatorListId +
  7459. '\" is not available');
  7460. continue;
  7461. }
  7462. this.processingType3 = glyph;
  7463. this.save();
  7464. ctx.scale(fontSize, fontSize);
  7465. ctx.transform.apply(ctx, fontMatrix);
  7466. this.executeOperatorList(operatorList);
  7467. this.restore();
  7468. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7469. width = transformed[0] * fontSize + spacing;
  7470. ctx.translate(width, 0);
  7471. current.x += width * textHScale;
  7472. }
  7473. ctx.restore();
  7474. this.processingType3 = null;
  7475. },
  7476. // Type3 fonts
  7477. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7478. // We can safely ignore this since the width should be the same
  7479. // as the width in the Widths array.
  7480. },
  7481. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7482. yWidth,
  7483. llx,
  7484. lly,
  7485. urx,
  7486. ury) {
  7487. // TODO According to the spec we're also suppose to ignore any operators
  7488. // that set color or include images while processing this type3 font.
  7489. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7490. this.clip();
  7491. this.endPath();
  7492. },
  7493. // Color
  7494. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7495. var pattern;
  7496. if (IR[0] === 'TilingPattern') {
  7497. var color = IR[1];
  7498. var baseTransform = this.baseTransform ||
  7499. this.ctx.mozCurrentTransform.slice();
  7500. var self = this;
  7501. var canvasGraphicsFactory = {
  7502. createCanvasGraphics: function (ctx) {
  7503. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7504. }
  7505. };
  7506. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7507. baseTransform);
  7508. } else {
  7509. pattern = getShadingPatternFromIR(IR);
  7510. }
  7511. return pattern;
  7512. },
  7513. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7514. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7515. },
  7516. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7517. this.current.fillColor = this.getColorN_Pattern(arguments);
  7518. this.current.patternFill = true;
  7519. },
  7520. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7521. var color = Util.makeCssRgb(r, g, b);
  7522. this.ctx.strokeStyle = color;
  7523. this.current.strokeColor = color;
  7524. },
  7525. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7526. var color = Util.makeCssRgb(r, g, b);
  7527. this.ctx.fillStyle = color;
  7528. this.current.fillColor = color;
  7529. this.current.patternFill = false;
  7530. },
  7531. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7532. var ctx = this.ctx;
  7533. this.save();
  7534. var pattern = getShadingPatternFromIR(patternIR);
  7535. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7536. var inv = ctx.mozCurrentTransformInverse;
  7537. if (inv) {
  7538. var canvas = ctx.canvas;
  7539. var width = canvas.width;
  7540. var height = canvas.height;
  7541. var bl = Util.applyTransform([0, 0], inv);
  7542. var br = Util.applyTransform([0, height], inv);
  7543. var ul = Util.applyTransform([width, 0], inv);
  7544. var ur = Util.applyTransform([width, height], inv);
  7545. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7546. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7547. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7548. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7549. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7550. } else {
  7551. // HACK to draw the gradient onto an infinite rectangle.
  7552. // PDF gradients are drawn across the entire image while
  7553. // Canvas only allows gradients to be drawn in a rectangle
  7554. // The following bug should allow us to remove this.
  7555. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7556. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7557. }
  7558. this.restore();
  7559. },
  7560. // Images
  7561. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7562. error('Should not call beginInlineImage');
  7563. },
  7564. beginImageData: function CanvasGraphics_beginImageData() {
  7565. error('Should not call beginImageData');
  7566. },
  7567. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7568. bbox) {
  7569. this.save();
  7570. this.baseTransformStack.push(this.baseTransform);
  7571. if (isArray(matrix) && 6 === matrix.length) {
  7572. this.transform.apply(this, matrix);
  7573. }
  7574. this.baseTransform = this.ctx.mozCurrentTransform;
  7575. if (isArray(bbox) && 4 === bbox.length) {
  7576. var width = bbox[2] - bbox[0];
  7577. var height = bbox[3] - bbox[1];
  7578. this.ctx.rect(bbox[0], bbox[1], width, height);
  7579. this.clip();
  7580. this.endPath();
  7581. }
  7582. },
  7583. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7584. this.restore();
  7585. this.baseTransform = this.baseTransformStack.pop();
  7586. },
  7587. beginGroup: function CanvasGraphics_beginGroup(group) {
  7588. this.save();
  7589. var currentCtx = this.ctx;
  7590. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7591. // group results aren't usually that different and they even have tools
  7592. // that ignore this setting. Notes from Rik on implementing:
  7593. // - When you encounter an transparency group, create a new canvas with
  7594. // the dimensions of the bbox
  7595. // - copy the content from the previous canvas to the new canvas
  7596. // - draw as usual
  7597. // - remove the backdrop alpha:
  7598. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7599. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7600. // backdrop
  7601. // - remove background color:
  7602. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7603. if (!group.isolated) {
  7604. info('TODO: Support non-isolated groups.');
  7605. }
  7606. // TODO knockout - supposedly possible with the clever use of compositing
  7607. // modes.
  7608. if (group.knockout) {
  7609. warn('Knockout groups not supported.');
  7610. }
  7611. var currentTransform = currentCtx.mozCurrentTransform;
  7612. if (group.matrix) {
  7613. currentCtx.transform.apply(currentCtx, group.matrix);
  7614. }
  7615. assert(group.bbox, 'Bounding box is required.');
  7616. // Based on the current transform figure out how big the bounding box
  7617. // will actually be.
  7618. var bounds = Util.getAxialAlignedBoundingBox(
  7619. group.bbox,
  7620. currentCtx.mozCurrentTransform);
  7621. // Clip the bounding box to the current canvas.
  7622. var canvasBounds = [0,
  7623. 0,
  7624. currentCtx.canvas.width,
  7625. currentCtx.canvas.height];
  7626. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7627. // Use ceil in case we're between sizes so we don't create canvas that is
  7628. // too small and make the canvas at least 1x1 pixels.
  7629. var offsetX = Math.floor(bounds[0]);
  7630. var offsetY = Math.floor(bounds[1]);
  7631. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7632. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7633. var scaleX = 1, scaleY = 1;
  7634. if (drawnWidth > MAX_GROUP_SIZE) {
  7635. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7636. drawnWidth = MAX_GROUP_SIZE;
  7637. }
  7638. if (drawnHeight > MAX_GROUP_SIZE) {
  7639. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7640. drawnHeight = MAX_GROUP_SIZE;
  7641. }
  7642. var cacheId = 'groupAt' + this.groupLevel;
  7643. if (group.smask) {
  7644. // Using two cache entries is case if masks are used one after another.
  7645. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7646. }
  7647. var scratchCanvas = this.cachedCanvases.getCanvas(
  7648. cacheId, drawnWidth, drawnHeight, true);
  7649. var groupCtx = scratchCanvas.context;
  7650. // Since we created a new canvas that is just the size of the bounding box
  7651. // we have to translate the group ctx.
  7652. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7653. groupCtx.translate(-offsetX, -offsetY);
  7654. groupCtx.transform.apply(groupCtx, currentTransform);
  7655. if (group.smask) {
  7656. // Saving state and cached mask to be used in setGState.
  7657. this.smaskStack.push({
  7658. canvas: scratchCanvas.canvas,
  7659. context: groupCtx,
  7660. offsetX: offsetX,
  7661. offsetY: offsetY,
  7662. scaleX: scaleX,
  7663. scaleY: scaleY,
  7664. subtype: group.smask.subtype,
  7665. backdrop: group.smask.backdrop,
  7666. transferMap: group.smask.transferMap || null,
  7667. startTransformInverse: null, // used during suspend operation
  7668. });
  7669. } else {
  7670. // Setup the current ctx so when the group is popped we draw it at the
  7671. // right location.
  7672. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7673. currentCtx.translate(offsetX, offsetY);
  7674. currentCtx.scale(scaleX, scaleY);
  7675. }
  7676. // The transparency group inherits all off the current graphics state
  7677. // except the blend mode, soft mask, and alpha constants.
  7678. copyCtxState(currentCtx, groupCtx);
  7679. this.ctx = groupCtx;
  7680. this.setGState([
  7681. ['BM', 'Normal'],
  7682. ['ca', 1],
  7683. ['CA', 1]
  7684. ]);
  7685. this.groupStack.push(currentCtx);
  7686. this.groupLevel++;
  7687. // Reseting mask state, masks will be applied on restore of the group.
  7688. this.current.activeSMask = null;
  7689. },
  7690. endGroup: function CanvasGraphics_endGroup(group) {
  7691. this.groupLevel--;
  7692. var groupCtx = this.ctx;
  7693. this.ctx = this.groupStack.pop();
  7694. // Turn off image smoothing to avoid sub pixel interpolation which can
  7695. // look kind of blurry for some pdfs.
  7696. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7697. this.ctx.imageSmoothingEnabled = false;
  7698. } else {
  7699. this.ctx.mozImageSmoothingEnabled = false;
  7700. }
  7701. if (group.smask) {
  7702. this.tempSMask = this.smaskStack.pop();
  7703. } else {
  7704. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7705. }
  7706. this.restore();
  7707. },
  7708. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7709. this.save();
  7710. this.current = new CanvasExtraState();
  7711. if (this.baseTransform) {
  7712. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7713. }
  7714. },
  7715. endAnnotations: function CanvasGraphics_endAnnotations() {
  7716. this.restore();
  7717. },
  7718. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7719. matrix) {
  7720. this.save();
  7721. if (isArray(rect) && 4 === rect.length) {
  7722. var width = rect[2] - rect[0];
  7723. var height = rect[3] - rect[1];
  7724. this.ctx.rect(rect[0], rect[1], width, height);
  7725. this.clip();
  7726. this.endPath();
  7727. }
  7728. this.transform.apply(this, transform);
  7729. this.transform.apply(this, matrix);
  7730. },
  7731. endAnnotation: function CanvasGraphics_endAnnotation() {
  7732. this.restore();
  7733. },
  7734. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7735. var domImage = this.objs.get(objId);
  7736. if (!domImage) {
  7737. warn('Dependent image isn\'t ready yet');
  7738. return;
  7739. }
  7740. this.save();
  7741. var ctx = this.ctx;
  7742. // scale the image to the unit square
  7743. ctx.scale(1 / w, -1 / h);
  7744. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7745. 0, -h, w, h);
  7746. if (this.imageLayer) {
  7747. var currentTransform = ctx.mozCurrentTransformInverse;
  7748. var position = this.getCanvasPosition(0, 0);
  7749. this.imageLayer.appendImage({
  7750. objId: objId,
  7751. left: position[0],
  7752. top: position[1],
  7753. width: w / currentTransform[0],
  7754. height: h / currentTransform[3]
  7755. });
  7756. }
  7757. this.restore();
  7758. },
  7759. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7760. var ctx = this.ctx;
  7761. var width = img.width, height = img.height;
  7762. var fillColor = this.current.fillColor;
  7763. var isPatternFill = this.current.patternFill;
  7764. var glyph = this.processingType3;
  7765. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7766. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7767. glyph.compiled =
  7768. compileType3Glyph({data: img.data, width: width, height: height});
  7769. } else {
  7770. glyph.compiled = null;
  7771. }
  7772. }
  7773. if (glyph && glyph.compiled) {
  7774. glyph.compiled(ctx);
  7775. return;
  7776. }
  7777. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7778. width, height);
  7779. var maskCtx = maskCanvas.context;
  7780. maskCtx.save();
  7781. putBinaryImageMask(maskCtx, img);
  7782. maskCtx.globalCompositeOperation = 'source-in';
  7783. maskCtx.fillStyle = isPatternFill ?
  7784. fillColor.getPattern(maskCtx, this) : fillColor;
  7785. maskCtx.fillRect(0, 0, width, height);
  7786. maskCtx.restore();
  7787. this.paintInlineImageXObject(maskCanvas.canvas);
  7788. },
  7789. paintImageMaskXObjectRepeat:
  7790. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7791. scaleY, positions) {
  7792. var width = imgData.width;
  7793. var height = imgData.height;
  7794. var fillColor = this.current.fillColor;
  7795. var isPatternFill = this.current.patternFill;
  7796. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7797. width, height);
  7798. var maskCtx = maskCanvas.context;
  7799. maskCtx.save();
  7800. putBinaryImageMask(maskCtx, imgData);
  7801. maskCtx.globalCompositeOperation = 'source-in';
  7802. maskCtx.fillStyle = isPatternFill ?
  7803. fillColor.getPattern(maskCtx, this) : fillColor;
  7804. maskCtx.fillRect(0, 0, width, height);
  7805. maskCtx.restore();
  7806. var ctx = this.ctx;
  7807. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7808. ctx.save();
  7809. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7810. ctx.scale(1, -1);
  7811. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7812. 0, -1, 1, 1);
  7813. ctx.restore();
  7814. }
  7815. },
  7816. paintImageMaskXObjectGroup:
  7817. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7818. var ctx = this.ctx;
  7819. var fillColor = this.current.fillColor;
  7820. var isPatternFill = this.current.patternFill;
  7821. for (var i = 0, ii = images.length; i < ii; i++) {
  7822. var image = images[i];
  7823. var width = image.width, height = image.height;
  7824. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7825. width, height);
  7826. var maskCtx = maskCanvas.context;
  7827. maskCtx.save();
  7828. putBinaryImageMask(maskCtx, image);
  7829. maskCtx.globalCompositeOperation = 'source-in';
  7830. maskCtx.fillStyle = isPatternFill ?
  7831. fillColor.getPattern(maskCtx, this) : fillColor;
  7832. maskCtx.fillRect(0, 0, width, height);
  7833. maskCtx.restore();
  7834. ctx.save();
  7835. ctx.transform.apply(ctx, image.transform);
  7836. ctx.scale(1, -1);
  7837. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7838. 0, -1, 1, 1);
  7839. ctx.restore();
  7840. }
  7841. },
  7842. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7843. var imgData = this.objs.get(objId);
  7844. if (!imgData) {
  7845. warn('Dependent image isn\'t ready yet');
  7846. return;
  7847. }
  7848. this.paintInlineImageXObject(imgData);
  7849. },
  7850. paintImageXObjectRepeat:
  7851. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7852. positions) {
  7853. var imgData = this.objs.get(objId);
  7854. if (!imgData) {
  7855. warn('Dependent image isn\'t ready yet');
  7856. return;
  7857. }
  7858. var width = imgData.width;
  7859. var height = imgData.height;
  7860. var map = [];
  7861. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7862. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7863. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7864. }
  7865. this.paintInlineImageXObjectGroup(imgData, map);
  7866. },
  7867. paintInlineImageXObject:
  7868. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7869. var width = imgData.width;
  7870. var height = imgData.height;
  7871. var ctx = this.ctx;
  7872. this.save();
  7873. // scale the image to the unit square
  7874. ctx.scale(1 / width, -1 / height);
  7875. var currentTransform = ctx.mozCurrentTransformInverse;
  7876. var a = currentTransform[0], b = currentTransform[1];
  7877. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7878. var c = currentTransform[2], d = currentTransform[3];
  7879. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7880. var imgToPaint, tmpCanvas;
  7881. // instanceof HTMLElement does not work in jsdom node.js module
  7882. if (imgData instanceof HTMLElement || !imgData.data) {
  7883. imgToPaint = imgData;
  7884. } else {
  7885. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7886. width, height);
  7887. var tmpCtx = tmpCanvas.context;
  7888. putBinaryImageData(tmpCtx, imgData);
  7889. imgToPaint = tmpCanvas.canvas;
  7890. }
  7891. var paintWidth = width, paintHeight = height;
  7892. var tmpCanvasId = 'prescale1';
  7893. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7894. // pixels during drawImage operation, painting on the temporary canvas(es)
  7895. // that are twice smaller in size
  7896. while ((widthScale > 2 && paintWidth > 1) ||
  7897. (heightScale > 2 && paintHeight > 1)) {
  7898. var newWidth = paintWidth, newHeight = paintHeight;
  7899. if (widthScale > 2 && paintWidth > 1) {
  7900. newWidth = Math.ceil(paintWidth / 2);
  7901. widthScale /= paintWidth / newWidth;
  7902. }
  7903. if (heightScale > 2 && paintHeight > 1) {
  7904. newHeight = Math.ceil(paintHeight / 2);
  7905. heightScale /= paintHeight / newHeight;
  7906. }
  7907. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7908. newWidth, newHeight);
  7909. tmpCtx = tmpCanvas.context;
  7910. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7911. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7912. 0, 0, newWidth, newHeight);
  7913. imgToPaint = tmpCanvas.canvas;
  7914. paintWidth = newWidth;
  7915. paintHeight = newHeight;
  7916. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7917. }
  7918. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7919. 0, -height, width, height);
  7920. if (this.imageLayer) {
  7921. var position = this.getCanvasPosition(0, -height);
  7922. this.imageLayer.appendImage({
  7923. imgData: imgData,
  7924. left: position[0],
  7925. top: position[1],
  7926. width: width / currentTransform[0],
  7927. height: height / currentTransform[3]
  7928. });
  7929. }
  7930. this.restore();
  7931. },
  7932. paintInlineImageXObjectGroup:
  7933. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7934. var ctx = this.ctx;
  7935. var w = imgData.width;
  7936. var h = imgData.height;
  7937. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7938. var tmpCtx = tmpCanvas.context;
  7939. putBinaryImageData(tmpCtx, imgData);
  7940. for (var i = 0, ii = map.length; i < ii; i++) {
  7941. var entry = map[i];
  7942. ctx.save();
  7943. ctx.transform.apply(ctx, entry.transform);
  7944. ctx.scale(1, -1);
  7945. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  7946. 0, -1, 1, 1);
  7947. if (this.imageLayer) {
  7948. var position = this.getCanvasPosition(entry.x, entry.y);
  7949. this.imageLayer.appendImage({
  7950. imgData: imgData,
  7951. left: position[0],
  7952. top: position[1],
  7953. width: w,
  7954. height: h
  7955. });
  7956. }
  7957. ctx.restore();
  7958. }
  7959. },
  7960. paintSolidColorImageMask:
  7961. function CanvasGraphics_paintSolidColorImageMask() {
  7962. this.ctx.fillRect(0, 0, 1, 1);
  7963. },
  7964. paintXObject: function CanvasGraphics_paintXObject() {
  7965. warn('Unsupported \'paintXObject\' command.');
  7966. },
  7967. // Marked content
  7968. markPoint: function CanvasGraphics_markPoint(tag) {
  7969. // TODO Marked content.
  7970. },
  7971. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  7972. // TODO Marked content.
  7973. },
  7974. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  7975. // TODO Marked content.
  7976. },
  7977. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  7978. tag, properties) {
  7979. // TODO Marked content.
  7980. },
  7981. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  7982. // TODO Marked content.
  7983. },
  7984. // Compatibility
  7985. beginCompat: function CanvasGraphics_beginCompat() {
  7986. // TODO ignore undefined operators (should we do that anyway?)
  7987. },
  7988. endCompat: function CanvasGraphics_endCompat() {
  7989. // TODO stop ignoring undefined operators
  7990. },
  7991. // Helper functions
  7992. consumePath: function CanvasGraphics_consumePath() {
  7993. var ctx = this.ctx;
  7994. if (this.pendingClip) {
  7995. if (this.pendingClip === EO_CLIP) {
  7996. if (ctx.mozFillRule !== undefined) {
  7997. ctx.mozFillRule = 'evenodd';
  7998. ctx.clip();
  7999. ctx.mozFillRule = 'nonzero';
  8000. } else {
  8001. ctx.clip('evenodd');
  8002. }
  8003. } else {
  8004. ctx.clip();
  8005. }
  8006. this.pendingClip = null;
  8007. }
  8008. ctx.beginPath();
  8009. },
  8010. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8011. if (this.cachedGetSinglePixelWidth === null) {
  8012. // NOTE: The `save` and `restore` commands used below is a workaround
  8013. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8014. // from intermittently returning incorrect values in Firefox, see:
  8015. // https://github.com/mozilla/pdf.js/issues/7188.
  8016. this.ctx.save();
  8017. var inverse = this.ctx.mozCurrentTransformInverse;
  8018. this.ctx.restore();
  8019. // max of the current horizontal and vertical scale
  8020. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8021. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8022. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8023. }
  8024. return this.cachedGetSinglePixelWidth;
  8025. },
  8026. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8027. var transform = this.ctx.mozCurrentTransform;
  8028. return [
  8029. transform[0] * x + transform[2] * y + transform[4],
  8030. transform[1] * x + transform[3] * y + transform[5]
  8031. ];
  8032. }
  8033. };
  8034. for (var op in OPS) {
  8035. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8036. }
  8037. return CanvasGraphics;
  8038. })();
  8039. exports.CanvasGraphics = CanvasGraphics;
  8040. exports.createScratchCanvas = createScratchCanvas;
  8041. }));
  8042. (function (root, factory) {
  8043. {
  8044. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8045. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8046. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8047. }
  8048. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8049. displayMetadata, displayDOMUtils, amdRequire) {
  8050. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8051. var MessageHandler = sharedUtil.MessageHandler;
  8052. var MissingPDFException = sharedUtil.MissingPDFException;
  8053. var PageViewport = sharedUtil.PageViewport;
  8054. var PasswordResponses = sharedUtil.PasswordResponses;
  8055. var PasswordException = sharedUtil.PasswordException;
  8056. var StatTimer = sharedUtil.StatTimer;
  8057. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8058. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8059. var Util = sharedUtil.Util;
  8060. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8061. var error = sharedUtil.error;
  8062. var deprecated = sharedUtil.deprecated;
  8063. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8064. var info = sharedUtil.info;
  8065. var isInt = sharedUtil.isInt;
  8066. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8067. var isSameOrigin = sharedUtil.isSameOrigin;
  8068. var loadJpegStream = sharedUtil.loadJpegStream;
  8069. var stringToBytes = sharedUtil.stringToBytes;
  8070. var globalScope = sharedUtil.globalScope;
  8071. var warn = sharedUtil.warn;
  8072. var FontFaceObject = displayFontLoader.FontFaceObject;
  8073. var FontLoader = displayFontLoader.FontLoader;
  8074. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8075. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8076. var Metadata = displayMetadata.Metadata;
  8077. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8078. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8079. var isWorkerDisabled = false;
  8080. var workerSrc;
  8081. var isPostMessageTransfersDisabled = false;
  8082. var useRequireEnsure = false;
  8083. if (typeof window === 'undefined') {
  8084. // node.js - disable worker and set require.ensure.
  8085. isWorkerDisabled = true;
  8086. if (typeof require.ensure === 'undefined') {
  8087. require.ensure = require('node-ensure');
  8088. }
  8089. useRequireEnsure = true;
  8090. }
  8091. if (typeof __webpack_require__ !== 'undefined') {
  8092. useRequireEnsure = true;
  8093. }
  8094. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8095. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8096. }
  8097. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8098. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8099. require.ensure([], function () {
  8100. var worker = require('./pdf.worker.js');
  8101. callback(worker.WorkerMessageHandler);
  8102. });
  8103. }) : dynamicLoaderSupported ? (function (callback) {
  8104. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8105. callback(worker.WorkerMessageHandler);
  8106. });
  8107. }) : null;
  8108. /**
  8109. * Document initialization / loading parameters object.
  8110. *
  8111. * @typedef {Object} DocumentInitParameters
  8112. * @property {string} url - The URL of the PDF.
  8113. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8114. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8115. * use atob() to convert it to a binary string first.
  8116. * @property {Object} httpHeaders - Basic authentication headers.
  8117. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8118. * Access-Control requests should be made using credentials such as cookies
  8119. * or authorization headers. The default is false.
  8120. * @property {string} password - For decrypting password-protected PDFs.
  8121. * @property {TypedArray} initialData - A typed array with the first portion or
  8122. * all of the pdf data. Used by the extension since some data is already
  8123. * loaded before the switch to range requests.
  8124. * @property {number} length - The PDF file length. It's used for progress
  8125. * reports and range requests operations.
  8126. * @property {PDFDataRangeTransport} range
  8127. * @property {number} rangeChunkSize - Optional parameter to specify
  8128. * maximum number of bytes fetched per range request. The default value is
  8129. * 2^16 = 65536.
  8130. * @property {PDFWorker} worker - The worker that will be used for the loading
  8131. * and parsing of the PDF data.
  8132. */
  8133. /**
  8134. * @typedef {Object} PDFDocumentStats
  8135. * @property {Array} streamTypes - Used stream types in the document (an item
  8136. * is set to true if specific stream ID was used in the document).
  8137. * @property {Array} fontTypes - Used font type in the document (an item is set
  8138. * to true if specific font ID was used in the document).
  8139. */
  8140. /**
  8141. * This is the main entry point for loading a PDF and interacting with it.
  8142. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8143. * is used, which means it must follow the same origin rules that any XHR does
  8144. * e.g. No cross domain requests without CORS.
  8145. *
  8146. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8147. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8148. * already populated with data or parameter object.
  8149. *
  8150. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8151. * if you want to manually serve range requests for data in the PDF.
  8152. *
  8153. * @param {function} passwordCallback (deprecated) It is used to request a
  8154. * password if wrong or no password was provided. The callback receives two
  8155. * parameters: function that needs to be called with new password and reason
  8156. * (see {PasswordResponses}).
  8157. *
  8158. * @param {function} progressCallback (deprecated) It is used to be able to
  8159. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8160. * a loading bar). The callback receives an {Object} with the properties:
  8161. * {number} loaded and {number} total.
  8162. *
  8163. * @return {PDFDocumentLoadingTask}
  8164. */
  8165. function getDocument(src, pdfDataRangeTransport,
  8166. passwordCallback, progressCallback) {
  8167. var task = new PDFDocumentLoadingTask();
  8168. // Support of the obsolete arguments (for compatibility with API v1.0)
  8169. if (arguments.length > 1) {
  8170. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8171. 'passwordCallback or progressCallback argument');
  8172. }
  8173. if (pdfDataRangeTransport) {
  8174. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8175. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8176. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8177. pdfDataRangeTransport.length = src.length;
  8178. pdfDataRangeTransport.initialData = src.initialData;
  8179. if (!pdfDataRangeTransport.abort) {
  8180. pdfDataRangeTransport.abort = function () {};
  8181. }
  8182. }
  8183. src = Object.create(src);
  8184. src.range = pdfDataRangeTransport;
  8185. }
  8186. task.onPassword = passwordCallback || null;
  8187. task.onProgress = progressCallback || null;
  8188. var source;
  8189. if (typeof src === 'string') {
  8190. source = { url: src };
  8191. } else if (isArrayBuffer(src)) {
  8192. source = { data: src };
  8193. } else if (src instanceof PDFDataRangeTransport) {
  8194. source = { range: src };
  8195. } else {
  8196. if (typeof src !== 'object') {
  8197. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8198. 'string or a parameter object');
  8199. }
  8200. if (!src.url && !src.data && !src.range) {
  8201. error('Invalid parameter object: need either .data, .range or .url');
  8202. }
  8203. source = src;
  8204. }
  8205. var params = {};
  8206. var rangeTransport = null;
  8207. var worker = null;
  8208. for (var key in source) {
  8209. if (key === 'url' && typeof window !== 'undefined') {
  8210. // The full path is required in the 'url' field.
  8211. params[key] = new URL(source[key], window.location).href;
  8212. continue;
  8213. } else if (key === 'range') {
  8214. rangeTransport = source[key];
  8215. continue;
  8216. } else if (key === 'worker') {
  8217. worker = source[key];
  8218. continue;
  8219. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8220. // Converting string or array-like data to Uint8Array.
  8221. var pdfBytes = source[key];
  8222. if (typeof pdfBytes === 'string') {
  8223. params[key] = stringToBytes(pdfBytes);
  8224. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8225. !isNaN(pdfBytes.length)) {
  8226. params[key] = new Uint8Array(pdfBytes);
  8227. } else if (isArrayBuffer(pdfBytes)) {
  8228. params[key] = new Uint8Array(pdfBytes);
  8229. } else {
  8230. error('Invalid PDF binary data: either typed array, string or ' +
  8231. 'array-like object is expected in the data property.');
  8232. }
  8233. continue;
  8234. }
  8235. params[key] = source[key];
  8236. }
  8237. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8238. if (!worker) {
  8239. // Worker was not provided -- creating and owning our own.
  8240. worker = new PDFWorker();
  8241. task._worker = worker;
  8242. }
  8243. var docId = task.docId;
  8244. worker.promise.then(function () {
  8245. if (task.destroyed) {
  8246. throw new Error('Loading aborted');
  8247. }
  8248. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8249. function (workerId) {
  8250. if (task.destroyed) {
  8251. throw new Error('Loading aborted');
  8252. }
  8253. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8254. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8255. task._transport = transport;
  8256. messageHandler.send('Ready', null);
  8257. });
  8258. }).catch(task._capability.reject);
  8259. return task;
  8260. }
  8261. /**
  8262. * Starts fetching of specified PDF document/data.
  8263. * @param {PDFWorker} worker
  8264. * @param {Object} source
  8265. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8266. * @param {string} docId Unique document id, used as MessageHandler id.
  8267. * @returns {Promise} The promise, which is resolved when worker id of
  8268. * MessageHandler is known.
  8269. * @private
  8270. */
  8271. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8272. if (worker.destroyed) {
  8273. return Promise.reject(new Error('Worker was destroyed'));
  8274. }
  8275. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8276. source.disableStream = getDefaultSetting('disableStream');
  8277. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8278. if (pdfDataRangeTransport) {
  8279. source.length = pdfDataRangeTransport.length;
  8280. source.initialData = pdfDataRangeTransport.initialData;
  8281. }
  8282. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8283. docId: docId,
  8284. source: source,
  8285. disableRange: getDefaultSetting('disableRange'),
  8286. maxImageSize: getDefaultSetting('maxImageSize'),
  8287. cMapUrl: getDefaultSetting('cMapUrl'),
  8288. cMapPacked: getDefaultSetting('cMapPacked'),
  8289. disableFontFace: getDefaultSetting('disableFontFace'),
  8290. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8291. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8292. !isPostMessageTransfersDisabled,
  8293. }).then(function (workerId) {
  8294. if (worker.destroyed) {
  8295. throw new Error('Worker was destroyed');
  8296. }
  8297. return workerId;
  8298. });
  8299. }
  8300. /**
  8301. * PDF document loading operation.
  8302. * @class
  8303. * @alias PDFDocumentLoadingTask
  8304. */
  8305. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8306. var nextDocumentId = 0;
  8307. /** @constructs PDFDocumentLoadingTask */
  8308. function PDFDocumentLoadingTask() {
  8309. this._capability = createPromiseCapability();
  8310. this._transport = null;
  8311. this._worker = null;
  8312. /**
  8313. * Unique document loading task id -- used in MessageHandlers.
  8314. * @type {string}
  8315. */
  8316. this.docId = 'd' + (nextDocumentId++);
  8317. /**
  8318. * Shows if loading task is destroyed.
  8319. * @type {boolean}
  8320. */
  8321. this.destroyed = false;
  8322. /**
  8323. * Callback to request a password if wrong or no password was provided.
  8324. * The callback receives two parameters: function that needs to be called
  8325. * with new password and reason (see {PasswordResponses}).
  8326. */
  8327. this.onPassword = null;
  8328. /**
  8329. * Callback to be able to monitor the loading progress of the PDF file
  8330. * (necessary to implement e.g. a loading bar). The callback receives
  8331. * an {Object} with the properties: {number} loaded and {number} total.
  8332. */
  8333. this.onProgress = null;
  8334. /**
  8335. * Callback to when unsupported feature is used. The callback receives
  8336. * an {UNSUPPORTED_FEATURES} argument.
  8337. */
  8338. this.onUnsupportedFeature = null;
  8339. }
  8340. PDFDocumentLoadingTask.prototype =
  8341. /** @lends PDFDocumentLoadingTask.prototype */ {
  8342. /**
  8343. * @return {Promise}
  8344. */
  8345. get promise() {
  8346. return this._capability.promise;
  8347. },
  8348. /**
  8349. * Aborts all network requests and destroys worker.
  8350. * @return {Promise} A promise that is resolved after destruction activity
  8351. * is completed.
  8352. */
  8353. destroy: function () {
  8354. this.destroyed = true;
  8355. var transportDestroyed = !this._transport ? Promise.resolve() :
  8356. this._transport.destroy();
  8357. return transportDestroyed.then(function () {
  8358. this._transport = null;
  8359. if (this._worker) {
  8360. this._worker.destroy();
  8361. this._worker = null;
  8362. }
  8363. }.bind(this));
  8364. },
  8365. /**
  8366. * Registers callbacks to indicate the document loading completion.
  8367. *
  8368. * @param {function} onFulfilled The callback for the loading completion.
  8369. * @param {function} onRejected The callback for the loading failure.
  8370. * @return {Promise} A promise that is resolved after the onFulfilled or
  8371. * onRejected callback.
  8372. */
  8373. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8374. return this.promise.then.apply(this.promise, arguments);
  8375. }
  8376. };
  8377. return PDFDocumentLoadingTask;
  8378. })();
  8379. /**
  8380. * Abstract class to support range requests file loading.
  8381. * @class
  8382. * @alias PDFDataRangeTransport
  8383. * @param {number} length
  8384. * @param {Uint8Array} initialData
  8385. */
  8386. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8387. function PDFDataRangeTransport(length, initialData) {
  8388. this.length = length;
  8389. this.initialData = initialData;
  8390. this._rangeListeners = [];
  8391. this._progressListeners = [];
  8392. this._progressiveReadListeners = [];
  8393. this._readyCapability = createPromiseCapability();
  8394. }
  8395. PDFDataRangeTransport.prototype =
  8396. /** @lends PDFDataRangeTransport.prototype */ {
  8397. addRangeListener:
  8398. function PDFDataRangeTransport_addRangeListener(listener) {
  8399. this._rangeListeners.push(listener);
  8400. },
  8401. addProgressListener:
  8402. function PDFDataRangeTransport_addProgressListener(listener) {
  8403. this._progressListeners.push(listener);
  8404. },
  8405. addProgressiveReadListener:
  8406. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8407. this._progressiveReadListeners.push(listener);
  8408. },
  8409. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8410. var listeners = this._rangeListeners;
  8411. for (var i = 0, n = listeners.length; i < n; ++i) {
  8412. listeners[i](begin, chunk);
  8413. }
  8414. },
  8415. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8416. this._readyCapability.promise.then(function () {
  8417. var listeners = this._progressListeners;
  8418. for (var i = 0, n = listeners.length; i < n; ++i) {
  8419. listeners[i](loaded);
  8420. }
  8421. }.bind(this));
  8422. },
  8423. onDataProgressiveRead:
  8424. function PDFDataRangeTransport_onDataProgress(chunk) {
  8425. this._readyCapability.promise.then(function () {
  8426. var listeners = this._progressiveReadListeners;
  8427. for (var i = 0, n = listeners.length; i < n; ++i) {
  8428. listeners[i](chunk);
  8429. }
  8430. }.bind(this));
  8431. },
  8432. transportReady: function PDFDataRangeTransport_transportReady() {
  8433. this._readyCapability.resolve();
  8434. },
  8435. requestDataRange:
  8436. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8437. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8438. },
  8439. abort: function PDFDataRangeTransport_abort() {
  8440. }
  8441. };
  8442. return PDFDataRangeTransport;
  8443. })();
  8444. /**
  8445. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8446. * properties that can be read synchronously.
  8447. * @class
  8448. * @alias PDFDocumentProxy
  8449. */
  8450. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8451. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8452. this.pdfInfo = pdfInfo;
  8453. this.transport = transport;
  8454. this.loadingTask = loadingTask;
  8455. }
  8456. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8457. /**
  8458. * @return {number} Total number of pages the PDF contains.
  8459. */
  8460. get numPages() {
  8461. return this.pdfInfo.numPages;
  8462. },
  8463. /**
  8464. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8465. * unique.
  8466. */
  8467. get fingerprint() {
  8468. return this.pdfInfo.fingerprint;
  8469. },
  8470. /**
  8471. * @param {number} pageNumber The page number to get. The first page is 1.
  8472. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8473. * object.
  8474. */
  8475. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8476. return this.transport.getPage(pageNumber);
  8477. },
  8478. /**
  8479. * @param {{num: number, gen: number}} ref The page reference. Must have
  8480. * the 'num' and 'gen' properties.
  8481. * @return {Promise} A promise that is resolved with the page index that is
  8482. * associated with the reference.
  8483. */
  8484. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8485. return this.transport.getPageIndex(ref);
  8486. },
  8487. /**
  8488. * @return {Promise} A promise that is resolved with a lookup table for
  8489. * mapping named destinations to reference numbers.
  8490. *
  8491. * This can be slow for large documents: use getDestination instead
  8492. */
  8493. getDestinations: function PDFDocumentProxy_getDestinations() {
  8494. return this.transport.getDestinations();
  8495. },
  8496. /**
  8497. * @param {string} id The named destination to get.
  8498. * @return {Promise} A promise that is resolved with all information
  8499. * of the given named destination.
  8500. */
  8501. getDestination: function PDFDocumentProxy_getDestination(id) {
  8502. return this.transport.getDestination(id);
  8503. },
  8504. /**
  8505. * @return {Promise} A promise that is resolved with:
  8506. * an Array containing the pageLabels that correspond to the pageIndexes,
  8507. * or `null` when no pageLabels are present in the PDF file.
  8508. */
  8509. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8510. return this.transport.getPageLabels();
  8511. },
  8512. /**
  8513. * @return {Promise} A promise that is resolved with a lookup table for
  8514. * mapping named attachments to their content.
  8515. */
  8516. getAttachments: function PDFDocumentProxy_getAttachments() {
  8517. return this.transport.getAttachments();
  8518. },
  8519. /**
  8520. * @return {Promise} A promise that is resolved with an array of all the
  8521. * JavaScript strings in the name tree.
  8522. */
  8523. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8524. return this.transport.getJavaScript();
  8525. },
  8526. /**
  8527. * @return {Promise} A promise that is resolved with an {Array} that is a
  8528. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8529. * [
  8530. * {
  8531. * title: string,
  8532. * bold: boolean,
  8533. * italic: boolean,
  8534. * color: rgb Uint8Array,
  8535. * dest: dest obj,
  8536. * url: string,
  8537. * items: array of more items like this
  8538. * },
  8539. * ...
  8540. * ].
  8541. */
  8542. getOutline: function PDFDocumentProxy_getOutline() {
  8543. return this.transport.getOutline();
  8544. },
  8545. /**
  8546. * @return {Promise} A promise that is resolved with an {Object} that has
  8547. * info and metadata properties. Info is an {Object} filled with anything
  8548. * available in the information dictionary and similarly metadata is a
  8549. * {Metadata} object with information from the metadata section of the PDF.
  8550. */
  8551. getMetadata: function PDFDocumentProxy_getMetadata() {
  8552. return this.transport.getMetadata();
  8553. },
  8554. /**
  8555. * @return {Promise} A promise that is resolved with a TypedArray that has
  8556. * the raw data from the PDF.
  8557. */
  8558. getData: function PDFDocumentProxy_getData() {
  8559. return this.transport.getData();
  8560. },
  8561. /**
  8562. * @return {Promise} A promise that is resolved when the document's data
  8563. * is loaded. It is resolved with an {Object} that contains the length
  8564. * property that indicates size of the PDF data in bytes.
  8565. */
  8566. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8567. return this.transport.downloadInfoCapability.promise;
  8568. },
  8569. /**
  8570. * @return {Promise} A promise this is resolved with current stats about
  8571. * document structures (see {@link PDFDocumentStats}).
  8572. */
  8573. getStats: function PDFDocumentProxy_getStats() {
  8574. return this.transport.getStats();
  8575. },
  8576. /**
  8577. * Cleans up resources allocated by the document, e.g. created @font-face.
  8578. */
  8579. cleanup: function PDFDocumentProxy_cleanup() {
  8580. this.transport.startCleanup();
  8581. },
  8582. /**
  8583. * Destroys current document instance and terminates worker.
  8584. */
  8585. destroy: function PDFDocumentProxy_destroy() {
  8586. return this.loadingTask.destroy();
  8587. }
  8588. };
  8589. return PDFDocumentProxy;
  8590. })();
  8591. /**
  8592. * Page getTextContent parameters.
  8593. *
  8594. * @typedef {Object} getTextContentParameters
  8595. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8596. * whitespace with standard spaces (0x20). The default value is `false`.
  8597. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8598. * same line {@link TextItem}'s. The default value is `false`.
  8599. */
  8600. /**
  8601. * Page text content.
  8602. *
  8603. * @typedef {Object} TextContent
  8604. * @property {array} items - array of {@link TextItem}
  8605. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8606. * name.
  8607. */
  8608. /**
  8609. * Page text content part.
  8610. *
  8611. * @typedef {Object} TextItem
  8612. * @property {string} str - text content.
  8613. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8614. * @property {array} transform - transformation matrix.
  8615. * @property {number} width - width in device space.
  8616. * @property {number} height - height in device space.
  8617. * @property {string} fontName - font name used by pdf.js for converted font.
  8618. */
  8619. /**
  8620. * Text style.
  8621. *
  8622. * @typedef {Object} TextStyle
  8623. * @property {number} ascent - font ascent.
  8624. * @property {number} descent - font descent.
  8625. * @property {boolean} vertical - text is in vertical mode.
  8626. * @property {string} fontFamily - possible font family
  8627. */
  8628. /**
  8629. * Page annotation parameters.
  8630. *
  8631. * @typedef {Object} GetAnnotationsParameters
  8632. * @param {string} intent - Determines the annotations that will be fetched,
  8633. * can be either 'display' (viewable annotations) or 'print'
  8634. * (printable annotations).
  8635. * If the parameter is omitted, all annotations are fetched.
  8636. */
  8637. /**
  8638. * Page render parameters.
  8639. *
  8640. * @typedef {Object} RenderParameters
  8641. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8642. * @property {PageViewport} viewport - Rendering viewport obtained by
  8643. * calling of PDFPage.getViewport method.
  8644. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8645. * (default value is 'display').
  8646. * @property {Array} transform - (optional) Additional transform, applied
  8647. * just before viewport transform.
  8648. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8649. * endLayout and appendImage functions.
  8650. * @property {function} continueCallback - (deprecated) A function that will be
  8651. * called each time the rendering is paused. To continue
  8652. * rendering call the function that is the first argument
  8653. * to the callback.
  8654. */
  8655. /**
  8656. * PDF page operator list.
  8657. *
  8658. * @typedef {Object} PDFOperatorList
  8659. * @property {Array} fnArray - Array containing the operator functions.
  8660. * @property {Array} argsArray - Array containing the arguments of the
  8661. * functions.
  8662. */
  8663. /**
  8664. * Proxy to a PDFPage in the worker thread.
  8665. * @class
  8666. * @alias PDFPageProxy
  8667. */
  8668. var PDFPageProxy = (function PDFPageProxyClosure() {
  8669. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8670. this.pageIndex = pageIndex;
  8671. this.pageInfo = pageInfo;
  8672. this.transport = transport;
  8673. this.stats = new StatTimer();
  8674. this.stats.enabled = getDefaultSetting('enableStats');
  8675. this.commonObjs = transport.commonObjs;
  8676. this.objs = new PDFObjects();
  8677. this.cleanupAfterRender = false;
  8678. this.pendingCleanup = false;
  8679. this.intentStates = Object.create(null);
  8680. this.destroyed = false;
  8681. }
  8682. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8683. /**
  8684. * @return {number} Page number of the page. First page is 1.
  8685. */
  8686. get pageNumber() {
  8687. return this.pageIndex + 1;
  8688. },
  8689. /**
  8690. * @return {number} The number of degrees the page is rotated clockwise.
  8691. */
  8692. get rotate() {
  8693. return this.pageInfo.rotate;
  8694. },
  8695. /**
  8696. * @return {Object} The reference that points to this page. It has 'num' and
  8697. * 'gen' properties.
  8698. */
  8699. get ref() {
  8700. return this.pageInfo.ref;
  8701. },
  8702. /**
  8703. * @return {Array} An array of the visible portion of the PDF page in the
  8704. * user space units - [x1, y1, x2, y2].
  8705. */
  8706. get view() {
  8707. return this.pageInfo.view;
  8708. },
  8709. /**
  8710. * @param {number} scale The desired scale of the viewport.
  8711. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8712. * defaults to the page rotation.
  8713. * @return {PageViewport} Contains 'width' and 'height' properties
  8714. * along with transforms required for rendering.
  8715. */
  8716. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8717. if (arguments.length < 2) {
  8718. rotate = this.rotate;
  8719. }
  8720. return new PageViewport(this.view, scale, rotate, 0, 0);
  8721. },
  8722. /**
  8723. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8724. * @return {Promise} A promise that is resolved with an {Array} of the
  8725. * annotation objects.
  8726. */
  8727. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8728. var intent = (params && params.intent) || null;
  8729. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8730. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8731. intent);
  8732. this.annotationsIntent = intent;
  8733. }
  8734. return this.annotationsPromise;
  8735. },
  8736. /**
  8737. * Begins the process of rendering a page to the desired context.
  8738. * @param {RenderParameters} params Page render parameters.
  8739. * @return {RenderTask} An object that contains the promise, which
  8740. * is resolved when the page finishes rendering.
  8741. */
  8742. render: function PDFPageProxy_render(params) {
  8743. var stats = this.stats;
  8744. stats.time('Overall');
  8745. // If there was a pending destroy cancel it so no cleanup happens during
  8746. // this call to render.
  8747. this.pendingCleanup = false;
  8748. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8749. if (!this.intentStates[renderingIntent]) {
  8750. this.intentStates[renderingIntent] = Object.create(null);
  8751. }
  8752. var intentState = this.intentStates[renderingIntent];
  8753. // If there's no displayReadyCapability yet, then the operatorList
  8754. // was never requested before. Make the request and create the promise.
  8755. if (!intentState.displayReadyCapability) {
  8756. intentState.receivingOperatorList = true;
  8757. intentState.displayReadyCapability = createPromiseCapability();
  8758. intentState.operatorList = {
  8759. fnArray: [],
  8760. argsArray: [],
  8761. lastChunk: false
  8762. };
  8763. this.stats.time('Page Request');
  8764. this.transport.messageHandler.send('RenderPageRequest', {
  8765. pageIndex: this.pageNumber - 1,
  8766. intent: renderingIntent
  8767. });
  8768. }
  8769. var internalRenderTask = new InternalRenderTask(complete, params,
  8770. this.objs,
  8771. this.commonObjs,
  8772. intentState.operatorList,
  8773. this.pageNumber);
  8774. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8775. if (!intentState.renderTasks) {
  8776. intentState.renderTasks = [];
  8777. }
  8778. intentState.renderTasks.push(internalRenderTask);
  8779. var renderTask = internalRenderTask.task;
  8780. // Obsolete parameter support
  8781. if (params.continueCallback) {
  8782. deprecated('render is used with continueCallback parameter');
  8783. renderTask.onContinue = params.continueCallback;
  8784. }
  8785. var self = this;
  8786. intentState.displayReadyCapability.promise.then(
  8787. function pageDisplayReadyPromise(transparency) {
  8788. if (self.pendingCleanup) {
  8789. complete();
  8790. return;
  8791. }
  8792. stats.time('Rendering');
  8793. internalRenderTask.initializeGraphics(transparency);
  8794. internalRenderTask.operatorListChanged();
  8795. },
  8796. function pageDisplayReadPromiseError(reason) {
  8797. complete(reason);
  8798. }
  8799. );
  8800. function complete(error) {
  8801. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8802. if (i >= 0) {
  8803. intentState.renderTasks.splice(i, 1);
  8804. }
  8805. if (self.cleanupAfterRender) {
  8806. self.pendingCleanup = true;
  8807. }
  8808. self._tryCleanup();
  8809. if (error) {
  8810. internalRenderTask.capability.reject(error);
  8811. } else {
  8812. internalRenderTask.capability.resolve();
  8813. }
  8814. stats.timeEnd('Rendering');
  8815. stats.timeEnd('Overall');
  8816. }
  8817. return renderTask;
  8818. },
  8819. /**
  8820. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8821. * object that represents page's operator list.
  8822. */
  8823. getOperatorList: function PDFPageProxy_getOperatorList() {
  8824. function operatorListChanged() {
  8825. if (intentState.operatorList.lastChunk) {
  8826. intentState.opListReadCapability.resolve(intentState.operatorList);
  8827. var i = intentState.renderTasks.indexOf(opListTask);
  8828. if (i >= 0) {
  8829. intentState.renderTasks.splice(i, 1);
  8830. }
  8831. }
  8832. }
  8833. var renderingIntent = 'oplist';
  8834. if (!this.intentStates[renderingIntent]) {
  8835. this.intentStates[renderingIntent] = Object.create(null);
  8836. }
  8837. var intentState = this.intentStates[renderingIntent];
  8838. var opListTask;
  8839. if (!intentState.opListReadCapability) {
  8840. opListTask = {};
  8841. opListTask.operatorListChanged = operatorListChanged;
  8842. intentState.receivingOperatorList = true;
  8843. intentState.opListReadCapability = createPromiseCapability();
  8844. intentState.renderTasks = [];
  8845. intentState.renderTasks.push(opListTask);
  8846. intentState.operatorList = {
  8847. fnArray: [],
  8848. argsArray: [],
  8849. lastChunk: false
  8850. };
  8851. this.transport.messageHandler.send('RenderPageRequest', {
  8852. pageIndex: this.pageIndex,
  8853. intent: renderingIntent
  8854. });
  8855. }
  8856. return intentState.opListReadCapability.promise;
  8857. },
  8858. /**
  8859. * @param {getTextContentParameters} params - getTextContent parameters.
  8860. * @return {Promise} That is resolved a {@link TextContent}
  8861. * object that represent the page text content.
  8862. */
  8863. getTextContent: function PDFPageProxy_getTextContent(params) {
  8864. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8865. pageIndex: this.pageNumber - 1,
  8866. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8867. true : /* Default */ false),
  8868. combineTextItems: (params && params.disableCombineTextItems === true ?
  8869. false : /* Default */ true),
  8870. });
  8871. },
  8872. /**
  8873. * Destroys page object.
  8874. */
  8875. _destroy: function PDFPageProxy_destroy() {
  8876. this.destroyed = true;
  8877. this.transport.pageCache[this.pageIndex] = null;
  8878. var waitOn = [];
  8879. Object.keys(this.intentStates).forEach(function(intent) {
  8880. if (intent === 'oplist') {
  8881. // Avoid errors below, since the renderTasks are just stubs.
  8882. return;
  8883. }
  8884. var intentState = this.intentStates[intent];
  8885. intentState.renderTasks.forEach(function(renderTask) {
  8886. var renderCompleted = renderTask.capability.promise.
  8887. catch(function () {}); // ignoring failures
  8888. waitOn.push(renderCompleted);
  8889. renderTask.cancel();
  8890. });
  8891. }, this);
  8892. this.objs.clear();
  8893. this.annotationsPromise = null;
  8894. this.pendingCleanup = false;
  8895. return Promise.all(waitOn);
  8896. },
  8897. /**
  8898. * Cleans up resources allocated by the page. (deprecated)
  8899. */
  8900. destroy: function() {
  8901. deprecated('page destroy method, use cleanup() instead');
  8902. this.cleanup();
  8903. },
  8904. /**
  8905. * Cleans up resources allocated by the page.
  8906. */
  8907. cleanup: function PDFPageProxy_cleanup() {
  8908. this.pendingCleanup = true;
  8909. this._tryCleanup();
  8910. },
  8911. /**
  8912. * For internal use only. Attempts to clean up if rendering is in a state
  8913. * where that's possible.
  8914. * @ignore
  8915. */
  8916. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8917. if (!this.pendingCleanup ||
  8918. Object.keys(this.intentStates).some(function(intent) {
  8919. var intentState = this.intentStates[intent];
  8920. return (intentState.renderTasks.length !== 0 ||
  8921. intentState.receivingOperatorList);
  8922. }, this)) {
  8923. return;
  8924. }
  8925. Object.keys(this.intentStates).forEach(function(intent) {
  8926. delete this.intentStates[intent];
  8927. }, this);
  8928. this.objs.clear();
  8929. this.annotationsPromise = null;
  8930. this.pendingCleanup = false;
  8931. },
  8932. /**
  8933. * For internal use only.
  8934. * @ignore
  8935. */
  8936. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  8937. intent) {
  8938. var intentState = this.intentStates[intent];
  8939. // TODO Refactor RenderPageRequest to separate rendering
  8940. // and operator list logic
  8941. if (intentState.displayReadyCapability) {
  8942. intentState.displayReadyCapability.resolve(transparency);
  8943. }
  8944. },
  8945. /**
  8946. * For internal use only.
  8947. * @ignore
  8948. */
  8949. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  8950. intent) {
  8951. var intentState = this.intentStates[intent];
  8952. var i, ii;
  8953. // Add the new chunk to the current operator list.
  8954. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  8955. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  8956. intentState.operatorList.argsArray.push(
  8957. operatorListChunk.argsArray[i]);
  8958. }
  8959. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  8960. // Notify all the rendering tasks there are more operators to be consumed.
  8961. for (i = 0; i < intentState.renderTasks.length; i++) {
  8962. intentState.renderTasks[i].operatorListChanged();
  8963. }
  8964. if (operatorListChunk.lastChunk) {
  8965. intentState.receivingOperatorList = false;
  8966. this._tryCleanup();
  8967. }
  8968. }
  8969. };
  8970. return PDFPageProxy;
  8971. })();
  8972. /**
  8973. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  8974. * WorkerTransport for them. If creation of a web worker is not possible,
  8975. * a "fake" worker will be used instead.
  8976. * @class
  8977. */
  8978. var PDFWorker = (function PDFWorkerClosure() {
  8979. var nextFakeWorkerId = 0;
  8980. function getWorkerSrc() {
  8981. if (typeof workerSrc !== 'undefined') {
  8982. return workerSrc;
  8983. }
  8984. if (getDefaultSetting('workerSrc')) {
  8985. return getDefaultSetting('workerSrc');
  8986. }
  8987. if (pdfjsFilePath) {
  8988. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  8989. }
  8990. error('No PDFJS.workerSrc specified');
  8991. }
  8992. var fakeWorkerFilesLoadedCapability;
  8993. // Loads worker code into main thread.
  8994. function setupFakeWorkerGlobal() {
  8995. var WorkerMessageHandler;
  8996. if (!fakeWorkerFilesLoadedCapability) {
  8997. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  8998. // In the developer build load worker_loader which in turn loads all the
  8999. // other files and resolves the promise. In production only the
  9000. // pdf.worker.js file is needed.
  9001. var loader = fakeWorkerFilesLoader || function (callback) {
  9002. Util.loadScript(getWorkerSrc(), function () {
  9003. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9004. });
  9005. };
  9006. loader(fakeWorkerFilesLoadedCapability.resolve);
  9007. }
  9008. return fakeWorkerFilesLoadedCapability.promise;
  9009. }
  9010. function createCDNWrapper(url) {
  9011. // We will rely on blob URL's property to specify origin.
  9012. // We want this function to fail in case if createObjectURL or Blob do not
  9013. // exist or fail for some reason -- our Worker creation will fail anyway.
  9014. var wrapper = 'importScripts(\'' + url + '\');';
  9015. return URL.createObjectURL(new Blob([wrapper]));
  9016. }
  9017. function PDFWorker(name) {
  9018. this.name = name;
  9019. this.destroyed = false;
  9020. this._readyCapability = createPromiseCapability();
  9021. this._port = null;
  9022. this._webWorker = null;
  9023. this._messageHandler = null;
  9024. this._initialize();
  9025. }
  9026. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9027. get promise() {
  9028. return this._readyCapability.promise;
  9029. },
  9030. get port() {
  9031. return this._port;
  9032. },
  9033. get messageHandler() {
  9034. return this._messageHandler;
  9035. },
  9036. _initialize: function PDFWorker_initialize() {
  9037. // If worker support isn't disabled explicit and the browser has worker
  9038. // support, create a new web worker and test if it/the browser fulfills
  9039. // all requirements to run parts of pdf.js in a web worker.
  9040. // Right now, the requirement is, that an Uint8Array is still an
  9041. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9042. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9043. typeof Worker !== 'undefined') {
  9044. var workerSrc = getWorkerSrc();
  9045. try {
  9046. // Wraps workerSrc path into blob URL, if the former does not belong
  9047. // to the same origin.
  9048. if (!isSameOrigin(window.location.href, workerSrc)) {
  9049. workerSrc = createCDNWrapper(
  9050. new URL(workerSrc, window.location).href);
  9051. }
  9052. // Some versions of FF can't create a worker on localhost, see:
  9053. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9054. var worker = new Worker(workerSrc);
  9055. var messageHandler = new MessageHandler('main', 'worker', worker);
  9056. var terminateEarly = function() {
  9057. worker.removeEventListener('error', onWorkerError);
  9058. messageHandler.destroy();
  9059. worker.terminate();
  9060. if (this.destroyed) {
  9061. this._readyCapability.reject(new Error('Worker was destroyed'));
  9062. } else {
  9063. // Fall back to fake worker if the termination is caused by an
  9064. // error (e.g. NetworkError / SecurityError).
  9065. this._setupFakeWorker();
  9066. }
  9067. }.bind(this);
  9068. var onWorkerError = function(event) {
  9069. if (!this._webWorker) {
  9070. // Worker failed to initialize due to an error. Clean up and fall
  9071. // back to the fake worker.
  9072. terminateEarly();
  9073. }
  9074. }.bind(this);
  9075. worker.addEventListener('error', onWorkerError);
  9076. messageHandler.on('test', function PDFWorker_test(data) {
  9077. worker.removeEventListener('error', onWorkerError);
  9078. if (this.destroyed) {
  9079. terminateEarly();
  9080. return; // worker was destroyed
  9081. }
  9082. var supportTypedArray = data && data.supportTypedArray;
  9083. if (supportTypedArray) {
  9084. this._messageHandler = messageHandler;
  9085. this._port = worker;
  9086. this._webWorker = worker;
  9087. if (!data.supportTransfers) {
  9088. isPostMessageTransfersDisabled = true;
  9089. }
  9090. this._readyCapability.resolve();
  9091. // Send global setting, e.g. verbosity level.
  9092. messageHandler.send('configure', {
  9093. verbosity: getVerbosityLevel()
  9094. });
  9095. } else {
  9096. this._setupFakeWorker();
  9097. messageHandler.destroy();
  9098. worker.terminate();
  9099. }
  9100. }.bind(this));
  9101. messageHandler.on('console_log', function (data) {
  9102. console.log.apply(console, data);
  9103. });
  9104. messageHandler.on('console_error', function (data) {
  9105. console.error.apply(console, data);
  9106. });
  9107. messageHandler.on('ready', function (data) {
  9108. worker.removeEventListener('error', onWorkerError);
  9109. if (this.destroyed) {
  9110. terminateEarly();
  9111. return; // worker was destroyed
  9112. }
  9113. try {
  9114. sendTest();
  9115. } catch (e) {
  9116. // We need fallback to a faked worker.
  9117. this._setupFakeWorker();
  9118. }
  9119. }.bind(this));
  9120. var sendTest = function () {
  9121. var postMessageTransfers =
  9122. getDefaultSetting('postMessageTransfers') &&
  9123. !isPostMessageTransfersDisabled;
  9124. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9125. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9126. // typed array. Also, checking if we can use transfers.
  9127. try {
  9128. messageHandler.send('test', testObj, [testObj.buffer]);
  9129. } catch (ex) {
  9130. info('Cannot use postMessage transfers');
  9131. testObj[0] = 0;
  9132. messageHandler.send('test', testObj);
  9133. }
  9134. };
  9135. // It might take time for worker to initialize (especially when AMD
  9136. // loader is used). We will try to send test immediately, and then
  9137. // when 'ready' message will arrive. The worker shall process only
  9138. // first received 'test'.
  9139. sendTest();
  9140. return;
  9141. } catch (e) {
  9142. info('The worker has been disabled.');
  9143. }
  9144. }
  9145. // Either workers are disabled, not supported or have thrown an exception.
  9146. // Thus, we fallback to a faked worker.
  9147. this._setupFakeWorker();
  9148. },
  9149. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9150. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9151. warn('Setting up fake worker.');
  9152. isWorkerDisabled = true;
  9153. }
  9154. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9155. if (this.destroyed) {
  9156. this._readyCapability.reject(new Error('Worker was destroyed'));
  9157. return;
  9158. }
  9159. // If we don't use a worker, just post/sendMessage to the main thread.
  9160. var port = {
  9161. _listeners: [],
  9162. postMessage: function (obj) {
  9163. var e = {data: obj};
  9164. this._listeners.forEach(function (listener) {
  9165. listener.call(this, e);
  9166. }, this);
  9167. },
  9168. addEventListener: function (name, listener) {
  9169. this._listeners.push(listener);
  9170. },
  9171. removeEventListener: function (name, listener) {
  9172. var i = this._listeners.indexOf(listener);
  9173. this._listeners.splice(i, 1);
  9174. },
  9175. terminate: function () {}
  9176. };
  9177. this._port = port;
  9178. // All fake workers use the same port, making id unique.
  9179. var id = 'fake' + (nextFakeWorkerId++);
  9180. // If the main thread is our worker, setup the handling for the
  9181. // messages -- the main thread sends to it self.
  9182. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9183. WorkerMessageHandler.setup(workerHandler, port);
  9184. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9185. this._messageHandler = messageHandler;
  9186. this._readyCapability.resolve();
  9187. }.bind(this));
  9188. },
  9189. /**
  9190. * Destroys the worker instance.
  9191. */
  9192. destroy: function PDFWorker_destroy() {
  9193. this.destroyed = true;
  9194. if (this._webWorker) {
  9195. // We need to terminate only web worker created resource.
  9196. this._webWorker.terminate();
  9197. this._webWorker = null;
  9198. }
  9199. this._port = null;
  9200. if (this._messageHandler) {
  9201. this._messageHandler.destroy();
  9202. this._messageHandler = null;
  9203. }
  9204. }
  9205. };
  9206. return PDFWorker;
  9207. })();
  9208. /**
  9209. * For internal use only.
  9210. * @ignore
  9211. */
  9212. var WorkerTransport = (function WorkerTransportClosure() {
  9213. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9214. this.messageHandler = messageHandler;
  9215. this.loadingTask = loadingTask;
  9216. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9217. this.commonObjs = new PDFObjects();
  9218. this.fontLoader = new FontLoader(loadingTask.docId);
  9219. this.destroyed = false;
  9220. this.destroyCapability = null;
  9221. this.pageCache = [];
  9222. this.pagePromises = [];
  9223. this.downloadInfoCapability = createPromiseCapability();
  9224. this.setupMessageHandler();
  9225. }
  9226. WorkerTransport.prototype = {
  9227. destroy: function WorkerTransport_destroy() {
  9228. if (this.destroyCapability) {
  9229. return this.destroyCapability.promise;
  9230. }
  9231. this.destroyed = true;
  9232. this.destroyCapability = createPromiseCapability();
  9233. var waitOn = [];
  9234. // We need to wait for all renderings to be completed, e.g.
  9235. // timeout/rAF can take a long time.
  9236. this.pageCache.forEach(function (page) {
  9237. if (page) {
  9238. waitOn.push(page._destroy());
  9239. }
  9240. });
  9241. this.pageCache = [];
  9242. this.pagePromises = [];
  9243. var self = this;
  9244. // We also need to wait for the worker to finish its long running tasks.
  9245. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9246. waitOn.push(terminated);
  9247. Promise.all(waitOn).then(function () {
  9248. self.fontLoader.clear();
  9249. if (self.pdfDataRangeTransport) {
  9250. self.pdfDataRangeTransport.abort();
  9251. self.pdfDataRangeTransport = null;
  9252. }
  9253. if (self.messageHandler) {
  9254. self.messageHandler.destroy();
  9255. self.messageHandler = null;
  9256. }
  9257. self.destroyCapability.resolve();
  9258. }, this.destroyCapability.reject);
  9259. return this.destroyCapability.promise;
  9260. },
  9261. setupMessageHandler:
  9262. function WorkerTransport_setupMessageHandler() {
  9263. var messageHandler = this.messageHandler;
  9264. function updatePassword(password) {
  9265. messageHandler.send('UpdatePassword', password);
  9266. }
  9267. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9268. if (pdfDataRangeTransport) {
  9269. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9270. messageHandler.send('OnDataRange', {
  9271. begin: begin,
  9272. chunk: chunk
  9273. });
  9274. });
  9275. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9276. messageHandler.send('OnDataProgress', {
  9277. loaded: loaded
  9278. });
  9279. });
  9280. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9281. messageHandler.send('OnDataRange', {
  9282. chunk: chunk
  9283. });
  9284. });
  9285. messageHandler.on('RequestDataRange',
  9286. function transportDataRange(data) {
  9287. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9288. }, this);
  9289. }
  9290. messageHandler.on('GetDoc', function transportDoc(data) {
  9291. var pdfInfo = data.pdfInfo;
  9292. this.numPages = data.pdfInfo.numPages;
  9293. var loadingTask = this.loadingTask;
  9294. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9295. this.pdfDocument = pdfDocument;
  9296. loadingTask._capability.resolve(pdfDocument);
  9297. }, this);
  9298. messageHandler.on('NeedPassword',
  9299. function transportNeedPassword(exception) {
  9300. var loadingTask = this.loadingTask;
  9301. if (loadingTask.onPassword) {
  9302. return loadingTask.onPassword(updatePassword,
  9303. PasswordResponses.NEED_PASSWORD);
  9304. }
  9305. loadingTask._capability.reject(
  9306. new PasswordException(exception.message, exception.code));
  9307. }, this);
  9308. messageHandler.on('IncorrectPassword',
  9309. function transportIncorrectPassword(exception) {
  9310. var loadingTask = this.loadingTask;
  9311. if (loadingTask.onPassword) {
  9312. return loadingTask.onPassword(updatePassword,
  9313. PasswordResponses.INCORRECT_PASSWORD);
  9314. }
  9315. loadingTask._capability.reject(
  9316. new PasswordException(exception.message, exception.code));
  9317. }, this);
  9318. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9319. this.loadingTask._capability.reject(
  9320. new InvalidPDFException(exception.message));
  9321. }, this);
  9322. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9323. this.loadingTask._capability.reject(
  9324. new MissingPDFException(exception.message));
  9325. }, this);
  9326. messageHandler.on('UnexpectedResponse',
  9327. function transportUnexpectedResponse(exception) {
  9328. this.loadingTask._capability.reject(
  9329. new UnexpectedResponseException(exception.message, exception.status));
  9330. }, this);
  9331. messageHandler.on('UnknownError',
  9332. function transportUnknownError(exception) {
  9333. this.loadingTask._capability.reject(
  9334. new UnknownErrorException(exception.message, exception.details));
  9335. }, this);
  9336. messageHandler.on('DataLoaded', function transportPage(data) {
  9337. this.downloadInfoCapability.resolve(data);
  9338. }, this);
  9339. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9340. if (this.pdfDataRangeTransport) {
  9341. this.pdfDataRangeTransport.transportReady();
  9342. }
  9343. }, this);
  9344. messageHandler.on('StartRenderPage', function transportRender(data) {
  9345. if (this.destroyed) {
  9346. return; // Ignore any pending requests if the worker was terminated.
  9347. }
  9348. var page = this.pageCache[data.pageIndex];
  9349. page.stats.timeEnd('Page Request');
  9350. page._startRenderPage(data.transparency, data.intent);
  9351. }, this);
  9352. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9353. if (this.destroyed) {
  9354. return; // Ignore any pending requests if the worker was terminated.
  9355. }
  9356. var page = this.pageCache[data.pageIndex];
  9357. page._renderPageChunk(data.operatorList, data.intent);
  9358. }, this);
  9359. messageHandler.on('commonobj', function transportObj(data) {
  9360. if (this.destroyed) {
  9361. return; // Ignore any pending requests if the worker was terminated.
  9362. }
  9363. var id = data[0];
  9364. var type = data[1];
  9365. if (this.commonObjs.hasData(id)) {
  9366. return;
  9367. }
  9368. switch (type) {
  9369. case 'Font':
  9370. var exportedData = data[2];
  9371. if ('error' in exportedData) {
  9372. var exportedError = exportedData.error;
  9373. warn('Error during font loading: ' + exportedError);
  9374. this.commonObjs.resolve(id, exportedError);
  9375. break;
  9376. }
  9377. var fontRegistry = null;
  9378. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9379. globalScope['FontInspector'].enabled) {
  9380. fontRegistry = {
  9381. registerFont: function (font, url) {
  9382. globalScope['FontInspector'].fontAdded(font, url);
  9383. }
  9384. };
  9385. }
  9386. var font = new FontFaceObject(exportedData, {
  9387. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9388. disableFontFace: getDefaultSetting('disableFontFace'),
  9389. fontRegistry: fontRegistry
  9390. });
  9391. this.fontLoader.bind(
  9392. [font],
  9393. function fontReady(fontObjs) {
  9394. this.commonObjs.resolve(id, font);
  9395. }.bind(this)
  9396. );
  9397. break;
  9398. case 'FontPath':
  9399. this.commonObjs.resolve(id, data[2]);
  9400. break;
  9401. default:
  9402. error('Got unknown common object type ' + type);
  9403. }
  9404. }, this);
  9405. messageHandler.on('obj', function transportObj(data) {
  9406. if (this.destroyed) {
  9407. return; // Ignore any pending requests if the worker was terminated.
  9408. }
  9409. var id = data[0];
  9410. var pageIndex = data[1];
  9411. var type = data[2];
  9412. var pageProxy = this.pageCache[pageIndex];
  9413. var imageData;
  9414. if (pageProxy.objs.hasData(id)) {
  9415. return;
  9416. }
  9417. switch (type) {
  9418. case 'JpegStream':
  9419. imageData = data[3];
  9420. loadJpegStream(id, imageData, pageProxy.objs);
  9421. break;
  9422. case 'Image':
  9423. imageData = data[3];
  9424. pageProxy.objs.resolve(id, imageData);
  9425. // heuristics that will allow not to store large data
  9426. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9427. if (imageData && 'data' in imageData &&
  9428. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9429. pageProxy.cleanupAfterRender = true;
  9430. }
  9431. break;
  9432. default:
  9433. error('Got unknown object type ' + type);
  9434. }
  9435. }, this);
  9436. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9437. if (this.destroyed) {
  9438. return; // Ignore any pending requests if the worker was terminated.
  9439. }
  9440. var loadingTask = this.loadingTask;
  9441. if (loadingTask.onProgress) {
  9442. loadingTask.onProgress({
  9443. loaded: data.loaded,
  9444. total: data.total
  9445. });
  9446. }
  9447. }, this);
  9448. messageHandler.on('PageError', function transportError(data) {
  9449. if (this.destroyed) {
  9450. return; // Ignore any pending requests if the worker was terminated.
  9451. }
  9452. var page = this.pageCache[data.pageNum - 1];
  9453. var intentState = page.intentStates[data.intent];
  9454. if (intentState.displayReadyCapability) {
  9455. intentState.displayReadyCapability.reject(data.error);
  9456. } else {
  9457. error(data.error);
  9458. }
  9459. if (intentState.operatorList) {
  9460. // Mark operator list as complete.
  9461. intentState.operatorList.lastChunk = true;
  9462. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9463. intentState.renderTasks[i].operatorListChanged();
  9464. }
  9465. }
  9466. }, this);
  9467. messageHandler.on('UnsupportedFeature',
  9468. function transportUnsupportedFeature(data) {
  9469. if (this.destroyed) {
  9470. return; // Ignore any pending requests if the worker was terminated.
  9471. }
  9472. var featureId = data.featureId;
  9473. var loadingTask = this.loadingTask;
  9474. if (loadingTask.onUnsupportedFeature) {
  9475. loadingTask.onUnsupportedFeature(featureId);
  9476. }
  9477. _UnsupportedManager.notify(featureId);
  9478. }, this);
  9479. messageHandler.on('JpegDecode', function(data) {
  9480. if (this.destroyed) {
  9481. return Promise.reject(new Error('Worker was destroyed'));
  9482. }
  9483. var imageUrl = data[0];
  9484. var components = data[1];
  9485. if (components !== 3 && components !== 1) {
  9486. return Promise.reject(
  9487. new Error('Only 3 components or 1 component can be returned'));
  9488. }
  9489. return new Promise(function (resolve, reject) {
  9490. var img = new Image();
  9491. img.onload = function () {
  9492. var width = img.width;
  9493. var height = img.height;
  9494. var size = width * height;
  9495. var rgbaLength = size * 4;
  9496. var buf = new Uint8Array(size * components);
  9497. var tmpCanvas = createScratchCanvas(width, height);
  9498. var tmpCtx = tmpCanvas.getContext('2d');
  9499. tmpCtx.drawImage(img, 0, 0);
  9500. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9501. var i, j;
  9502. if (components === 3) {
  9503. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9504. buf[j] = data[i];
  9505. buf[j + 1] = data[i + 1];
  9506. buf[j + 2] = data[i + 2];
  9507. }
  9508. } else if (components === 1) {
  9509. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9510. buf[j] = data[i];
  9511. }
  9512. }
  9513. resolve({ data: buf, width: width, height: height});
  9514. };
  9515. img.onerror = function () {
  9516. reject(new Error('JpegDecode failed to load image'));
  9517. };
  9518. img.src = imageUrl;
  9519. });
  9520. }, this);
  9521. },
  9522. getData: function WorkerTransport_getData() {
  9523. return this.messageHandler.sendWithPromise('GetData', null);
  9524. },
  9525. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9526. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9527. return Promise.reject(new Error('Invalid page request'));
  9528. }
  9529. var pageIndex = pageNumber - 1;
  9530. if (pageIndex in this.pagePromises) {
  9531. return this.pagePromises[pageIndex];
  9532. }
  9533. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9534. pageIndex: pageIndex
  9535. }).then(function (pageInfo) {
  9536. if (this.destroyed) {
  9537. throw new Error('Transport destroyed');
  9538. }
  9539. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9540. this.pageCache[pageIndex] = page;
  9541. return page;
  9542. }.bind(this));
  9543. this.pagePromises[pageIndex] = promise;
  9544. return promise;
  9545. },
  9546. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9547. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9548. ref: ref,
  9549. }).catch(function (reason) {
  9550. return Promise.reject(new Error(reason));
  9551. });
  9552. },
  9553. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9554. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9555. pageIndex: pageIndex,
  9556. intent: intent,
  9557. });
  9558. },
  9559. getDestinations: function WorkerTransport_getDestinations() {
  9560. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9561. },
  9562. getDestination: function WorkerTransport_getDestination(id) {
  9563. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9564. },
  9565. getPageLabels: function WorkerTransport_getPageLabels() {
  9566. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9567. },
  9568. getAttachments: function WorkerTransport_getAttachments() {
  9569. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9570. },
  9571. getJavaScript: function WorkerTransport_getJavaScript() {
  9572. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9573. },
  9574. getOutline: function WorkerTransport_getOutline() {
  9575. return this.messageHandler.sendWithPromise('GetOutline', null);
  9576. },
  9577. getMetadata: function WorkerTransport_getMetadata() {
  9578. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9579. then(function transportMetadata(results) {
  9580. return {
  9581. info: results[0],
  9582. metadata: (results[1] ? new Metadata(results[1]) : null)
  9583. };
  9584. });
  9585. },
  9586. getStats: function WorkerTransport_getStats() {
  9587. return this.messageHandler.sendWithPromise('GetStats', null);
  9588. },
  9589. startCleanup: function WorkerTransport_startCleanup() {
  9590. this.messageHandler.sendWithPromise('Cleanup', null).
  9591. then(function endCleanup() {
  9592. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9593. var page = this.pageCache[i];
  9594. if (page) {
  9595. page.cleanup();
  9596. }
  9597. }
  9598. this.commonObjs.clear();
  9599. this.fontLoader.clear();
  9600. }.bind(this));
  9601. }
  9602. };
  9603. return WorkerTransport;
  9604. })();
  9605. /**
  9606. * A PDF document and page is built of many objects. E.g. there are objects
  9607. * for fonts, images, rendering code and such. These objects might get processed
  9608. * inside of a worker. The `PDFObjects` implements some basic functions to
  9609. * manage these objects.
  9610. * @ignore
  9611. */
  9612. var PDFObjects = (function PDFObjectsClosure() {
  9613. function PDFObjects() {
  9614. this.objs = Object.create(null);
  9615. }
  9616. PDFObjects.prototype = {
  9617. /**
  9618. * Internal function.
  9619. * Ensures there is an object defined for `objId`.
  9620. */
  9621. ensureObj: function PDFObjects_ensureObj(objId) {
  9622. if (this.objs[objId]) {
  9623. return this.objs[objId];
  9624. }
  9625. var obj = {
  9626. capability: createPromiseCapability(),
  9627. data: null,
  9628. resolved: false
  9629. };
  9630. this.objs[objId] = obj;
  9631. return obj;
  9632. },
  9633. /**
  9634. * If called *without* callback, this returns the data of `objId` but the
  9635. * object needs to be resolved. If it isn't, this function throws.
  9636. *
  9637. * If called *with* a callback, the callback is called with the data of the
  9638. * object once the object is resolved. That means, if you call this
  9639. * function and the object is already resolved, the callback gets called
  9640. * right away.
  9641. */
  9642. get: function PDFObjects_get(objId, callback) {
  9643. // If there is a callback, then the get can be async and the object is
  9644. // not required to be resolved right now
  9645. if (callback) {
  9646. this.ensureObj(objId).capability.promise.then(callback);
  9647. return null;
  9648. }
  9649. // If there isn't a callback, the user expects to get the resolved data
  9650. // directly.
  9651. var obj = this.objs[objId];
  9652. // If there isn't an object yet or the object isn't resolved, then the
  9653. // data isn't ready yet!
  9654. if (!obj || !obj.resolved) {
  9655. error('Requesting object that isn\'t resolved yet ' + objId);
  9656. }
  9657. return obj.data;
  9658. },
  9659. /**
  9660. * Resolves the object `objId` with optional `data`.
  9661. */
  9662. resolve: function PDFObjects_resolve(objId, data) {
  9663. var obj = this.ensureObj(objId);
  9664. obj.resolved = true;
  9665. obj.data = data;
  9666. obj.capability.resolve(data);
  9667. },
  9668. isResolved: function PDFObjects_isResolved(objId) {
  9669. var objs = this.objs;
  9670. if (!objs[objId]) {
  9671. return false;
  9672. } else {
  9673. return objs[objId].resolved;
  9674. }
  9675. },
  9676. hasData: function PDFObjects_hasData(objId) {
  9677. return this.isResolved(objId);
  9678. },
  9679. /**
  9680. * Returns the data of `objId` if object exists, null otherwise.
  9681. */
  9682. getData: function PDFObjects_getData(objId) {
  9683. var objs = this.objs;
  9684. if (!objs[objId] || !objs[objId].resolved) {
  9685. return null;
  9686. } else {
  9687. return objs[objId].data;
  9688. }
  9689. },
  9690. clear: function PDFObjects_clear() {
  9691. this.objs = Object.create(null);
  9692. }
  9693. };
  9694. return PDFObjects;
  9695. })();
  9696. /**
  9697. * Allows controlling of the rendering tasks.
  9698. * @class
  9699. * @alias RenderTask
  9700. */
  9701. var RenderTask = (function RenderTaskClosure() {
  9702. function RenderTask(internalRenderTask) {
  9703. this._internalRenderTask = internalRenderTask;
  9704. /**
  9705. * Callback for incremental rendering -- a function that will be called
  9706. * each time the rendering is paused. To continue rendering call the
  9707. * function that is the first argument to the callback.
  9708. * @type {function}
  9709. */
  9710. this.onContinue = null;
  9711. }
  9712. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9713. /**
  9714. * Promise for rendering task completion.
  9715. * @return {Promise}
  9716. */
  9717. get promise() {
  9718. return this._internalRenderTask.capability.promise;
  9719. },
  9720. /**
  9721. * Cancels the rendering task. If the task is currently rendering it will
  9722. * not be cancelled until graphics pauses with a timeout. The promise that
  9723. * this object extends will resolved when cancelled.
  9724. */
  9725. cancel: function RenderTask_cancel() {
  9726. this._internalRenderTask.cancel();
  9727. },
  9728. /**
  9729. * Registers callbacks to indicate the rendering task completion.
  9730. *
  9731. * @param {function} onFulfilled The callback for the rendering completion.
  9732. * @param {function} onRejected The callback for the rendering failure.
  9733. * @return {Promise} A promise that is resolved after the onFulfilled or
  9734. * onRejected callback.
  9735. */
  9736. then: function RenderTask_then(onFulfilled, onRejected) {
  9737. return this.promise.then.apply(this.promise, arguments);
  9738. }
  9739. };
  9740. return RenderTask;
  9741. })();
  9742. /**
  9743. * For internal use only.
  9744. * @ignore
  9745. */
  9746. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9747. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9748. pageNumber) {
  9749. this.callback = callback;
  9750. this.params = params;
  9751. this.objs = objs;
  9752. this.commonObjs = commonObjs;
  9753. this.operatorListIdx = null;
  9754. this.operatorList = operatorList;
  9755. this.pageNumber = pageNumber;
  9756. this.running = false;
  9757. this.graphicsReadyCallback = null;
  9758. this.graphicsReady = false;
  9759. this.useRequestAnimationFrame = false;
  9760. this.cancelled = false;
  9761. this.capability = createPromiseCapability();
  9762. this.task = new RenderTask(this);
  9763. // caching this-bound methods
  9764. this._continueBound = this._continue.bind(this);
  9765. this._scheduleNextBound = this._scheduleNext.bind(this);
  9766. this._nextBound = this._next.bind(this);
  9767. }
  9768. InternalRenderTask.prototype = {
  9769. initializeGraphics:
  9770. function InternalRenderTask_initializeGraphics(transparency) {
  9771. if (this.cancelled) {
  9772. return;
  9773. }
  9774. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9775. globalScope.StepperManager.enabled) {
  9776. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9777. this.stepper.init(this.operatorList);
  9778. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9779. }
  9780. var params = this.params;
  9781. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9782. this.objs, params.imageLayer);
  9783. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9784. this.operatorListIdx = 0;
  9785. this.graphicsReady = true;
  9786. if (this.graphicsReadyCallback) {
  9787. this.graphicsReadyCallback();
  9788. }
  9789. },
  9790. cancel: function InternalRenderTask_cancel() {
  9791. this.running = false;
  9792. this.cancelled = true;
  9793. this.callback('cancelled');
  9794. },
  9795. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9796. if (!this.graphicsReady) {
  9797. if (!this.graphicsReadyCallback) {
  9798. this.graphicsReadyCallback = this._continueBound;
  9799. }
  9800. return;
  9801. }
  9802. if (this.stepper) {
  9803. this.stepper.updateOperatorList(this.operatorList);
  9804. }
  9805. if (this.running) {
  9806. return;
  9807. }
  9808. this._continue();
  9809. },
  9810. _continue: function InternalRenderTask__continue() {
  9811. this.running = true;
  9812. if (this.cancelled) {
  9813. return;
  9814. }
  9815. if (this.task.onContinue) {
  9816. this.task.onContinue.call(this.task, this._scheduleNextBound);
  9817. } else {
  9818. this._scheduleNext();
  9819. }
  9820. },
  9821. _scheduleNext: function InternalRenderTask__scheduleNext() {
  9822. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  9823. window.requestAnimationFrame(this._nextBound);
  9824. } else {
  9825. Promise.resolve(undefined).then(this._nextBound);
  9826. }
  9827. },
  9828. _next: function InternalRenderTask__next() {
  9829. if (this.cancelled) {
  9830. return;
  9831. }
  9832. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  9833. this.operatorListIdx,
  9834. this._continueBound,
  9835. this.stepper);
  9836. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  9837. this.running = false;
  9838. if (this.operatorList.lastChunk) {
  9839. this.gfx.endDrawing();
  9840. this.callback();
  9841. }
  9842. }
  9843. }
  9844. };
  9845. return InternalRenderTask;
  9846. })();
  9847. /**
  9848. * (Deprecated) Global observer of unsupported feature usages. Use
  9849. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  9850. */
  9851. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  9852. var listeners = [];
  9853. return {
  9854. listen: function (cb) {
  9855. deprecated('Global UnsupportedManager.listen is used: ' +
  9856. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  9857. listeners.push(cb);
  9858. },
  9859. notify: function (featureId) {
  9860. for (var i = 0, ii = listeners.length; i < ii; i++) {
  9861. listeners[i](featureId);
  9862. }
  9863. }
  9864. };
  9865. })();
  9866. if (typeof pdfjsVersion !== 'undefined') {
  9867. exports.version = pdfjsVersion;
  9868. }
  9869. if (typeof pdfjsBuild !== 'undefined') {
  9870. exports.build = pdfjsBuild;
  9871. }
  9872. exports.getDocument = getDocument;
  9873. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  9874. exports.PDFWorker = PDFWorker;
  9875. exports.PDFDocumentProxy = PDFDocumentProxy;
  9876. exports.PDFPageProxy = PDFPageProxy;
  9877. exports._UnsupportedManager = _UnsupportedManager;
  9878. }));
  9879. (function (root, factory) {
  9880. {
  9881. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  9882. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  9883. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  9884. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  9885. }
  9886. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  9887. displayAnnotationLayer, displayTextLayer, displayMetadata,
  9888. displaySVG) {
  9889. var globalScope = sharedUtil.globalScope;
  9890. var deprecated = sharedUtil.deprecated;
  9891. var warn = sharedUtil.warn;
  9892. var LinkTarget = displayDOMUtils.LinkTarget;
  9893. var isWorker = (typeof window === 'undefined');
  9894. // The global PDFJS object is now deprecated and will not be supported in
  9895. // the future. The members below are maintained for backward compatibility
  9896. // and shall not be extended or modified. If the global.js is included as
  9897. // a module, we will create a global PDFJS object instance or use existing.
  9898. if (!globalScope.PDFJS) {
  9899. globalScope.PDFJS = {};
  9900. }
  9901. var PDFJS = globalScope.PDFJS;
  9902. if (typeof pdfjsVersion !== 'undefined') {
  9903. PDFJS.version = pdfjsVersion;
  9904. }
  9905. if (typeof pdfjsBuild !== 'undefined') {
  9906. PDFJS.build = pdfjsBuild;
  9907. }
  9908. PDFJS.pdfBug = false;
  9909. if (PDFJS.verbosity !== undefined) {
  9910. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  9911. }
  9912. delete PDFJS.verbosity;
  9913. Object.defineProperty(PDFJS, 'verbosity', {
  9914. get: function () { return sharedUtil.getVerbosityLevel(); },
  9915. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  9920. PDFJS.OPS = sharedUtil.OPS;
  9921. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  9922. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  9923. PDFJS.shadow = sharedUtil.shadow;
  9924. PDFJS.createBlob = sharedUtil.createBlob;
  9925. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  9926. return sharedUtil.createObjectURL(data, contentType,
  9927. PDFJS.disableCreateObjectURL);
  9928. };
  9929. Object.defineProperty(PDFJS, 'isLittleEndian', {
  9930. configurable: true,
  9931. get: function PDFJS_isLittleEndian() {
  9932. var value = sharedUtil.isLittleEndian();
  9933. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  9934. }
  9935. });
  9936. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  9937. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  9938. PDFJS.PasswordException = sharedUtil.PasswordException;
  9939. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  9940. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  9941. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  9942. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  9943. PDFJS.Util = sharedUtil.Util;
  9944. PDFJS.PageViewport = sharedUtil.PageViewport;
  9945. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  9946. /**
  9947. * The maximum allowed image size in total pixels e.g. width * height. Images
  9948. * above this value will not be drawn. Use -1 for no limit.
  9949. * @var {number}
  9950. */
  9951. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  9952. -1 : PDFJS.maxImageSize);
  9953. /**
  9954. * The url of where the predefined Adobe CMaps are located. Include trailing
  9955. * slash.
  9956. * @var {string}
  9957. */
  9958. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  9959. /**
  9960. * Specifies if CMaps are binary packed.
  9961. * @var {boolean}
  9962. */
  9963. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  9964. /**
  9965. * By default fonts are converted to OpenType fonts and loaded via font face
  9966. * rules. If disabled, the font will be rendered using a built in font
  9967. * renderer that constructs the glyphs with primitive path commands.
  9968. * @var {boolean}
  9969. */
  9970. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  9971. false : PDFJS.disableFontFace);
  9972. /**
  9973. * Path for image resources, mainly for annotation icons. Include trailing
  9974. * slash.
  9975. * @var {string}
  9976. */
  9977. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  9978. '' : PDFJS.imageResourcesPath);
  9979. /**
  9980. * Disable the web worker and run all code on the main thread. This will
  9981. * happen automatically if the browser doesn't support workers or sending
  9982. * typed arrays to workers.
  9983. * @var {boolean}
  9984. */
  9985. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  9986. false : PDFJS.disableWorker);
  9987. /**
  9988. * Path and filename of the worker file. Required when the worker is enabled
  9989. * in development mode. If unspecified in the production build, the worker
  9990. * will be loaded based on the location of the pdf.js file. It is recommended
  9991. * that the workerSrc is set in a custom application to prevent issues caused
  9992. * by third-party frameworks and libraries.
  9993. * @var {string}
  9994. */
  9995. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  9996. /**
  9997. * Disable range request loading of PDF files. When enabled and if the server
  9998. * supports partial content requests then the PDF will be fetched in chunks.
  9999. * Enabled (false) by default.
  10000. * @var {boolean}
  10001. */
  10002. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  10003. false : PDFJS.disableRange);
  10004. /**
  10005. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10006. * in chunks. This default behavior can be disabled.
  10007. * @var {boolean}
  10008. */
  10009. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  10010. false : PDFJS.disableStream);
  10011. /**
  10012. * Disable pre-fetching of PDF file data. When range requests are enabled
  10013. * PDF.js will automatically keep fetching more data even if it isn't needed
  10014. * to display the current page. This default behavior can be disabled.
  10015. *
  10016. * NOTE: It is also necessary to disable streaming, see above,
  10017. * in order for disabling of pre-fetching to work correctly.
  10018. * @var {boolean}
  10019. */
  10020. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10021. false : PDFJS.disableAutoFetch);
  10022. /**
  10023. * Enables special hooks for debugging PDF.js.
  10024. * @var {boolean}
  10025. */
  10026. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10027. /**
  10028. * Enables transfer usage in postMessage for ArrayBuffers.
  10029. * @var {boolean}
  10030. */
  10031. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10032. true : PDFJS.postMessageTransfers);
  10033. /**
  10034. * Disables URL.createObjectURL usage.
  10035. * @var {boolean}
  10036. */
  10037. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10038. false : PDFJS.disableCreateObjectURL);
  10039. /**
  10040. * Disables WebGL usage.
  10041. * @var {boolean}
  10042. */
  10043. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10044. true : PDFJS.disableWebGL);
  10045. /**
  10046. * Specifies the |target| attribute for external links.
  10047. * The constants from PDFJS.LinkTarget should be used:
  10048. * - NONE [default]
  10049. * - SELF
  10050. * - BLANK
  10051. * - PARENT
  10052. * - TOP
  10053. * @var {number}
  10054. */
  10055. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10056. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10057. /**
  10058. * Specifies the |rel| attribute for external links. Defaults to stripping
  10059. * the referrer.
  10060. * @var {string}
  10061. */
  10062. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10063. 'noreferrer' : PDFJS.externalLinkRel);
  10064. /**
  10065. * Determines if we can eval strings as JS. Primarily used to improve
  10066. * performance for font rendering.
  10067. * @var {boolean}
  10068. */
  10069. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10070. true : PDFJS.isEvalSupported);
  10071. /**
  10072. * Renders interactive form elements.
  10073. * @var {boolean}
  10074. */
  10075. PDFJS.renderInteractiveForms = (PDFJS.renderInteractiveForms === undefined ?
  10076. false : PDFJS.renderInteractiveForms);
  10077. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10078. delete PDFJS.openExternalLinksInNewWindow;
  10079. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10080. get: function () {
  10081. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10082. },
  10083. set: function (value) {
  10084. if (value) {
  10085. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10086. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10087. }
  10088. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10089. warn('PDFJS.externalLinkTarget is already initialized');
  10090. return;
  10091. }
  10092. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. if (savedOpenExternalLinksInNewWindow) {
  10098. /**
  10099. * (Deprecated) Opens external links in a new window if enabled.
  10100. * The default behavior opens external links in the PDF.js window.
  10101. *
  10102. * NOTE: This property has been deprecated, please use
  10103. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10104. * @var {boolean}
  10105. */
  10106. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10107. }
  10108. PDFJS.getDocument = displayAPI.getDocument;
  10109. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10110. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10111. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10112. configurable: true,
  10113. get: function PDFJS_hasCanvasTypedArrays() {
  10114. var value = displayDOMUtils.hasCanvasTypedArrays();
  10115. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10116. }
  10117. });
  10118. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10119. PDFJS.LinkTarget = LinkTarget;
  10120. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10121. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10122. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10123. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10124. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10125. PDFJS.Metadata = displayMetadata.Metadata;
  10126. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10127. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10128. exports.globalScope = globalScope;
  10129. exports.isWorker = isWorker;
  10130. exports.PDFJS = globalScope.PDFJS;
  10131. }));
  10132. }).call(pdfjsLibs);
  10133. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10134. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10135. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10136. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10137. exports.PDFDataRangeTransport =
  10138. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10139. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10140. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10141. exports.AnnotationLayer =
  10142. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10143. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10144. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10145. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10146. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10147. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10148. exports.UnexpectedResponseException =
  10149. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10150. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10151. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10152. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10153. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10154. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10155. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10156. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10157. exports.getFilenameFromUrl =
  10158. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10159. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10160. }));