pdf.js 366 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503
  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.481';
  30. var pdfjsBuild = '431af8c';
  31. var pdfjsFilePath =
  32. typeof document !== 'undefined' && document.currentScript ?
  33. document.currentScript.src : null;
  34. var pdfjsLibs = {};
  35. (function pdfjsWrapper() {
  36. (function (root, factory) {
  37. {
  38. factory((root.pdfjsSharedUtil = {}));
  39. }
  40. }(this, function (exports) {
  41. var globalScope = (typeof window !== 'undefined') ? window :
  42. (typeof global !== 'undefined') ? global :
  43. (typeof self !== 'undefined') ? self : this;
  44. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  45. var TextRenderingMode = {
  46. FILL: 0,
  47. STROKE: 1,
  48. FILL_STROKE: 2,
  49. INVISIBLE: 3,
  50. FILL_ADD_TO_PATH: 4,
  51. STROKE_ADD_TO_PATH: 5,
  52. FILL_STROKE_ADD_TO_PATH: 6,
  53. ADD_TO_PATH: 7,
  54. FILL_STROKE_MASK: 3,
  55. ADD_TO_PATH_FLAG: 4
  56. };
  57. var ImageKind = {
  58. GRAYSCALE_1BPP: 1,
  59. RGB_24BPP: 2,
  60. RGBA_32BPP: 3
  61. };
  62. var AnnotationType = {
  63. TEXT: 1,
  64. LINK: 2,
  65. FREETEXT: 3,
  66. LINE: 4,
  67. SQUARE: 5,
  68. CIRCLE: 6,
  69. POLYGON: 7,
  70. POLYLINE: 8,
  71. HIGHLIGHT: 9,
  72. UNDERLINE: 10,
  73. SQUIGGLY: 11,
  74. STRIKEOUT: 12,
  75. STAMP: 13,
  76. CARET: 14,
  77. INK: 15,
  78. POPUP: 16,
  79. FILEATTACHMENT: 17,
  80. SOUND: 18,
  81. MOVIE: 19,
  82. WIDGET: 20,
  83. SCREEN: 21,
  84. PRINTERMARK: 22,
  85. TRAPNET: 23,
  86. WATERMARK: 24,
  87. THREED: 25,
  88. REDACT: 26
  89. };
  90. var AnnotationFlag = {
  91. INVISIBLE: 0x01,
  92. HIDDEN: 0x02,
  93. PRINT: 0x04,
  94. NOZOOM: 0x08,
  95. NOROTATE: 0x10,
  96. NOVIEW: 0x20,
  97. READONLY: 0x40,
  98. LOCKED: 0x80,
  99. TOGGLENOVIEW: 0x100,
  100. LOCKEDCONTENTS: 0x200
  101. };
  102. var AnnotationFieldFlag = {
  103. READONLY: 1,
  104. REQUIRED: 2,
  105. NOEXPORT: 3,
  106. MULTILINE: 13,
  107. PASSWORD: 14,
  108. NOTOGGLETOOFF: 15,
  109. RADIO: 16,
  110. PUSHBUTTON: 17,
  111. COMBO: 18,
  112. EDIT: 19,
  113. SORT: 20,
  114. FILESELECT: 21,
  115. MULTISELECT: 22,
  116. DONOTSPELLCHECK: 23,
  117. DONOTSCROLL: 24,
  118. COMB: 25,
  119. RICHTEXT: 26,
  120. RADIOSINUNISON: 26,
  121. COMMITONSELCHANGE: 27,
  122. };
  123. var AnnotationBorderStyleType = {
  124. SOLID: 1,
  125. DASHED: 2,
  126. BEVELED: 3,
  127. INSET: 4,
  128. UNDERLINE: 5
  129. };
  130. var StreamType = {
  131. UNKNOWN: 0,
  132. FLATE: 1,
  133. LZW: 2,
  134. DCT: 3,
  135. JPX: 4,
  136. JBIG: 5,
  137. A85: 6,
  138. AHX: 7,
  139. CCF: 8,
  140. RL: 9
  141. };
  142. var FontType = {
  143. UNKNOWN: 0,
  144. TYPE1: 1,
  145. TYPE1C: 2,
  146. CIDFONTTYPE0: 3,
  147. CIDFONTTYPE0C: 4,
  148. TRUETYPE: 5,
  149. CIDFONTTYPE2: 6,
  150. TYPE3: 7,
  151. OPENTYPE: 8,
  152. TYPE0: 9,
  153. MMTYPE1: 10
  154. };
  155. var VERBOSITY_LEVELS = {
  156. errors: 0,
  157. warnings: 1,
  158. infos: 5
  159. };
  160. // All the possible operations for an operator list.
  161. var OPS = {
  162. // Intentionally start from 1 so it is easy to spot bad operators that will be
  163. // 0's.
  164. dependency: 1,
  165. setLineWidth: 2,
  166. setLineCap: 3,
  167. setLineJoin: 4,
  168. setMiterLimit: 5,
  169. setDash: 6,
  170. setRenderingIntent: 7,
  171. setFlatness: 8,
  172. setGState: 9,
  173. save: 10,
  174. restore: 11,
  175. transform: 12,
  176. moveTo: 13,
  177. lineTo: 14,
  178. curveTo: 15,
  179. curveTo2: 16,
  180. curveTo3: 17,
  181. closePath: 18,
  182. rectangle: 19,
  183. stroke: 20,
  184. closeStroke: 21,
  185. fill: 22,
  186. eoFill: 23,
  187. fillStroke: 24,
  188. eoFillStroke: 25,
  189. closeFillStroke: 26,
  190. closeEOFillStroke: 27,
  191. endPath: 28,
  192. clip: 29,
  193. eoClip: 30,
  194. beginText: 31,
  195. endText: 32,
  196. setCharSpacing: 33,
  197. setWordSpacing: 34,
  198. setHScale: 35,
  199. setLeading: 36,
  200. setFont: 37,
  201. setTextRenderingMode: 38,
  202. setTextRise: 39,
  203. moveText: 40,
  204. setLeadingMoveText: 41,
  205. setTextMatrix: 42,
  206. nextLine: 43,
  207. showText: 44,
  208. showSpacedText: 45,
  209. nextLineShowText: 46,
  210. nextLineSetSpacingShowText: 47,
  211. setCharWidth: 48,
  212. setCharWidthAndBounds: 49,
  213. setStrokeColorSpace: 50,
  214. setFillColorSpace: 51,
  215. setStrokeColor: 52,
  216. setStrokeColorN: 53,
  217. setFillColor: 54,
  218. setFillColorN: 55,
  219. setStrokeGray: 56,
  220. setFillGray: 57,
  221. setStrokeRGBColor: 58,
  222. setFillRGBColor: 59,
  223. setStrokeCMYKColor: 60,
  224. setFillCMYKColor: 61,
  225. shadingFill: 62,
  226. beginInlineImage: 63,
  227. beginImageData: 64,
  228. endInlineImage: 65,
  229. paintXObject: 66,
  230. markPoint: 67,
  231. markPointProps: 68,
  232. beginMarkedContent: 69,
  233. beginMarkedContentProps: 70,
  234. endMarkedContent: 71,
  235. beginCompat: 72,
  236. endCompat: 73,
  237. paintFormXObjectBegin: 74,
  238. paintFormXObjectEnd: 75,
  239. beginGroup: 76,
  240. endGroup: 77,
  241. beginAnnotations: 78,
  242. endAnnotations: 79,
  243. beginAnnotation: 80,
  244. endAnnotation: 81,
  245. paintJpegXObject: 82,
  246. paintImageMaskXObject: 83,
  247. paintImageMaskXObjectGroup: 84,
  248. paintImageXObject: 85,
  249. paintInlineImageXObject: 86,
  250. paintInlineImageXObjectGroup: 87,
  251. paintImageXObjectRepeat: 88,
  252. paintImageMaskXObjectRepeat: 89,
  253. paintSolidColorImageMask: 90,
  254. constructPath: 91
  255. };
  256. var verbosity = VERBOSITY_LEVELS.warnings;
  257. function setVerbosityLevel(level) {
  258. verbosity = level;
  259. }
  260. function getVerbosityLevel() {
  261. return verbosity;
  262. }
  263. // A notice for devs. These are good for things that are helpful to devs, such
  264. // as warning that Workers were disabled, which is important to devs but not
  265. // end users.
  266. function info(msg) {
  267. if (verbosity >= VERBOSITY_LEVELS.infos) {
  268. console.log('Info: ' + msg);
  269. }
  270. }
  271. // Non-fatal warnings.
  272. function warn(msg) {
  273. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  274. console.log('Warning: ' + msg);
  275. }
  276. }
  277. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  278. function deprecated(details) {
  279. console.log('Deprecated API usage: ' + details);
  280. }
  281. // Fatal errors that should trigger the fallback UI and halt execution by
  282. // throwing an exception.
  283. function error(msg) {
  284. if (verbosity >= VERBOSITY_LEVELS.errors) {
  285. console.log('Error: ' + msg);
  286. console.log(backtrace());
  287. }
  288. throw new Error(msg);
  289. }
  290. function backtrace() {
  291. try {
  292. throw new Error();
  293. } catch (e) {
  294. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  295. }
  296. }
  297. function assert(cond, msg) {
  298. if (!cond) {
  299. error(msg);
  300. }
  301. }
  302. var UNSUPPORTED_FEATURES = {
  303. unknown: 'unknown',
  304. forms: 'forms',
  305. javaScript: 'javaScript',
  306. smask: 'smask',
  307. shadingPattern: 'shadingPattern',
  308. font: 'font'
  309. };
  310. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  311. function isSameOrigin(baseUrl, otherUrl) {
  312. try {
  313. var base = new URL(baseUrl);
  314. if (!base.origin || base.origin === 'null') {
  315. return false; // non-HTTP url
  316. }
  317. } catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  324. function isValidUrl(url, allowRelative) {
  325. if (!url || typeof url !== 'string') {
  326. return false;
  327. }
  328. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  329. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  330. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  331. if (!protocol) {
  332. return allowRelative;
  333. }
  334. protocol = protocol[0].toLowerCase();
  335. switch (protocol) {
  336. case 'http':
  337. case 'https':
  338. case 'ftp':
  339. case 'mailto':
  340. case 'tel':
  341. return true;
  342. default:
  343. return false;
  344. }
  345. }
  346. function shadow(obj, prop, value) {
  347. Object.defineProperty(obj, prop, { value: value,
  348. enumerable: true,
  349. configurable: true,
  350. writable: false });
  351. return value;
  352. }
  353. function getLookupTableFactory(initializer) {
  354. var lookup;
  355. return function () {
  356. if (initializer) {
  357. lookup = Object.create(null);
  358. initializer(lookup);
  359. initializer = null;
  360. }
  361. return lookup;
  362. };
  363. }
  364. var PasswordResponses = {
  365. NEED_PASSWORD: 1,
  366. INCORRECT_PASSWORD: 2
  367. };
  368. var PasswordException = (function PasswordExceptionClosure() {
  369. function PasswordException(msg, code) {
  370. this.name = 'PasswordException';
  371. this.message = msg;
  372. this.code = code;
  373. }
  374. PasswordException.prototype = new Error();
  375. PasswordException.constructor = PasswordException;
  376. return PasswordException;
  377. })();
  378. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  379. function UnknownErrorException(msg, details) {
  380. this.name = 'UnknownErrorException';
  381. this.message = msg;
  382. this.details = details;
  383. }
  384. UnknownErrorException.prototype = new Error();
  385. UnknownErrorException.constructor = UnknownErrorException;
  386. return UnknownErrorException;
  387. })();
  388. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  389. function InvalidPDFException(msg) {
  390. this.name = 'InvalidPDFException';
  391. this.message = msg;
  392. }
  393. InvalidPDFException.prototype = new Error();
  394. InvalidPDFException.constructor = InvalidPDFException;
  395. return InvalidPDFException;
  396. })();
  397. var MissingPDFException = (function MissingPDFExceptionClosure() {
  398. function MissingPDFException(msg) {
  399. this.name = 'MissingPDFException';
  400. this.message = msg;
  401. }
  402. MissingPDFException.prototype = new Error();
  403. MissingPDFException.constructor = MissingPDFException;
  404. return MissingPDFException;
  405. })();
  406. var UnexpectedResponseException =
  407. (function UnexpectedResponseExceptionClosure() {
  408. function UnexpectedResponseException(msg, status) {
  409. this.name = 'UnexpectedResponseException';
  410. this.message = msg;
  411. this.status = status;
  412. }
  413. UnexpectedResponseException.prototype = new Error();
  414. UnexpectedResponseException.constructor = UnexpectedResponseException;
  415. return UnexpectedResponseException;
  416. })();
  417. var NotImplementedException = (function NotImplementedExceptionClosure() {
  418. function NotImplementedException(msg) {
  419. this.message = msg;
  420. }
  421. NotImplementedException.prototype = new Error();
  422. NotImplementedException.prototype.name = 'NotImplementedException';
  423. NotImplementedException.constructor = NotImplementedException;
  424. return NotImplementedException;
  425. })();
  426. var MissingDataException = (function MissingDataExceptionClosure() {
  427. function MissingDataException(begin, end) {
  428. this.begin = begin;
  429. this.end = end;
  430. this.message = 'Missing data [' + begin + ', ' + end + ')';
  431. }
  432. MissingDataException.prototype = new Error();
  433. MissingDataException.prototype.name = 'MissingDataException';
  434. MissingDataException.constructor = MissingDataException;
  435. return MissingDataException;
  436. })();
  437. var XRefParseException = (function XRefParseExceptionClosure() {
  438. function XRefParseException(msg) {
  439. this.message = msg;
  440. }
  441. XRefParseException.prototype = new Error();
  442. XRefParseException.prototype.name = 'XRefParseException';
  443. XRefParseException.constructor = XRefParseException;
  444. return XRefParseException;
  445. })();
  446. var NullCharactersRegExp = /\x00/g;
  447. function removeNullCharacters(str) {
  448. if (typeof str !== 'string') {
  449. warn('The argument for removeNullCharacters must be a string.');
  450. return str;
  451. }
  452. return str.replace(NullCharactersRegExp, '');
  453. }
  454. function bytesToString(bytes) {
  455. assert(bytes !== null && typeof bytes === 'object' &&
  456. bytes.length !== undefined, 'Invalid argument for bytesToString');
  457. var length = bytes.length;
  458. var MAX_ARGUMENT_COUNT = 8192;
  459. if (length < MAX_ARGUMENT_COUNT) {
  460. return String.fromCharCode.apply(null, bytes);
  461. }
  462. var strBuf = [];
  463. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  464. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  465. var chunk = bytes.subarray(i, chunkEnd);
  466. strBuf.push(String.fromCharCode.apply(null, chunk));
  467. }
  468. return strBuf.join('');
  469. }
  470. function stringToBytes(str) {
  471. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  472. var length = str.length;
  473. var bytes = new Uint8Array(length);
  474. for (var i = 0; i < length; ++i) {
  475. bytes[i] = str.charCodeAt(i) & 0xFF;
  476. }
  477. return bytes;
  478. }
  479. /**
  480. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  481. * @param {Array|Uint8Array|string} arr
  482. * @returns {number}
  483. */
  484. function arrayByteLength(arr) {
  485. if (arr.length !== undefined) {
  486. return arr.length;
  487. }
  488. assert(arr.byteLength !== undefined);
  489. return arr.byteLength;
  490. }
  491. /**
  492. * Combines array items (arrays) into single Uint8Array object.
  493. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  494. * @returns {Uint8Array}
  495. */
  496. function arraysToBytes(arr) {
  497. // Shortcut: if first and only item is Uint8Array, return it.
  498. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) {
  499. return arr[0];
  500. }
  501. var resultLength = 0;
  502. var i, ii = arr.length;
  503. var item, itemLength ;
  504. for (i = 0; i < ii; i++) {
  505. item = arr[i];
  506. itemLength = arrayByteLength(item);
  507. resultLength += itemLength;
  508. }
  509. var pos = 0;
  510. var data = new Uint8Array(resultLength);
  511. for (i = 0; i < ii; i++) {
  512. item = arr[i];
  513. if (!(item instanceof Uint8Array)) {
  514. if (typeof item === 'string') {
  515. item = stringToBytes(item);
  516. } else {
  517. item = new Uint8Array(item);
  518. }
  519. }
  520. itemLength = item.byteLength;
  521. data.set(item, pos);
  522. pos += itemLength;
  523. }
  524. return data;
  525. }
  526. function string32(value) {
  527. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  528. (value >> 8) & 0xff, value & 0xff);
  529. }
  530. function log2(x) {
  531. var n = 1, i = 0;
  532. while (x > n) {
  533. n <<= 1;
  534. i++;
  535. }
  536. return i;
  537. }
  538. function readInt8(data, start) {
  539. return (data[start] << 24) >> 24;
  540. }
  541. function readUint16(data, offset) {
  542. return (data[offset] << 8) | data[offset + 1];
  543. }
  544. function readUint32(data, offset) {
  545. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  546. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  547. }
  548. // Lazy test the endianness of the platform
  549. // NOTE: This will be 'true' for simulated TypedArrays
  550. function isLittleEndian() {
  551. var buffer8 = new Uint8Array(2);
  552. buffer8[0] = 1;
  553. var buffer16 = new Uint16Array(buffer8.buffer);
  554. return (buffer16[0] === 1);
  555. }
  556. // Checks if it's possible to eval JS expressions.
  557. function isEvalSupported() {
  558. try {
  559. /* jshint evil: true */
  560. new Function('');
  561. return true;
  562. } catch (e) {
  563. return false;
  564. }
  565. }
  566. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  567. function Uint32ArrayView(buffer, length) {
  568. this.buffer = buffer;
  569. this.byteLength = buffer.length;
  570. this.length = length === undefined ? (this.byteLength >> 2) : length;
  571. ensureUint32ArrayViewProps(this.length);
  572. }
  573. Uint32ArrayView.prototype = Object.create(null);
  574. var uint32ArrayViewSetters = 0;
  575. function createUint32ArrayProp(index) {
  576. return {
  577. get: function () {
  578. var buffer = this.buffer, offset = index << 2;
  579. return (buffer[offset] | (buffer[offset + 1] << 8) |
  580. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  581. },
  582. set: function (value) {
  583. var buffer = this.buffer, offset = index << 2;
  584. buffer[offset] = value & 255;
  585. buffer[offset + 1] = (value >> 8) & 255;
  586. buffer[offset + 2] = (value >> 16) & 255;
  587. buffer[offset + 3] = (value >>> 24) & 255;
  588. }
  589. };
  590. }
  591. function ensureUint32ArrayViewProps(length) {
  592. while (uint32ArrayViewSetters < length) {
  593. Object.defineProperty(Uint32ArrayView.prototype,
  594. uint32ArrayViewSetters,
  595. createUint32ArrayProp(uint32ArrayViewSetters));
  596. uint32ArrayViewSetters++;
  597. }
  598. }
  599. return Uint32ArrayView;
  600. })();
  601. exports.Uint32ArrayView = Uint32ArrayView;
  602. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  603. var Util = (function UtilClosure() {
  604. function Util() {}
  605. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  606. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  607. // creating many intermediate strings.
  608. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  609. rgbBuf[1] = r;
  610. rgbBuf[3] = g;
  611. rgbBuf[5] = b;
  612. return rgbBuf.join('');
  613. };
  614. // Concatenates two transformation matrices together and returns the result.
  615. Util.transform = function Util_transform(m1, m2) {
  616. return [
  617. m1[0] * m2[0] + m1[2] * m2[1],
  618. m1[1] * m2[0] + m1[3] * m2[1],
  619. m1[0] * m2[2] + m1[2] * m2[3],
  620. m1[1] * m2[2] + m1[3] * m2[3],
  621. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  622. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  623. ];
  624. };
  625. // For 2d affine transforms
  626. Util.applyTransform = function Util_applyTransform(p, m) {
  627. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  628. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  629. return [xt, yt];
  630. };
  631. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  632. var d = m[0] * m[3] - m[1] * m[2];
  633. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  634. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  635. return [xt, yt];
  636. };
  637. // Applies the transform to the rectangle and finds the minimum axially
  638. // aligned bounding box.
  639. Util.getAxialAlignedBoundingBox =
  640. function Util_getAxialAlignedBoundingBox(r, m) {
  641. var p1 = Util.applyTransform(r, m);
  642. var p2 = Util.applyTransform(r.slice(2, 4), m);
  643. var p3 = Util.applyTransform([r[0], r[3]], m);
  644. var p4 = Util.applyTransform([r[2], r[1]], m);
  645. return [
  646. Math.min(p1[0], p2[0], p3[0], p4[0]),
  647. Math.min(p1[1], p2[1], p3[1], p4[1]),
  648. Math.max(p1[0], p2[0], p3[0], p4[0]),
  649. Math.max(p1[1], p2[1], p3[1], p4[1])
  650. ];
  651. };
  652. Util.inverseTransform = function Util_inverseTransform(m) {
  653. var d = m[0] * m[3] - m[1] * m[2];
  654. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  655. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  656. };
  657. // Apply a generic 3d matrix M on a 3-vector v:
  658. // | a b c | | X |
  659. // | d e f | x | Y |
  660. // | g h i | | Z |
  661. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  662. // with v as [X,Y,Z]
  663. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  664. return [
  665. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  666. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  667. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  668. ];
  669. };
  670. // This calculation uses Singular Value Decomposition.
  671. // The SVD can be represented with formula A = USV. We are interested in the
  672. // matrix S here because it represents the scale values.
  673. Util.singularValueDecompose2dScale =
  674. function Util_singularValueDecompose2dScale(m) {
  675. var transpose = [m[0], m[2], m[1], m[3]];
  676. // Multiply matrix m with its transpose.
  677. var a = m[0] * transpose[0] + m[1] * transpose[2];
  678. var b = m[0] * transpose[1] + m[1] * transpose[3];
  679. var c = m[2] * transpose[0] + m[3] * transpose[2];
  680. var d = m[2] * transpose[1] + m[3] * transpose[3];
  681. // Solve the second degree polynomial to get roots.
  682. var first = (a + d) / 2;
  683. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  684. var sx = first + second || 1;
  685. var sy = first - second || 1;
  686. // Scale values are the square roots of the eigenvalues.
  687. return [Math.sqrt(sx), Math.sqrt(sy)];
  688. };
  689. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  690. // For coordinate systems whose origin lies in the bottom-left, this
  691. // means normalization to (BL,TR) ordering. For systems with origin in the
  692. // top-left, this means (TL,BR) ordering.
  693. Util.normalizeRect = function Util_normalizeRect(rect) {
  694. var r = rect.slice(0); // clone rect
  695. if (rect[0] > rect[2]) {
  696. r[0] = rect[2];
  697. r[2] = rect[0];
  698. }
  699. if (rect[1] > rect[3]) {
  700. r[1] = rect[3];
  701. r[3] = rect[1];
  702. }
  703. return r;
  704. };
  705. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  706. // intersection of rect1 and rect2. If no intersection, returns 'false'
  707. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  708. Util.intersect = function Util_intersect(rect1, rect2) {
  709. function compare(a, b) {
  710. return a - b;
  711. }
  712. // Order points along the axes
  713. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  714. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  715. result = [];
  716. rect1 = Util.normalizeRect(rect1);
  717. rect2 = Util.normalizeRect(rect2);
  718. // X: first and second points belong to different rectangles?
  719. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  720. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  721. // Intersection must be between second and third points
  722. result[0] = orderedX[1];
  723. result[2] = orderedX[2];
  724. } else {
  725. return false;
  726. }
  727. // Y: first and second points belong to different rectangles?
  728. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  729. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  730. // Intersection must be between second and third points
  731. result[1] = orderedY[1];
  732. result[3] = orderedY[2];
  733. } else {
  734. return false;
  735. }
  736. return result;
  737. };
  738. Util.sign = function Util_sign(num) {
  739. return num < 0 ? -1 : 1;
  740. };
  741. var ROMAN_NUMBER_MAP = [
  742. '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  743. '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  744. '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
  745. ];
  746. /**
  747. * Converts positive integers to (upper case) Roman numerals.
  748. * @param {integer} number - The number that should be converted.
  749. * @param {boolean} lowerCase - Indicates if the result should be converted
  750. * to lower case letters. The default is false.
  751. * @return {string} The resulting Roman number.
  752. */
  753. Util.toRoman = function Util_toRoman(number, lowerCase) {
  754. assert(isInt(number) && number > 0,
  755. 'The number should be a positive integer.');
  756. var pos, romanBuf = [];
  757. // Thousands
  758. while (number >= 1000) {
  759. number -= 1000;
  760. romanBuf.push('M');
  761. }
  762. // Hundreds
  763. pos = (number / 100) | 0;
  764. number %= 100;
  765. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  766. // Tens
  767. pos = (number / 10) | 0;
  768. number %= 10;
  769. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  770. // Ones
  771. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  772. var romanStr = romanBuf.join('');
  773. return (lowerCase ? romanStr.toLowerCase() : romanStr);
  774. };
  775. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  776. Array.prototype.push.apply(arr1, arr2);
  777. };
  778. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  779. Array.prototype.unshift.apply(arr1, arr2);
  780. };
  781. Util.extendObj = function extendObj(obj1, obj2) {
  782. for (var key in obj2) {
  783. obj1[key] = obj2[key];
  784. }
  785. };
  786. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  787. name) {
  788. while (dict && !dict.has(name)) {
  789. dict = dict.get('Parent');
  790. }
  791. if (!dict) {
  792. return null;
  793. }
  794. return dict.get(name);
  795. };
  796. Util.inherit = function Util_inherit(sub, base, prototype) {
  797. sub.prototype = Object.create(base.prototype);
  798. sub.prototype.constructor = sub;
  799. for (var prop in prototype) {
  800. sub.prototype[prop] = prototype[prop];
  801. }
  802. };
  803. Util.loadScript = function Util_loadScript(src, callback) {
  804. var script = document.createElement('script');
  805. var loaded = false;
  806. script.setAttribute('src', src);
  807. if (callback) {
  808. script.onload = function() {
  809. if (!loaded) {
  810. callback();
  811. }
  812. loaded = true;
  813. };
  814. }
  815. document.getElementsByTagName('head')[0].appendChild(script);
  816. };
  817. return Util;
  818. })();
  819. /**
  820. * PDF page viewport created based on scale, rotation and offset.
  821. * @class
  822. * @alias PageViewport
  823. */
  824. var PageViewport = (function PageViewportClosure() {
  825. /**
  826. * @constructor
  827. * @private
  828. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  829. * @param scale {number} scale of the viewport.
  830. * @param rotation {number} rotations of the viewport in degrees.
  831. * @param offsetX {number} offset X
  832. * @param offsetY {number} offset Y
  833. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  834. */
  835. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  836. this.viewBox = viewBox;
  837. this.scale = scale;
  838. this.rotation = rotation;
  839. this.offsetX = offsetX;
  840. this.offsetY = offsetY;
  841. // creating transform to convert pdf coordinate system to the normal
  842. // canvas like coordinates taking in account scale and rotation
  843. var centerX = (viewBox[2] + viewBox[0]) / 2;
  844. var centerY = (viewBox[3] + viewBox[1]) / 2;
  845. var rotateA, rotateB, rotateC, rotateD;
  846. rotation = rotation % 360;
  847. rotation = rotation < 0 ? rotation + 360 : rotation;
  848. switch (rotation) {
  849. case 180:
  850. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  851. break;
  852. case 90:
  853. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  854. break;
  855. case 270:
  856. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  857. break;
  858. //case 0:
  859. default:
  860. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  861. break;
  862. }
  863. if (dontFlip) {
  864. rotateC = -rotateC; rotateD = -rotateD;
  865. }
  866. var offsetCanvasX, offsetCanvasY;
  867. var width, height;
  868. if (rotateA === 0) {
  869. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  870. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  871. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  872. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  873. } else {
  874. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  875. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  876. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  877. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  878. }
  879. // creating transform for the following operations:
  880. // translate(-centerX, -centerY), rotate and flip vertically,
  881. // scale, and translate(offsetCanvasX, offsetCanvasY)
  882. this.transform = [
  883. rotateA * scale,
  884. rotateB * scale,
  885. rotateC * scale,
  886. rotateD * scale,
  887. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  888. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  889. ];
  890. this.width = width;
  891. this.height = height;
  892. this.fontScale = scale;
  893. }
  894. PageViewport.prototype = /** @lends PageViewport.prototype */ {
  895. /**
  896. * Clones viewport with additional properties.
  897. * @param args {Object} (optional) If specified, may contain the 'scale' or
  898. * 'rotation' properties to override the corresponding properties in
  899. * the cloned viewport.
  900. * @returns {PageViewport} Cloned viewport.
  901. */
  902. clone: function PageViewPort_clone(args) {
  903. args = args || {};
  904. var scale = 'scale' in args ? args.scale : this.scale;
  905. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  906. return new PageViewport(this.viewBox.slice(), scale, rotation,
  907. this.offsetX, this.offsetY, args.dontFlip);
  908. },
  909. /**
  910. * Converts PDF point to the viewport coordinates. For examples, useful for
  911. * converting PDF location into canvas pixel coordinates.
  912. * @param x {number} X coordinate.
  913. * @param y {number} Y coordinate.
  914. * @returns {Object} Object that contains 'x' and 'y' properties of the
  915. * point in the viewport coordinate space.
  916. * @see {@link convertToPdfPoint}
  917. * @see {@link convertToViewportRectangle}
  918. */
  919. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  920. return Util.applyTransform([x, y], this.transform);
  921. },
  922. /**
  923. * Converts PDF rectangle to the viewport coordinates.
  924. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  925. * @returns {Array} Contains corresponding coordinates of the rectangle
  926. * in the viewport coordinate space.
  927. * @see {@link convertToViewportPoint}
  928. */
  929. convertToViewportRectangle:
  930. function PageViewport_convertToViewportRectangle(rect) {
  931. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  932. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  933. return [tl[0], tl[1], br[0], br[1]];
  934. },
  935. /**
  936. * Converts viewport coordinates to the PDF location. For examples, useful
  937. * for converting canvas pixel location into PDF one.
  938. * @param x {number} X coordinate.
  939. * @param y {number} Y coordinate.
  940. * @returns {Object} Object that contains 'x' and 'y' properties of the
  941. * point in the PDF coordinate space.
  942. * @see {@link convertToViewportPoint}
  943. */
  944. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  945. return Util.applyInverseTransform([x, y], this.transform);
  946. }
  947. };
  948. return PageViewport;
  949. })();
  950. var PDFStringTranslateTable = [
  951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  952. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  957. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  958. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  959. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  960. ];
  961. function stringToPDFString(str) {
  962. var i, n = str.length, strBuf = [];
  963. if (str[0] === '\xFE' && str[1] === '\xFF') {
  964. // UTF16BE BOM
  965. for (i = 2; i < n; i += 2) {
  966. strBuf.push(String.fromCharCode(
  967. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  968. }
  969. } else {
  970. for (i = 0; i < n; ++i) {
  971. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  972. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  973. }
  974. }
  975. return strBuf.join('');
  976. }
  977. function stringToUTF8String(str) {
  978. return decodeURIComponent(escape(str));
  979. }
  980. function utf8StringToString(str) {
  981. return unescape(encodeURIComponent(str));
  982. }
  983. function isEmptyObj(obj) {
  984. for (var key in obj) {
  985. return false;
  986. }
  987. return true;
  988. }
  989. function isBool(v) {
  990. return typeof v === 'boolean';
  991. }
  992. function isInt(v) {
  993. return typeof v === 'number' && ((v | 0) === v);
  994. }
  995. function isNum(v) {
  996. return typeof v === 'number';
  997. }
  998. function isString(v) {
  999. return typeof v === 'string';
  1000. }
  1001. function isArray(v) {
  1002. return v instanceof Array;
  1003. }
  1004. function isArrayBuffer(v) {
  1005. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1006. }
  1007. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1008. function isSpace(ch) {
  1009. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  1010. }
  1011. /**
  1012. * Promise Capability object.
  1013. *
  1014. * @typedef {Object} PromiseCapability
  1015. * @property {Promise} promise - A promise object.
  1016. * @property {function} resolve - Fulfills the promise.
  1017. * @property {function} reject - Rejects the promise.
  1018. */
  1019. /**
  1020. * Creates a promise capability object.
  1021. * @alias createPromiseCapability
  1022. *
  1023. * @return {PromiseCapability} A capability object contains:
  1024. * - a Promise, resolve and reject methods.
  1025. */
  1026. function createPromiseCapability() {
  1027. var capability = {};
  1028. capability.promise = new Promise(function (resolve, reject) {
  1029. capability.resolve = resolve;
  1030. capability.reject = reject;
  1031. });
  1032. return capability;
  1033. }
  1034. /**
  1035. * Polyfill for Promises:
  1036. * The following promise implementation tries to generally implement the
  1037. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1038. * - There currently isn't a separate deferred and promise object.
  1039. * - Unhandled rejections eventually show an error if they aren't handled.
  1040. *
  1041. * Based off of the work in:
  1042. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1043. */
  1044. (function PromiseClosure() {
  1045. if (globalScope.Promise) {
  1046. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1047. if (typeof globalScope.Promise.all !== 'function') {
  1048. globalScope.Promise.all = function (iterable) {
  1049. var count = 0, results = [], resolve, reject;
  1050. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1051. resolve = resolve_;
  1052. reject = reject_;
  1053. });
  1054. iterable.forEach(function (p, i) {
  1055. count++;
  1056. p.then(function (result) {
  1057. results[i] = result;
  1058. count--;
  1059. if (count === 0) {
  1060. resolve(results);
  1061. }
  1062. }, reject);
  1063. });
  1064. if (count === 0) {
  1065. resolve(results);
  1066. }
  1067. return promise;
  1068. };
  1069. }
  1070. if (typeof globalScope.Promise.resolve !== 'function') {
  1071. globalScope.Promise.resolve = function (value) {
  1072. return new globalScope.Promise(function (resolve) { resolve(value); });
  1073. };
  1074. }
  1075. if (typeof globalScope.Promise.reject !== 'function') {
  1076. globalScope.Promise.reject = function (reason) {
  1077. return new globalScope.Promise(function (resolve, reject) {
  1078. reject(reason);
  1079. });
  1080. };
  1081. }
  1082. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1083. globalScope.Promise.prototype.catch = function (onReject) {
  1084. return globalScope.Promise.prototype.then(undefined, onReject);
  1085. };
  1086. }
  1087. return;
  1088. }
  1089. var STATUS_PENDING = 0;
  1090. var STATUS_RESOLVED = 1;
  1091. var STATUS_REJECTED = 2;
  1092. // In an attempt to avoid silent exceptions, unhandled rejections are
  1093. // tracked and if they aren't handled in a certain amount of time an
  1094. // error is logged.
  1095. var REJECTION_TIMEOUT = 500;
  1096. var HandlerManager = {
  1097. handlers: [],
  1098. running: false,
  1099. unhandledRejections: [],
  1100. pendingRejectionCheck: false,
  1101. scheduleHandlers: function scheduleHandlers(promise) {
  1102. if (promise._status === STATUS_PENDING) {
  1103. return;
  1104. }
  1105. this.handlers = this.handlers.concat(promise._handlers);
  1106. promise._handlers = [];
  1107. if (this.running) {
  1108. return;
  1109. }
  1110. this.running = true;
  1111. setTimeout(this.runHandlers.bind(this), 0);
  1112. },
  1113. runHandlers: function runHandlers() {
  1114. var RUN_TIMEOUT = 1; // ms
  1115. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1116. while (this.handlers.length > 0) {
  1117. var handler = this.handlers.shift();
  1118. var nextStatus = handler.thisPromise._status;
  1119. var nextValue = handler.thisPromise._value;
  1120. try {
  1121. if (nextStatus === STATUS_RESOLVED) {
  1122. if (typeof handler.onResolve === 'function') {
  1123. nextValue = handler.onResolve(nextValue);
  1124. }
  1125. } else if (typeof handler.onReject === 'function') {
  1126. nextValue = handler.onReject(nextValue);
  1127. nextStatus = STATUS_RESOLVED;
  1128. if (handler.thisPromise._unhandledRejection) {
  1129. this.removeUnhandeledRejection(handler.thisPromise);
  1130. }
  1131. }
  1132. } catch (ex) {
  1133. nextStatus = STATUS_REJECTED;
  1134. nextValue = ex;
  1135. }
  1136. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1137. if (Date.now() >= timeoutAt) {
  1138. break;
  1139. }
  1140. }
  1141. if (this.handlers.length > 0) {
  1142. setTimeout(this.runHandlers.bind(this), 0);
  1143. return;
  1144. }
  1145. this.running = false;
  1146. },
  1147. addUnhandledRejection: function addUnhandledRejection(promise) {
  1148. this.unhandledRejections.push({
  1149. promise: promise,
  1150. time: Date.now()
  1151. });
  1152. this.scheduleRejectionCheck();
  1153. },
  1154. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1155. promise._unhandledRejection = false;
  1156. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1157. if (this.unhandledRejections[i].promise === promise) {
  1158. this.unhandledRejections.splice(i);
  1159. i--;
  1160. }
  1161. }
  1162. },
  1163. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1164. if (this.pendingRejectionCheck) {
  1165. return;
  1166. }
  1167. this.pendingRejectionCheck = true;
  1168. setTimeout(function rejectionCheck() {
  1169. this.pendingRejectionCheck = false;
  1170. var now = Date.now();
  1171. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1172. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1173. var unhandled = this.unhandledRejections[i].promise._value;
  1174. var msg = 'Unhandled rejection: ' + unhandled;
  1175. if (unhandled.stack) {
  1176. msg += '\n' + unhandled.stack;
  1177. }
  1178. warn(msg);
  1179. this.unhandledRejections.splice(i);
  1180. i--;
  1181. }
  1182. }
  1183. if (this.unhandledRejections.length) {
  1184. this.scheduleRejectionCheck();
  1185. }
  1186. }.bind(this), REJECTION_TIMEOUT);
  1187. }
  1188. };
  1189. function Promise(resolver) {
  1190. this._status = STATUS_PENDING;
  1191. this._handlers = [];
  1192. try {
  1193. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1194. } catch (e) {
  1195. this._reject(e);
  1196. }
  1197. }
  1198. /**
  1199. * Builds a promise that is resolved when all the passed in promises are
  1200. * resolved.
  1201. * @param {array} promises array of data and/or promises to wait for.
  1202. * @return {Promise} New dependent promise.
  1203. */
  1204. Promise.all = function Promise_all(promises) {
  1205. var resolveAll, rejectAll;
  1206. var deferred = new Promise(function (resolve, reject) {
  1207. resolveAll = resolve;
  1208. rejectAll = reject;
  1209. });
  1210. var unresolved = promises.length;
  1211. var results = [];
  1212. if (unresolved === 0) {
  1213. resolveAll(results);
  1214. return deferred;
  1215. }
  1216. function reject(reason) {
  1217. if (deferred._status === STATUS_REJECTED) {
  1218. return;
  1219. }
  1220. results = [];
  1221. rejectAll(reason);
  1222. }
  1223. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1224. var promise = promises[i];
  1225. var resolve = (function(i) {
  1226. return function(value) {
  1227. if (deferred._status === STATUS_REJECTED) {
  1228. return;
  1229. }
  1230. results[i] = value;
  1231. unresolved--;
  1232. if (unresolved === 0) {
  1233. resolveAll(results);
  1234. }
  1235. };
  1236. })(i);
  1237. if (Promise.isPromise(promise)) {
  1238. promise.then(resolve, reject);
  1239. } else {
  1240. resolve(promise);
  1241. }
  1242. }
  1243. return deferred;
  1244. };
  1245. /**
  1246. * Checks if the value is likely a promise (has a 'then' function).
  1247. * @return {boolean} true if value is thenable
  1248. */
  1249. Promise.isPromise = function Promise_isPromise(value) {
  1250. return value && typeof value.then === 'function';
  1251. };
  1252. /**
  1253. * Creates resolved promise
  1254. * @param value resolve value
  1255. * @returns {Promise}
  1256. */
  1257. Promise.resolve = function Promise_resolve(value) {
  1258. return new Promise(function (resolve) { resolve(value); });
  1259. };
  1260. /**
  1261. * Creates rejected promise
  1262. * @param reason rejection value
  1263. * @returns {Promise}
  1264. */
  1265. Promise.reject = function Promise_reject(reason) {
  1266. return new Promise(function (resolve, reject) { reject(reason); });
  1267. };
  1268. Promise.prototype = {
  1269. _status: null,
  1270. _value: null,
  1271. _handlers: null,
  1272. _unhandledRejection: null,
  1273. _updateStatus: function Promise__updateStatus(status, value) {
  1274. if (this._status === STATUS_RESOLVED ||
  1275. this._status === STATUS_REJECTED) {
  1276. return;
  1277. }
  1278. if (status === STATUS_RESOLVED &&
  1279. Promise.isPromise(value)) {
  1280. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1281. this._updateStatus.bind(this, STATUS_REJECTED));
  1282. return;
  1283. }
  1284. this._status = status;
  1285. this._value = value;
  1286. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1287. this._unhandledRejection = true;
  1288. HandlerManager.addUnhandledRejection(this);
  1289. }
  1290. HandlerManager.scheduleHandlers(this);
  1291. },
  1292. _resolve: function Promise_resolve(value) {
  1293. this._updateStatus(STATUS_RESOLVED, value);
  1294. },
  1295. _reject: function Promise_reject(reason) {
  1296. this._updateStatus(STATUS_REJECTED, reason);
  1297. },
  1298. then: function Promise_then(onResolve, onReject) {
  1299. var nextPromise = new Promise(function (resolve, reject) {
  1300. this.resolve = resolve;
  1301. this.reject = reject;
  1302. });
  1303. this._handlers.push({
  1304. thisPromise: this,
  1305. onResolve: onResolve,
  1306. onReject: onReject,
  1307. nextPromise: nextPromise
  1308. });
  1309. HandlerManager.scheduleHandlers(this);
  1310. return nextPromise;
  1311. },
  1312. catch: function Promise_catch(onReject) {
  1313. return this.then(undefined, onReject);
  1314. }
  1315. };
  1316. globalScope.Promise = Promise;
  1317. })();
  1318. (function WeakMapClosure() {
  1319. if (globalScope.WeakMap) {
  1320. return;
  1321. }
  1322. var id = 0;
  1323. function WeakMap() {
  1324. this.id = '$weakmap' + (id++);
  1325. }
  1326. WeakMap.prototype = {
  1327. has: function(obj) {
  1328. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1329. },
  1330. get: function(obj, defaultValue) {
  1331. return this.has(obj) ? obj[this.id] : defaultValue;
  1332. },
  1333. set: function(obj, value) {
  1334. Object.defineProperty(obj, this.id, {
  1335. value: value,
  1336. enumerable: false,
  1337. configurable: true
  1338. });
  1339. },
  1340. delete: function(obj) {
  1341. delete obj[this.id];
  1342. }
  1343. };
  1344. globalScope.WeakMap = WeakMap;
  1345. })();
  1346. var StatTimer = (function StatTimerClosure() {
  1347. function rpad(str, pad, length) {
  1348. while (str.length < length) {
  1349. str += pad;
  1350. }
  1351. return str;
  1352. }
  1353. function StatTimer() {
  1354. this.started = Object.create(null);
  1355. this.times = [];
  1356. this.enabled = true;
  1357. }
  1358. StatTimer.prototype = {
  1359. time: function StatTimer_time(name) {
  1360. if (!this.enabled) {
  1361. return;
  1362. }
  1363. if (name in this.started) {
  1364. warn('Timer is already running for ' + name);
  1365. }
  1366. this.started[name] = Date.now();
  1367. },
  1368. timeEnd: function StatTimer_timeEnd(name) {
  1369. if (!this.enabled) {
  1370. return;
  1371. }
  1372. if (!(name in this.started)) {
  1373. warn('Timer has not been started for ' + name);
  1374. }
  1375. this.times.push({
  1376. 'name': name,
  1377. 'start': this.started[name],
  1378. 'end': Date.now()
  1379. });
  1380. // Remove timer from started so it can be called again.
  1381. delete this.started[name];
  1382. },
  1383. toString: function StatTimer_toString() {
  1384. var i, ii;
  1385. var times = this.times;
  1386. var out = '';
  1387. // Find the longest name for padding purposes.
  1388. var longest = 0;
  1389. for (i = 0, ii = times.length; i < ii; ++i) {
  1390. var name = times[i]['name'];
  1391. if (name.length > longest) {
  1392. longest = name.length;
  1393. }
  1394. }
  1395. for (i = 0, ii = times.length; i < ii; ++i) {
  1396. var span = times[i];
  1397. var duration = span.end - span.start;
  1398. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1399. }
  1400. return out;
  1401. }
  1402. };
  1403. return StatTimer;
  1404. })();
  1405. var createBlob = function createBlob(data, contentType) {
  1406. if (typeof Blob !== 'undefined') {
  1407. return new Blob([data], { type: contentType });
  1408. }
  1409. warn('The "Blob" constructor is not supported.');
  1410. };
  1411. var createObjectURL = (function createObjectURLClosure() {
  1412. // Blob/createObjectURL is not available, falling back to data schema.
  1413. var digits =
  1414. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1415. return function createObjectURL(data, contentType, forceDataSchema) {
  1416. if (!forceDataSchema &&
  1417. typeof URL !== 'undefined' && URL.createObjectURL) {
  1418. var blob = createBlob(data, contentType);
  1419. return URL.createObjectURL(blob);
  1420. }
  1421. var buffer = 'data:' + contentType + ';base64,';
  1422. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1423. var b1 = data[i] & 0xFF;
  1424. var b2 = data[i + 1] & 0xFF;
  1425. var b3 = data[i + 2] & 0xFF;
  1426. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1427. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1428. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1429. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1430. }
  1431. return buffer;
  1432. };
  1433. })();
  1434. function MessageHandler(sourceName, targetName, comObj) {
  1435. this.sourceName = sourceName;
  1436. this.targetName = targetName;
  1437. this.comObj = comObj;
  1438. this.callbackIndex = 1;
  1439. this.postMessageTransfers = true;
  1440. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1441. var ah = this.actionHandler = Object.create(null);
  1442. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1443. var data = event.data;
  1444. if (data.targetName !== this.sourceName) {
  1445. return;
  1446. }
  1447. if (data.isReply) {
  1448. var callbackId = data.callbackId;
  1449. if (data.callbackId in callbacksCapabilities) {
  1450. var callback = callbacksCapabilities[callbackId];
  1451. delete callbacksCapabilities[callbackId];
  1452. if ('error' in data) {
  1453. callback.reject(data.error);
  1454. } else {
  1455. callback.resolve(data.data);
  1456. }
  1457. } else {
  1458. error('Cannot resolve callback ' + callbackId);
  1459. }
  1460. } else if (data.action in ah) {
  1461. var action = ah[data.action];
  1462. if (data.callbackId) {
  1463. var sourceName = this.sourceName;
  1464. var targetName = data.sourceName;
  1465. Promise.resolve().then(function () {
  1466. return action[0].call(action[1], data.data);
  1467. }).then(function (result) {
  1468. comObj.postMessage({
  1469. sourceName: sourceName,
  1470. targetName: targetName,
  1471. isReply: true,
  1472. callbackId: data.callbackId,
  1473. data: result
  1474. });
  1475. }, function (reason) {
  1476. if (reason instanceof Error) {
  1477. // Serialize error to avoid "DataCloneError"
  1478. reason = reason + '';
  1479. }
  1480. comObj.postMessage({
  1481. sourceName: sourceName,
  1482. targetName: targetName,
  1483. isReply: true,
  1484. callbackId: data.callbackId,
  1485. error: reason
  1486. });
  1487. });
  1488. } else {
  1489. action[0].call(action[1], data.data);
  1490. }
  1491. } else {
  1492. error('Unknown action from worker: ' + data.action);
  1493. }
  1494. }.bind(this);
  1495. comObj.addEventListener('message', this._onComObjOnMessage);
  1496. }
  1497. MessageHandler.prototype = {
  1498. on: function messageHandlerOn(actionName, handler, scope) {
  1499. var ah = this.actionHandler;
  1500. if (ah[actionName]) {
  1501. error('There is already an actionName called "' + actionName + '"');
  1502. }
  1503. ah[actionName] = [handler, scope];
  1504. },
  1505. /**
  1506. * Sends a message to the comObj to invoke the action with the supplied data.
  1507. * @param {String} actionName Action to call.
  1508. * @param {JSON} data JSON data to send.
  1509. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1510. */
  1511. send: function messageHandlerSend(actionName, data, transfers) {
  1512. var message = {
  1513. sourceName: this.sourceName,
  1514. targetName: this.targetName,
  1515. action: actionName,
  1516. data: data
  1517. };
  1518. this.postMessage(message, transfers);
  1519. },
  1520. /**
  1521. * Sends a message to the comObj to invoke the action with the supplied data.
  1522. * Expects that other side will callback with the response.
  1523. * @param {String} actionName Action to call.
  1524. * @param {JSON} data JSON data to send.
  1525. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1526. * @returns {Promise} Promise to be resolved with response data.
  1527. */
  1528. sendWithPromise:
  1529. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1530. var callbackId = this.callbackIndex++;
  1531. var message = {
  1532. sourceName: this.sourceName,
  1533. targetName: this.targetName,
  1534. action: actionName,
  1535. data: data,
  1536. callbackId: callbackId
  1537. };
  1538. var capability = createPromiseCapability();
  1539. this.callbacksCapabilities[callbackId] = capability;
  1540. try {
  1541. this.postMessage(message, transfers);
  1542. } catch (e) {
  1543. capability.reject(e);
  1544. }
  1545. return capability.promise;
  1546. },
  1547. /**
  1548. * Sends raw message to the comObj.
  1549. * @private
  1550. * @param message {Object} Raw message.
  1551. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1552. */
  1553. postMessage: function (message, transfers) {
  1554. if (transfers && this.postMessageTransfers) {
  1555. this.comObj.postMessage(message, transfers);
  1556. } else {
  1557. this.comObj.postMessage(message);
  1558. }
  1559. },
  1560. destroy: function () {
  1561. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1562. }
  1563. };
  1564. function loadJpegStream(id, imageUrl, objs) {
  1565. var img = new Image();
  1566. img.onload = (function loadJpegStream_onloadClosure() {
  1567. objs.resolve(id, img);
  1568. });
  1569. img.onerror = (function loadJpegStream_onerrorClosure() {
  1570. objs.resolve(id, null);
  1571. warn('Error during JPEG image loading');
  1572. });
  1573. img.src = imageUrl;
  1574. }
  1575. // Polyfill from https://github.com/Polymer/URL
  1576. /* Any copyright is dedicated to the Public Domain.
  1577. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1578. (function checkURLConstructor(scope) {
  1579. // feature detect for URL constructor
  1580. var hasWorkingUrl = false;
  1581. try {
  1582. if (typeof URL === 'function' &&
  1583. typeof URL.prototype === 'object' &&
  1584. ('origin' in URL.prototype)) {
  1585. var u = new URL('b', 'http://a');
  1586. u.pathname = 'c%20d';
  1587. hasWorkingUrl = u.href === 'http://a/c%20d';
  1588. }
  1589. } catch(e) { }
  1590. if (hasWorkingUrl) {
  1591. return;
  1592. }
  1593. var relative = Object.create(null);
  1594. relative['ftp'] = 21;
  1595. relative['file'] = 0;
  1596. relative['gopher'] = 70;
  1597. relative['http'] = 80;
  1598. relative['https'] = 443;
  1599. relative['ws'] = 80;
  1600. relative['wss'] = 443;
  1601. var relativePathDotMapping = Object.create(null);
  1602. relativePathDotMapping['%2e'] = '.';
  1603. relativePathDotMapping['.%2e'] = '..';
  1604. relativePathDotMapping['%2e.'] = '..';
  1605. relativePathDotMapping['%2e%2e'] = '..';
  1606. function isRelativeScheme(scheme) {
  1607. return relative[scheme] !== undefined;
  1608. }
  1609. function invalid() {
  1610. clear.call(this);
  1611. this._isInvalid = true;
  1612. }
  1613. function IDNAToASCII(h) {
  1614. if ('' === h) {
  1615. invalid.call(this);
  1616. }
  1617. // XXX
  1618. return h.toLowerCase();
  1619. }
  1620. function percentEscape(c) {
  1621. var unicode = c.charCodeAt(0);
  1622. if (unicode > 0x20 &&
  1623. unicode < 0x7F &&
  1624. // " # < > ? `
  1625. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1
  1626. ) {
  1627. return c;
  1628. }
  1629. return encodeURIComponent(c);
  1630. }
  1631. function percentEscapeQuery(c) {
  1632. // XXX This actually needs to encode c using encoding and then
  1633. // convert the bytes one-by-one.
  1634. var unicode = c.charCodeAt(0);
  1635. if (unicode > 0x20 &&
  1636. unicode < 0x7F &&
  1637. // " # < > ` (do not escape '?')
  1638. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1
  1639. ) {
  1640. return c;
  1641. }
  1642. return encodeURIComponent(c);
  1643. }
  1644. var EOF, ALPHA = /[a-zA-Z]/,
  1645. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1646. function parse(input, stateOverride, base) {
  1647. function err(message) {
  1648. errors.push(message);
  1649. }
  1650. var state = stateOverride || 'scheme start',
  1651. cursor = 0,
  1652. buffer = '',
  1653. seenAt = false,
  1654. seenBracket = false,
  1655. errors = [];
  1656. loop: while ((input[cursor - 1] !== EOF || cursor === 0) &&
  1657. !this._isInvalid) {
  1658. var c = input[cursor];
  1659. switch (state) {
  1660. case 'scheme start':
  1661. if (c && ALPHA.test(c)) {
  1662. buffer += c.toLowerCase(); // ASCII-safe
  1663. state = 'scheme';
  1664. } else if (!stateOverride) {
  1665. buffer = '';
  1666. state = 'no scheme';
  1667. continue;
  1668. } else {
  1669. err('Invalid scheme.');
  1670. break loop;
  1671. }
  1672. break;
  1673. case 'scheme':
  1674. if (c && ALPHANUMERIC.test(c)) {
  1675. buffer += c.toLowerCase(); // ASCII-safe
  1676. } else if (':' === c) {
  1677. this._scheme = buffer;
  1678. buffer = '';
  1679. if (stateOverride) {
  1680. break loop;
  1681. }
  1682. if (isRelativeScheme(this._scheme)) {
  1683. this._isRelative = true;
  1684. }
  1685. if ('file' === this._scheme) {
  1686. state = 'relative';
  1687. } else if (this._isRelative && base &&
  1688. base._scheme === this._scheme) {
  1689. state = 'relative or authority';
  1690. } else if (this._isRelative) {
  1691. state = 'authority first slash';
  1692. } else {
  1693. state = 'scheme data';
  1694. }
  1695. } else if (!stateOverride) {
  1696. buffer = '';
  1697. cursor = 0;
  1698. state = 'no scheme';
  1699. continue;
  1700. } else if (EOF === c) {
  1701. break loop;
  1702. } else {
  1703. err('Code point not allowed in scheme: ' + c);
  1704. break loop;
  1705. }
  1706. break;
  1707. case 'scheme data':
  1708. if ('?' === c) {
  1709. this._query = '?';
  1710. state = 'query';
  1711. } else if ('#' === c) {
  1712. this._fragment = '#';
  1713. state = 'fragment';
  1714. } else {
  1715. // XXX error handling
  1716. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1717. this._schemeData += percentEscape(c);
  1718. }
  1719. }
  1720. break;
  1721. case 'no scheme':
  1722. if (!base || !(isRelativeScheme(base._scheme))) {
  1723. err('Missing scheme.');
  1724. invalid.call(this);
  1725. } else {
  1726. state = 'relative';
  1727. continue;
  1728. }
  1729. break;
  1730. case 'relative or authority':
  1731. if ('/' === c && '/' === input[cursor+1]) {
  1732. state = 'authority ignore slashes';
  1733. } else {
  1734. err('Expected /, got: ' + c);
  1735. state = 'relative';
  1736. continue;
  1737. }
  1738. break;
  1739. case 'relative':
  1740. this._isRelative = true;
  1741. if ('file' !== this._scheme) {
  1742. this._scheme = base._scheme;
  1743. }
  1744. if (EOF === c) {
  1745. this._host = base._host;
  1746. this._port = base._port;
  1747. this._path = base._path.slice();
  1748. this._query = base._query;
  1749. this._username = base._username;
  1750. this._password = base._password;
  1751. break loop;
  1752. } else if ('/' === c || '\\' === c) {
  1753. if ('\\' === c) {
  1754. err('\\ is an invalid code point.');
  1755. }
  1756. state = 'relative slash';
  1757. } else if ('?' === c) {
  1758. this._host = base._host;
  1759. this._port = base._port;
  1760. this._path = base._path.slice();
  1761. this._query = '?';
  1762. this._username = base._username;
  1763. this._password = base._password;
  1764. state = 'query';
  1765. } else if ('#' === c) {
  1766. this._host = base._host;
  1767. this._port = base._port;
  1768. this._path = base._path.slice();
  1769. this._query = base._query;
  1770. this._fragment = '#';
  1771. this._username = base._username;
  1772. this._password = base._password;
  1773. state = 'fragment';
  1774. } else {
  1775. var nextC = input[cursor+1];
  1776. var nextNextC = input[cursor+2];
  1777. if ('file' !== this._scheme || !ALPHA.test(c) ||
  1778. (nextC !== ':' && nextC !== '|') ||
  1779. (EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC &&
  1780. '?' !== nextNextC && '#' !== nextNextC)) {
  1781. this._host = base._host;
  1782. this._port = base._port;
  1783. this._username = base._username;
  1784. this._password = base._password;
  1785. this._path = base._path.slice();
  1786. this._path.pop();
  1787. }
  1788. state = 'relative path';
  1789. continue;
  1790. }
  1791. break;
  1792. case 'relative slash':
  1793. if ('/' === c || '\\' === c) {
  1794. if ('\\' === c) {
  1795. err('\\ is an invalid code point.');
  1796. }
  1797. if ('file' === this._scheme) {
  1798. state = 'file host';
  1799. } else {
  1800. state = 'authority ignore slashes';
  1801. }
  1802. } else {
  1803. if ('file' !== this._scheme) {
  1804. this._host = base._host;
  1805. this._port = base._port;
  1806. this._username = base._username;
  1807. this._password = base._password;
  1808. }
  1809. state = 'relative path';
  1810. continue;
  1811. }
  1812. break;
  1813. case 'authority first slash':
  1814. if ('/' === c) {
  1815. state = 'authority second slash';
  1816. } else {
  1817. err('Expected \'/\', got: ' + c);
  1818. state = 'authority ignore slashes';
  1819. continue;
  1820. }
  1821. break;
  1822. case 'authority second slash':
  1823. state = 'authority ignore slashes';
  1824. if ('/' !== c) {
  1825. err('Expected \'/\', got: ' + c);
  1826. continue;
  1827. }
  1828. break;
  1829. case 'authority ignore slashes':
  1830. if ('/' !== c && '\\' !== c) {
  1831. state = 'authority';
  1832. continue;
  1833. } else {
  1834. err('Expected authority, got: ' + c);
  1835. }
  1836. break;
  1837. case 'authority':
  1838. if ('@' === c) {
  1839. if (seenAt) {
  1840. err('@ already seen.');
  1841. buffer += '%40';
  1842. }
  1843. seenAt = true;
  1844. for (var i = 0; i < buffer.length; i++) {
  1845. var cp = buffer[i];
  1846. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  1847. err('Invalid whitespace in authority.');
  1848. continue;
  1849. }
  1850. // XXX check URL code points
  1851. if (':' === cp && null === this._password) {
  1852. this._password = '';
  1853. continue;
  1854. }
  1855. var tempC = percentEscape(cp);
  1856. if (null !== this._password) {
  1857. this._password += tempC;
  1858. } else {
  1859. this._username += tempC;
  1860. }
  1861. }
  1862. buffer = '';
  1863. } else if (EOF === c || '/' === c || '\\' === c ||
  1864. '?' === c || '#' === c) {
  1865. cursor -= buffer.length;
  1866. buffer = '';
  1867. state = 'host';
  1868. continue;
  1869. } else {
  1870. buffer += c;
  1871. }
  1872. break;
  1873. case 'file host':
  1874. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  1875. if (buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1876. (buffer[1] === ':' || buffer[1] === '|')) {
  1877. state = 'relative path';
  1878. } else if (buffer.length === 0) {
  1879. state = 'relative path start';
  1880. } else {
  1881. this._host = IDNAToASCII.call(this, buffer);
  1882. buffer = '';
  1883. state = 'relative path start';
  1884. }
  1885. continue;
  1886. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1887. err('Invalid whitespace in file host.');
  1888. } else {
  1889. buffer += c;
  1890. }
  1891. break;
  1892. case 'host':
  1893. case 'hostname':
  1894. if (':' === c && !seenBracket) {
  1895. // XXX host parsing
  1896. this._host = IDNAToASCII.call(this, buffer);
  1897. buffer = '';
  1898. state = 'port';
  1899. if ('hostname' === stateOverride) {
  1900. break loop;
  1901. }
  1902. } else if (EOF === c || '/' === c ||
  1903. '\\' === c || '?' === c || '#' === c) {
  1904. this._host = IDNAToASCII.call(this, buffer);
  1905. buffer = '';
  1906. state = 'relative path start';
  1907. if (stateOverride) {
  1908. break loop;
  1909. }
  1910. continue;
  1911. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1912. if ('[' === c) {
  1913. seenBracket = true;
  1914. } else if (']' === c) {
  1915. seenBracket = false;
  1916. }
  1917. buffer += c;
  1918. } else {
  1919. err('Invalid code point in host/hostname: ' + c);
  1920. }
  1921. break;
  1922. case 'port':
  1923. if (/[0-9]/.test(c)) {
  1924. buffer += c;
  1925. } else if (EOF === c || '/' === c || '\\' === c ||
  1926. '?' === c || '#' === c || stateOverride) {
  1927. if ('' !== buffer) {
  1928. var temp = parseInt(buffer, 10);
  1929. if (temp !== relative[this._scheme]) {
  1930. this._port = temp + '';
  1931. }
  1932. buffer = '';
  1933. }
  1934. if (stateOverride) {
  1935. break loop;
  1936. }
  1937. state = 'relative path start';
  1938. continue;
  1939. } else if ('\t' === c || '\n' === c || '\r' === c) {
  1940. err('Invalid code point in port: ' + c);
  1941. } else {
  1942. invalid.call(this);
  1943. }
  1944. break;
  1945. case 'relative path start':
  1946. if ('\\' === c) {
  1947. err('\'\\\' not allowed in path.');
  1948. }
  1949. state = 'relative path';
  1950. if ('/' !== c && '\\' !== c) {
  1951. continue;
  1952. }
  1953. break;
  1954. case 'relative path':
  1955. if (EOF === c || '/' === c || '\\' === c ||
  1956. (!stateOverride && ('?' === c || '#' === c))) {
  1957. if ('\\' === c) {
  1958. err('\\ not allowed in relative path.');
  1959. }
  1960. var tmp;
  1961. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1962. buffer = tmp;
  1963. }
  1964. if ('..' === buffer) {
  1965. this._path.pop();
  1966. if ('/' !== c && '\\' !== c) {
  1967. this._path.push('');
  1968. }
  1969. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  1970. this._path.push('');
  1971. } else if ('.' !== buffer) {
  1972. if ('file' === this._scheme && this._path.length === 0 &&
  1973. buffer.length === 2 && ALPHA.test(buffer[0]) &&
  1974. buffer[1] === '|') {
  1975. buffer = buffer[0] + ':';
  1976. }
  1977. this._path.push(buffer);
  1978. }
  1979. buffer = '';
  1980. if ('?' === c) {
  1981. this._query = '?';
  1982. state = 'query';
  1983. } else if ('#' === c) {
  1984. this._fragment = '#';
  1985. state = 'fragment';
  1986. }
  1987. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1988. buffer += percentEscape(c);
  1989. }
  1990. break;
  1991. case 'query':
  1992. if (!stateOverride && '#' === c) {
  1993. this._fragment = '#';
  1994. state = 'fragment';
  1995. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1996. this._query += percentEscapeQuery(c);
  1997. }
  1998. break;
  1999. case 'fragment':
  2000. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2001. this._fragment += c;
  2002. }
  2003. break;
  2004. }
  2005. cursor++;
  2006. }
  2007. }
  2008. function clear() {
  2009. this._scheme = '';
  2010. this._schemeData = '';
  2011. this._username = '';
  2012. this._password = null;
  2013. this._host = '';
  2014. this._port = '';
  2015. this._path = [];
  2016. this._query = '';
  2017. this._fragment = '';
  2018. this._isInvalid = false;
  2019. this._isRelative = false;
  2020. }
  2021. // Does not process domain names or IP addresses.
  2022. // Does not handle encoding for the query parameter.
  2023. function JURL(url, base /* , encoding */) {
  2024. if (base !== undefined && !(base instanceof JURL)) {
  2025. base = new JURL(String(base));
  2026. }
  2027. this._url = url;
  2028. clear.call(this);
  2029. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2030. // encoding = encoding || 'utf-8'
  2031. parse.call(this, input, null, base);
  2032. }
  2033. JURL.prototype = {
  2034. toString: function() {
  2035. return this.href;
  2036. },
  2037. get href() {
  2038. if (this._isInvalid) {
  2039. return this._url;
  2040. }
  2041. var authority = '';
  2042. if ('' !== this._username || null !== this._password) {
  2043. authority = this._username +
  2044. (null !== this._password ? ':' + this._password : '') + '@';
  2045. }
  2046. return this.protocol +
  2047. (this._isRelative ? '//' + authority + this.host : '') +
  2048. this.pathname + this._query + this._fragment;
  2049. },
  2050. set href(href) {
  2051. clear.call(this);
  2052. parse.call(this, href);
  2053. },
  2054. get protocol() {
  2055. return this._scheme + ':';
  2056. },
  2057. set protocol(protocol) {
  2058. if (this._isInvalid) {
  2059. return;
  2060. }
  2061. parse.call(this, protocol + ':', 'scheme start');
  2062. },
  2063. get host() {
  2064. return this._isInvalid ? '' : this._port ?
  2065. this._host + ':' + this._port : this._host;
  2066. },
  2067. set host(host) {
  2068. if (this._isInvalid || !this._isRelative) {
  2069. return;
  2070. }
  2071. parse.call(this, host, 'host');
  2072. },
  2073. get hostname() {
  2074. return this._host;
  2075. },
  2076. set hostname(hostname) {
  2077. if (this._isInvalid || !this._isRelative) {
  2078. return;
  2079. }
  2080. parse.call(this, hostname, 'hostname');
  2081. },
  2082. get port() {
  2083. return this._port;
  2084. },
  2085. set port(port) {
  2086. if (this._isInvalid || !this._isRelative) {
  2087. return;
  2088. }
  2089. parse.call(this, port, 'port');
  2090. },
  2091. get pathname() {
  2092. return this._isInvalid ? '' : this._isRelative ?
  2093. '/' + this._path.join('/') : this._schemeData;
  2094. },
  2095. set pathname(pathname) {
  2096. if (this._isInvalid || !this._isRelative) {
  2097. return;
  2098. }
  2099. this._path = [];
  2100. parse.call(this, pathname, 'relative path start');
  2101. },
  2102. get search() {
  2103. return this._isInvalid || !this._query || '?' === this._query ?
  2104. '' : this._query;
  2105. },
  2106. set search(search) {
  2107. if (this._isInvalid || !this._isRelative) {
  2108. return;
  2109. }
  2110. this._query = '?';
  2111. if ('?' === search[0]) {
  2112. search = search.slice(1);
  2113. }
  2114. parse.call(this, search, 'query');
  2115. },
  2116. get hash() {
  2117. return this._isInvalid || !this._fragment || '#' === this._fragment ?
  2118. '' : this._fragment;
  2119. },
  2120. set hash(hash) {
  2121. if (this._isInvalid) {
  2122. return;
  2123. }
  2124. this._fragment = '#';
  2125. if ('#' === hash[0]) {
  2126. hash = hash.slice(1);
  2127. }
  2128. parse.call(this, hash, 'fragment');
  2129. },
  2130. get origin() {
  2131. var host;
  2132. if (this._isInvalid || !this._scheme) {
  2133. return '';
  2134. }
  2135. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2136. // Gecko throws error for "data://"
  2137. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2138. // Gecko returns String("") for file: mailto:
  2139. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2140. switch (this._scheme) {
  2141. case 'data':
  2142. case 'file':
  2143. case 'javascript':
  2144. case 'mailto':
  2145. return 'null';
  2146. }
  2147. host = this.host;
  2148. if (!host) {
  2149. return '';
  2150. }
  2151. return this._scheme + '://' + host;
  2152. }
  2153. };
  2154. // Copy over the static methods
  2155. var OriginalURL = scope.URL;
  2156. if (OriginalURL) {
  2157. JURL.createObjectURL = function(blob) {
  2158. // IE extension allows a second optional options argument.
  2159. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2160. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2161. };
  2162. JURL.revokeObjectURL = function(url) {
  2163. OriginalURL.revokeObjectURL(url);
  2164. };
  2165. }
  2166. scope.URL = JURL;
  2167. })(globalScope);
  2168. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2169. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2170. exports.OPS = OPS;
  2171. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2172. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2173. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2174. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2175. exports.AnnotationFlag = AnnotationFlag;
  2176. exports.AnnotationType = AnnotationType;
  2177. exports.FontType = FontType;
  2178. exports.ImageKind = ImageKind;
  2179. exports.InvalidPDFException = InvalidPDFException;
  2180. exports.MessageHandler = MessageHandler;
  2181. exports.MissingDataException = MissingDataException;
  2182. exports.MissingPDFException = MissingPDFException;
  2183. exports.NotImplementedException = NotImplementedException;
  2184. exports.PageViewport = PageViewport;
  2185. exports.PasswordException = PasswordException;
  2186. exports.PasswordResponses = PasswordResponses;
  2187. exports.StatTimer = StatTimer;
  2188. exports.StreamType = StreamType;
  2189. exports.TextRenderingMode = TextRenderingMode;
  2190. exports.UnexpectedResponseException = UnexpectedResponseException;
  2191. exports.UnknownErrorException = UnknownErrorException;
  2192. exports.Util = Util;
  2193. exports.XRefParseException = XRefParseException;
  2194. exports.arrayByteLength = arrayByteLength;
  2195. exports.arraysToBytes = arraysToBytes;
  2196. exports.assert = assert;
  2197. exports.bytesToString = bytesToString;
  2198. exports.createBlob = createBlob;
  2199. exports.createPromiseCapability = createPromiseCapability;
  2200. exports.createObjectURL = createObjectURL;
  2201. exports.deprecated = deprecated;
  2202. exports.error = error;
  2203. exports.getLookupTableFactory = getLookupTableFactory;
  2204. exports.getVerbosityLevel = getVerbosityLevel;
  2205. exports.globalScope = globalScope;
  2206. exports.info = info;
  2207. exports.isArray = isArray;
  2208. exports.isArrayBuffer = isArrayBuffer;
  2209. exports.isBool = isBool;
  2210. exports.isEmptyObj = isEmptyObj;
  2211. exports.isInt = isInt;
  2212. exports.isNum = isNum;
  2213. exports.isString = isString;
  2214. exports.isSpace = isSpace;
  2215. exports.isSameOrigin = isSameOrigin;
  2216. exports.isValidUrl = isValidUrl;
  2217. exports.isLittleEndian = isLittleEndian;
  2218. exports.isEvalSupported = isEvalSupported;
  2219. exports.loadJpegStream = loadJpegStream;
  2220. exports.log2 = log2;
  2221. exports.readInt8 = readInt8;
  2222. exports.readUint16 = readUint16;
  2223. exports.readUint32 = readUint32;
  2224. exports.removeNullCharacters = removeNullCharacters;
  2225. exports.setVerbosityLevel = setVerbosityLevel;
  2226. exports.shadow = shadow;
  2227. exports.string32 = string32;
  2228. exports.stringToBytes = stringToBytes;
  2229. exports.stringToPDFString = stringToPDFString;
  2230. exports.stringToUTF8String = stringToUTF8String;
  2231. exports.utf8StringToString = utf8StringToString;
  2232. exports.warn = warn;
  2233. }));
  2234. (function (root, factory) {
  2235. {
  2236. factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil);
  2237. }
  2238. }(this, function (exports, sharedUtil) {
  2239. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2240. var warn = sharedUtil.warn;
  2241. /**
  2242. * Optimised CSS custom property getter/setter.
  2243. * @class
  2244. */
  2245. var CustomStyle = (function CustomStyleClosure() {
  2246. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2247. // animate-css-transforms-firefox-webkit.html
  2248. // in some versions of IE9 it is critical that ms appear in this list
  2249. // before Moz
  2250. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  2251. var _cache = Object.create(null);
  2252. function CustomStyle() {}
  2253. CustomStyle.getProp = function get(propName, element) {
  2254. // check cache only when no element is given
  2255. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2256. return _cache[propName];
  2257. }
  2258. element = element || document.documentElement;
  2259. var style = element.style, prefixed, uPropName;
  2260. // test standard property first
  2261. if (typeof style[propName] === 'string') {
  2262. return (_cache[propName] = propName);
  2263. }
  2264. // capitalize
  2265. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2266. // test vendor specific properties
  2267. for (var i = 0, l = prefixes.length; i < l; i++) {
  2268. prefixed = prefixes[i] + uPropName;
  2269. if (typeof style[prefixed] === 'string') {
  2270. return (_cache[propName] = prefixed);
  2271. }
  2272. }
  2273. //if all fails then set to undefined
  2274. return (_cache[propName] = 'undefined');
  2275. };
  2276. CustomStyle.setProp = function set(propName, element, str) {
  2277. var prop = this.getProp(propName);
  2278. if (prop !== 'undefined') {
  2279. element.style[prop] = str;
  2280. }
  2281. };
  2282. return CustomStyle;
  2283. })();
  2284. function hasCanvasTypedArrays() {
  2285. var canvas = document.createElement('canvas');
  2286. canvas.width = canvas.height = 1;
  2287. var ctx = canvas.getContext('2d');
  2288. var imageData = ctx.createImageData(1, 1);
  2289. return (typeof imageData.data.buffer !== 'undefined');
  2290. }
  2291. var LinkTarget = {
  2292. NONE: 0, // Default value.
  2293. SELF: 1,
  2294. BLANK: 2,
  2295. PARENT: 3,
  2296. TOP: 4,
  2297. };
  2298. var LinkTargetStringMap = [
  2299. '',
  2300. '_self',
  2301. '_blank',
  2302. '_parent',
  2303. '_top'
  2304. ];
  2305. /**
  2306. * @typedef ExternalLinkParameters
  2307. * @typedef {Object} ExternalLinkParameters
  2308. * @property {string} url - An absolute URL.
  2309. * @property {LinkTarget} target - The link target.
  2310. * @property {string} rel - The link relationship.
  2311. */
  2312. /**
  2313. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2314. * @param {HTMLLinkElement} link - The link element.
  2315. * @param {ExternalLinkParameters} params
  2316. */
  2317. function addLinkAttributes(link, params) {
  2318. var url = params && params.url;
  2319. link.href = link.title = (url ? removeNullCharacters(url) : '');
  2320. if (url) {
  2321. var target = params.target;
  2322. if (typeof target === 'undefined') {
  2323. target = getDefaultSetting('externalLinkTarget');
  2324. }
  2325. link.target = LinkTargetStringMap[target];
  2326. var rel = params.rel;
  2327. if (typeof rel === 'undefined') {
  2328. rel = getDefaultSetting('externalLinkRel');
  2329. }
  2330. link.rel = rel;
  2331. }
  2332. }
  2333. // Gets the file name from a given URL.
  2334. function getFilenameFromUrl(url) {
  2335. var anchor = url.indexOf('#');
  2336. var query = url.indexOf('?');
  2337. var end = Math.min(
  2338. anchor > 0 ? anchor : url.length,
  2339. query > 0 ? query : url.length);
  2340. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2341. }
  2342. function getDefaultSetting(id) {
  2343. // The list of the settings and their default is maintained for backward
  2344. // compatibility and shall not be extended or modified. See also global.js.
  2345. var globalSettings = sharedUtil.globalScope.PDFJS;
  2346. switch (id) {
  2347. case 'pdfBug':
  2348. return globalSettings ? globalSettings.pdfBug : false;
  2349. case 'disableAutoFetch':
  2350. return globalSettings ? globalSettings.disableAutoFetch : false;
  2351. case 'disableStream':
  2352. return globalSettings ? globalSettings.disableStream : false;
  2353. case 'disableRange':
  2354. return globalSettings ? globalSettings.disableRange : false;
  2355. case 'disableFontFace':
  2356. return globalSettings ? globalSettings.disableFontFace : false;
  2357. case 'disableCreateObjectURL':
  2358. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2359. case 'disableWebGL':
  2360. return globalSettings ? globalSettings.disableWebGL : true;
  2361. case 'cMapUrl':
  2362. return globalSettings ? globalSettings.cMapUrl : null;
  2363. case 'cMapPacked':
  2364. return globalSettings ? globalSettings.cMapPacked : false;
  2365. case 'postMessageTransfers':
  2366. return globalSettings ? globalSettings.postMessageTransfers : true;
  2367. case 'workerSrc':
  2368. return globalSettings ? globalSettings.workerSrc : null;
  2369. case 'disableWorker':
  2370. return globalSettings ? globalSettings.disableWorker : false;
  2371. case 'maxImageSize':
  2372. return globalSettings ? globalSettings.maxImageSize : -1;
  2373. case 'imageResourcesPath':
  2374. return globalSettings ? globalSettings.imageResourcesPath : '';
  2375. case 'isEvalSupported':
  2376. return globalSettings ? globalSettings.isEvalSupported : true;
  2377. case 'externalLinkTarget':
  2378. if (!globalSettings) {
  2379. return LinkTarget.NONE;
  2380. }
  2381. switch (globalSettings.externalLinkTarget) {
  2382. case LinkTarget.NONE:
  2383. case LinkTarget.SELF:
  2384. case LinkTarget.BLANK:
  2385. case LinkTarget.PARENT:
  2386. case LinkTarget.TOP:
  2387. return globalSettings.externalLinkTarget;
  2388. }
  2389. warn('PDFJS.externalLinkTarget is invalid: ' +
  2390. globalSettings.externalLinkTarget);
  2391. // Reset the external link target, to suppress further warnings.
  2392. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2393. return LinkTarget.NONE;
  2394. case 'externalLinkRel':
  2395. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2396. case 'enableStats':
  2397. return !!(globalSettings && globalSettings.enableStats);
  2398. default:
  2399. throw new Error('Unknown default setting: ' + id);
  2400. }
  2401. }
  2402. function isExternalLinkTargetSet() {
  2403. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2404. switch (externalLinkTarget) {
  2405. case LinkTarget.NONE:
  2406. return false;
  2407. case LinkTarget.SELF:
  2408. case LinkTarget.BLANK:
  2409. case LinkTarget.PARENT:
  2410. case LinkTarget.TOP:
  2411. return true;
  2412. }
  2413. }
  2414. exports.CustomStyle = CustomStyle;
  2415. exports.addLinkAttributes = addLinkAttributes;
  2416. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2417. exports.getFilenameFromUrl = getFilenameFromUrl;
  2418. exports.LinkTarget = LinkTarget;
  2419. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2420. exports.getDefaultSetting = getDefaultSetting;
  2421. }));
  2422. (function (root, factory) {
  2423. {
  2424. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil);
  2425. }
  2426. }(this, function (exports, sharedUtil) {
  2427. var assert = sharedUtil.assert;
  2428. var bytesToString = sharedUtil.bytesToString;
  2429. var string32 = sharedUtil.string32;
  2430. var shadow = sharedUtil.shadow;
  2431. var warn = sharedUtil.warn;
  2432. function FontLoader(docId) {
  2433. this.docId = docId;
  2434. this.styleElement = null;
  2435. this.nativeFontFaces = [];
  2436. this.loadTestFontId = 0;
  2437. this.loadingContext = {
  2438. requests: [],
  2439. nextRequestId: 0
  2440. };
  2441. }
  2442. FontLoader.prototype = {
  2443. insertRule: function fontLoaderInsertRule(rule) {
  2444. var styleElement = this.styleElement;
  2445. if (!styleElement) {
  2446. styleElement = this.styleElement = document.createElement('style');
  2447. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2448. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2449. styleElement);
  2450. }
  2451. var styleSheet = styleElement.sheet;
  2452. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2453. },
  2454. clear: function fontLoaderClear() {
  2455. var styleElement = this.styleElement;
  2456. if (styleElement) {
  2457. styleElement.parentNode.removeChild(styleElement);
  2458. styleElement = this.styleElement = null;
  2459. }
  2460. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2461. document.fonts.delete(nativeFontFace);
  2462. });
  2463. this.nativeFontFaces.length = 0;
  2464. },
  2465. get loadTestFont() {
  2466. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2467. // height.
  2468. return shadow(this, 'loadTestFont', atob(
  2469. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2470. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2471. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2472. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2473. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2474. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2475. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2476. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2477. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2478. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2479. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2480. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2481. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2482. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2483. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2484. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2485. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2486. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2487. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2488. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2489. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2490. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2491. ));
  2492. },
  2493. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2494. this.nativeFontFaces.push(nativeFontFace);
  2495. document.fonts.add(nativeFontFace);
  2496. },
  2497. bind: function fontLoaderBind(fonts, callback) {
  2498. var rules = [];
  2499. var fontsToLoad = [];
  2500. var fontLoadPromises = [];
  2501. var getNativeFontPromise = function(nativeFontFace) {
  2502. // Return a promise that is always fulfilled, even when the font fails to
  2503. // load.
  2504. return nativeFontFace.loaded.catch(function(e) {
  2505. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2506. });
  2507. };
  2508. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2509. var font = fonts[i];
  2510. // Add the font to the DOM only once or skip if the font
  2511. // is already loaded.
  2512. if (font.attached || font.loading === false) {
  2513. continue;
  2514. }
  2515. font.attached = true;
  2516. if (FontLoader.isFontLoadingAPISupported) {
  2517. var nativeFontFace = font.createNativeFontFace();
  2518. if (nativeFontFace) {
  2519. this.addNativeFontFace(nativeFontFace);
  2520. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2521. }
  2522. } else {
  2523. var rule = font.createFontFaceRule();
  2524. if (rule) {
  2525. this.insertRule(rule);
  2526. rules.push(rule);
  2527. fontsToLoad.push(font);
  2528. }
  2529. }
  2530. }
  2531. var request = this.queueLoadingCallback(callback);
  2532. if (FontLoader.isFontLoadingAPISupported) {
  2533. Promise.all(fontLoadPromises).then(function() {
  2534. request.complete();
  2535. });
  2536. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2537. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2538. } else {
  2539. request.complete();
  2540. }
  2541. },
  2542. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  2543. function LoadLoader_completeRequest() {
  2544. assert(!request.end, 'completeRequest() cannot be called twice');
  2545. request.end = Date.now();
  2546. // sending all completed requests in order how they were queued
  2547. while (context.requests.length > 0 && context.requests[0].end) {
  2548. var otherRequest = context.requests.shift();
  2549. setTimeout(otherRequest.callback, 0);
  2550. }
  2551. }
  2552. var context = this.loadingContext;
  2553. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  2554. var request = {
  2555. id: requestId,
  2556. complete: LoadLoader_completeRequest,
  2557. callback: callback,
  2558. started: Date.now()
  2559. };
  2560. context.requests.push(request);
  2561. return request;
  2562. },
  2563. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  2564. fonts,
  2565. request) {
  2566. /** Hack begin */
  2567. // There's currently no event when a font has finished downloading so the
  2568. // following code is a dirty hack to 'guess' when a font is
  2569. // ready. It's assumed fonts are loaded in order, so add a known test
  2570. // font after the desired fonts and then test for the loading of that
  2571. // test font.
  2572. function int32(data, offset) {
  2573. return (data.charCodeAt(offset) << 24) |
  2574. (data.charCodeAt(offset + 1) << 16) |
  2575. (data.charCodeAt(offset + 2) << 8) |
  2576. (data.charCodeAt(offset + 3) & 0xff);
  2577. }
  2578. function spliceString(s, offset, remove, insert) {
  2579. var chunk1 = s.substr(0, offset);
  2580. var chunk2 = s.substr(offset + remove);
  2581. return chunk1 + insert + chunk2;
  2582. }
  2583. var i, ii;
  2584. var canvas = document.createElement('canvas');
  2585. canvas.width = 1;
  2586. canvas.height = 1;
  2587. var ctx = canvas.getContext('2d');
  2588. var called = 0;
  2589. function isFontReady(name, callback) {
  2590. called++;
  2591. // With setTimeout clamping this gives the font ~100ms to load.
  2592. if(called > 30) {
  2593. warn('Load test font never loaded.');
  2594. callback();
  2595. return;
  2596. }
  2597. ctx.font = '30px ' + name;
  2598. ctx.fillText('.', 0, 20);
  2599. var imageData = ctx.getImageData(0, 0, 1, 1);
  2600. if (imageData.data[3] > 0) {
  2601. callback();
  2602. return;
  2603. }
  2604. setTimeout(isFontReady.bind(null, name, callback));
  2605. }
  2606. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2607. // Chromium seems to cache fonts based on a hash of the actual font data,
  2608. // so the font must be modified for each load test else it will appear to
  2609. // be loaded already.
  2610. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2611. // font by splitting it in chunks before hand and padding the font id.
  2612. var data = this.loadTestFont;
  2613. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  2614. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  2615. loadTestFontId);
  2616. // CFF checksum is important for IE, adjusting it
  2617. var CFF_CHECKSUM_OFFSET = 16;
  2618. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  2619. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2620. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2621. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  2622. }
  2623. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  2624. checksum = (checksum - XXXX_VALUE +
  2625. int32(loadTestFontId + 'XXX', i)) | 0;
  2626. }
  2627. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2628. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2629. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  2630. url + '}';
  2631. this.insertRule(rule);
  2632. var names = [];
  2633. for (i = 0, ii = fonts.length; i < ii; i++) {
  2634. names.push(fonts[i].loadedName);
  2635. }
  2636. names.push(loadTestFontId);
  2637. var div = document.createElement('div');
  2638. div.setAttribute('style',
  2639. 'visibility: hidden;' +
  2640. 'width: 10px; height: 10px;' +
  2641. 'position: absolute; top: 0px; left: 0px;');
  2642. for (i = 0, ii = names.length; i < ii; ++i) {
  2643. var span = document.createElement('span');
  2644. span.textContent = 'Hi';
  2645. span.style.fontFamily = names[i];
  2646. div.appendChild(span);
  2647. }
  2648. document.body.appendChild(div);
  2649. isFontReady(loadTestFontId, function() {
  2650. document.body.removeChild(div);
  2651. request.complete();
  2652. });
  2653. /** Hack end */
  2654. }
  2655. };
  2656. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' &&
  2657. !!document.fonts;
  2658. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2659. get: function () {
  2660. if (typeof navigator === 'undefined') {
  2661. // node.js - we can pretend sync font loading is supported.
  2662. return shadow(FontLoader, 'isSyncFontLoadingSupported', true);
  2663. }
  2664. var supported = false;
  2665. // User agent string sniffing is bad, but there is no reliable way to tell
  2666. // if font is fully loaded and ready to be used with canvas.
  2667. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2668. if (m && m[1] >= 14) {
  2669. supported = true;
  2670. }
  2671. // TODO other browsers
  2672. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  2673. },
  2674. enumerable: true,
  2675. configurable: true
  2676. });
  2677. var IsEvalSupportedCached = {
  2678. get value() {
  2679. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2680. }
  2681. };
  2682. var FontFaceObject = (function FontFaceObjectClosure() {
  2683. function FontFaceObject(translatedData, options) {
  2684. this.compiledGlyphs = Object.create(null);
  2685. // importing translated data
  2686. for (var i in translatedData) {
  2687. this[i] = translatedData[i];
  2688. }
  2689. this.options = options;
  2690. }
  2691. FontFaceObject.prototype = {
  2692. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2693. if (!this.data) {
  2694. return null;
  2695. }
  2696. if (this.options.disableFontFace) {
  2697. this.disableFontFace = true;
  2698. return null;
  2699. }
  2700. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2701. if (this.options.fontRegistry) {
  2702. this.options.fontRegistry.registerFont(this);
  2703. }
  2704. return nativeFontFace;
  2705. },
  2706. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2707. if (!this.data) {
  2708. return null;
  2709. }
  2710. if (this.options.disableFontFace) {
  2711. this.disableFontFace = true;
  2712. return null;
  2713. }
  2714. var data = bytesToString(new Uint8Array(this.data));
  2715. var fontName = this.loadedName;
  2716. // Add the font-face rule to the document
  2717. var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
  2718. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2719. if (this.options.fontRegistry) {
  2720. this.options.fontRegistry.registerFont(this, url);
  2721. }
  2722. return rule;
  2723. },
  2724. getPathGenerator:
  2725. function FontFaceObject_getPathGenerator(objs, character) {
  2726. if (!(character in this.compiledGlyphs)) {
  2727. var cmds = objs.get(this.loadedName + '_path_' + character);
  2728. var current, i, len;
  2729. // If we can, compile cmds into JS for MAXIMUM SPEED
  2730. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2731. var args, js = '';
  2732. for (i = 0, len = cmds.length; i < len; i++) {
  2733. current = cmds[i];
  2734. if (current.args !== undefined) {
  2735. args = current.args.join(',');
  2736. } else {
  2737. args = '';
  2738. }
  2739. js += 'c.' + current.cmd + '(' + args + ');\n';
  2740. }
  2741. /* jshint -W054 */
  2742. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2743. } else {
  2744. // But fall back on using Function.prototype.apply() if we're
  2745. // blocked from using eval() for whatever reason (like CSP policies)
  2746. this.compiledGlyphs[character] = function(c, size) {
  2747. for (i = 0, len = cmds.length; i < len; i++) {
  2748. current = cmds[i];
  2749. if (current.cmd === 'scale') {
  2750. current.args = [size, -size];
  2751. }
  2752. c[current.cmd].apply(c, current.args);
  2753. }
  2754. };
  2755. }
  2756. }
  2757. return this.compiledGlyphs[character];
  2758. }
  2759. };
  2760. return FontFaceObject;
  2761. })();
  2762. exports.FontFaceObject = FontFaceObject;
  2763. exports.FontLoader = FontLoader;
  2764. }));
  2765. (function (root, factory) {
  2766. {
  2767. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  2768. }
  2769. }(this, function (exports, sharedUtil) {
  2770. var error = sharedUtil.error;
  2771. function fixMetadata(meta) {
  2772. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2773. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2774. function(code, d1, d2, d3) {
  2775. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2776. });
  2777. var chars = '';
  2778. for (var i = 0; i < bytes.length; i += 2) {
  2779. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2780. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2781. code !== 38 && false ? String.fromCharCode(code) :
  2782. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2783. }
  2784. return '>' + chars;
  2785. });
  2786. }
  2787. function Metadata(meta) {
  2788. if (typeof meta === 'string') {
  2789. // Ghostscript produces invalid metadata
  2790. meta = fixMetadata(meta);
  2791. var parser = new DOMParser();
  2792. meta = parser.parseFromString(meta, 'application/xml');
  2793. } else if (!(meta instanceof Document)) {
  2794. error('Metadata: Invalid metadata object');
  2795. }
  2796. this.metaDocument = meta;
  2797. this.metadata = Object.create(null);
  2798. this.parse();
  2799. }
  2800. Metadata.prototype = {
  2801. parse: function Metadata_parse() {
  2802. var doc = this.metaDocument;
  2803. var rdf = doc.documentElement;
  2804. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2805. rdf = rdf.firstChild;
  2806. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2807. rdf = rdf.nextSibling;
  2808. }
  2809. }
  2810. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2811. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2812. return;
  2813. }
  2814. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2815. for (i = 0, length = children.length; i < length; i++) {
  2816. desc = children[i];
  2817. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2818. continue;
  2819. }
  2820. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2821. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2822. entry = desc.childNodes[ii];
  2823. name = entry.nodeName.toLowerCase();
  2824. this.metadata[name] = entry.textContent.trim();
  2825. }
  2826. }
  2827. }
  2828. },
  2829. get: function Metadata_get(name) {
  2830. return this.metadata[name] || null;
  2831. },
  2832. has: function Metadata_has(name) {
  2833. return typeof this.metadata[name] !== 'undefined';
  2834. }
  2835. };
  2836. exports.Metadata = Metadata;
  2837. }));
  2838. (function (root, factory) {
  2839. {
  2840. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  2841. }
  2842. }(this, function (exports, sharedUtil) {
  2843. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2844. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2845. var ImageKind = sharedUtil.ImageKind;
  2846. var OPS = sharedUtil.OPS;
  2847. var Util = sharedUtil.Util;
  2848. var isNum = sharedUtil.isNum;
  2849. var isArray = sharedUtil.isArray;
  2850. var warn = sharedUtil.warn;
  2851. var createObjectURL = sharedUtil.createObjectURL;
  2852. var SVG_DEFAULTS = {
  2853. fontStyle: 'normal',
  2854. fontWeight: 'normal',
  2855. fillColor: '#000000'
  2856. };
  2857. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  2858. var PNG_HEADER =
  2859. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  2860. var CHUNK_WRAPPER_SIZE = 12;
  2861. var crcTable = new Int32Array(256);
  2862. for (var i = 0; i < 256; i++) {
  2863. var c = i;
  2864. for (var h = 0; h < 8; h++) {
  2865. if (c & 1) {
  2866. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  2867. } else {
  2868. c = (c >> 1) & 0x7fffffff;
  2869. }
  2870. }
  2871. crcTable[i] = c;
  2872. }
  2873. function crc32(data, start, end) {
  2874. var crc = -1;
  2875. for (var i = start; i < end; i++) {
  2876. var a = (crc ^ data[i]) & 0xff;
  2877. var b = crcTable[a];
  2878. crc = (crc >>> 8) ^ b;
  2879. }
  2880. return crc ^ -1;
  2881. }
  2882. function writePngChunk(type, body, data, offset) {
  2883. var p = offset;
  2884. var len = body.length;
  2885. data[p] = len >> 24 & 0xff;
  2886. data[p + 1] = len >> 16 & 0xff;
  2887. data[p + 2] = len >> 8 & 0xff;
  2888. data[p + 3] = len & 0xff;
  2889. p += 4;
  2890. data[p] = type.charCodeAt(0) & 0xff;
  2891. data[p + 1] = type.charCodeAt(1) & 0xff;
  2892. data[p + 2] = type.charCodeAt(2) & 0xff;
  2893. data[p + 3] = type.charCodeAt(3) & 0xff;
  2894. p += 4;
  2895. data.set(body, p);
  2896. p += body.length;
  2897. var crc = crc32(data, offset + 4, p);
  2898. data[p] = crc >> 24 & 0xff;
  2899. data[p + 1] = crc >> 16 & 0xff;
  2900. data[p + 2] = crc >> 8 & 0xff;
  2901. data[p + 3] = crc & 0xff;
  2902. }
  2903. function adler32(data, start, end) {
  2904. var a = 1;
  2905. var b = 0;
  2906. for (var i = start; i < end; ++i) {
  2907. a = (a + (data[i] & 0xff)) % 65521;
  2908. b = (b + a) % 65521;
  2909. }
  2910. return (b << 16) | a;
  2911. }
  2912. function encode(imgData, kind, forceDataSchema) {
  2913. var width = imgData.width;
  2914. var height = imgData.height;
  2915. var bitDepth, colorType, lineSize;
  2916. var bytes = imgData.data;
  2917. switch (kind) {
  2918. case ImageKind.GRAYSCALE_1BPP:
  2919. colorType = 0;
  2920. bitDepth = 1;
  2921. lineSize = (width + 7) >> 3;
  2922. break;
  2923. case ImageKind.RGB_24BPP:
  2924. colorType = 2;
  2925. bitDepth = 8;
  2926. lineSize = width * 3;
  2927. break;
  2928. case ImageKind.RGBA_32BPP:
  2929. colorType = 6;
  2930. bitDepth = 8;
  2931. lineSize = width * 4;
  2932. break;
  2933. default:
  2934. throw new Error('invalid format');
  2935. }
  2936. // prefix every row with predictor 0
  2937. var literals = new Uint8Array((1 + lineSize) * height);
  2938. var offsetLiterals = 0, offsetBytes = 0;
  2939. var y, i;
  2940. for (y = 0; y < height; ++y) {
  2941. literals[offsetLiterals++] = 0; // no prediction
  2942. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  2943. offsetLiterals);
  2944. offsetBytes += lineSize;
  2945. offsetLiterals += lineSize;
  2946. }
  2947. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2948. // inverting for B/W
  2949. offsetLiterals = 0;
  2950. for (y = 0; y < height; y++) {
  2951. offsetLiterals++; // skipping predictor
  2952. for (i = 0; i < lineSize; i++) {
  2953. literals[offsetLiterals++] ^= 0xFF;
  2954. }
  2955. }
  2956. }
  2957. var ihdr = new Uint8Array([
  2958. width >> 24 & 0xff,
  2959. width >> 16 & 0xff,
  2960. width >> 8 & 0xff,
  2961. width & 0xff,
  2962. height >> 24 & 0xff,
  2963. height >> 16 & 0xff,
  2964. height >> 8 & 0xff,
  2965. height & 0xff,
  2966. bitDepth, // bit depth
  2967. colorType, // color type
  2968. 0x00, // compression method
  2969. 0x00, // filter method
  2970. 0x00 // interlace method
  2971. ]);
  2972. var len = literals.length;
  2973. var maxBlockLength = 0xFFFF;
  2974. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2975. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2976. var pi = 0;
  2977. idat[pi++] = 0x78; // compression method and flags
  2978. idat[pi++] = 0x9c; // flags
  2979. var pos = 0;
  2980. while (len > maxBlockLength) {
  2981. // writing non-final DEFLATE blocks type 0 and length of 65535
  2982. idat[pi++] = 0x00;
  2983. idat[pi++] = 0xff;
  2984. idat[pi++] = 0xff;
  2985. idat[pi++] = 0x00;
  2986. idat[pi++] = 0x00;
  2987. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2988. pi += maxBlockLength;
  2989. pos += maxBlockLength;
  2990. len -= maxBlockLength;
  2991. }
  2992. // writing non-final DEFLATE blocks type 0
  2993. idat[pi++] = 0x01;
  2994. idat[pi++] = len & 0xff;
  2995. idat[pi++] = len >> 8 & 0xff;
  2996. idat[pi++] = (~len & 0xffff) & 0xff;
  2997. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  2998. idat.set(literals.subarray(pos), pi);
  2999. pi += literals.length - pos;
  3000. var adler = adler32(literals, 0, literals.length); // checksum
  3001. idat[pi++] = adler >> 24 & 0xff;
  3002. idat[pi++] = adler >> 16 & 0xff;
  3003. idat[pi++] = adler >> 8 & 0xff;
  3004. idat[pi++] = adler & 0xff;
  3005. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3006. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  3007. ihdr.length + idat.length;
  3008. var data = new Uint8Array(pngLength);
  3009. var offset = 0;
  3010. data.set(PNG_HEADER, offset);
  3011. offset += PNG_HEADER.length;
  3012. writePngChunk('IHDR', ihdr, data, offset);
  3013. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3014. writePngChunk('IDATA', idat, data, offset);
  3015. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3016. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3017. return createObjectURL(data, 'image/png', forceDataSchema);
  3018. }
  3019. return function convertImgDataToPng(imgData, forceDataSchema) {
  3020. var kind = (imgData.kind === undefined ?
  3021. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  3022. return encode(imgData, kind, forceDataSchema);
  3023. };
  3024. })();
  3025. var SVGExtraState = (function SVGExtraStateClosure() {
  3026. function SVGExtraState() {
  3027. this.fontSizeScale = 1;
  3028. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3029. this.fontSize = 0;
  3030. this.textMatrix = IDENTITY_MATRIX;
  3031. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3032. this.leading = 0;
  3033. // Current point (in user coordinates)
  3034. this.x = 0;
  3035. this.y = 0;
  3036. // Start of text line (in text coordinates)
  3037. this.lineX = 0;
  3038. this.lineY = 0;
  3039. // Character and word spacing
  3040. this.charSpacing = 0;
  3041. this.wordSpacing = 0;
  3042. this.textHScale = 1;
  3043. this.textRise = 0;
  3044. // Default foreground and background colors
  3045. this.fillColor = SVG_DEFAULTS.fillColor;
  3046. this.strokeColor = '#000000';
  3047. this.fillAlpha = 1;
  3048. this.strokeAlpha = 1;
  3049. this.lineWidth = 1;
  3050. this.lineJoin = '';
  3051. this.lineCap = '';
  3052. this.miterLimit = 0;
  3053. this.dashArray = [];
  3054. this.dashPhase = 0;
  3055. this.dependencies = [];
  3056. // Clipping
  3057. this.clipId = '';
  3058. this.pendingClip = false;
  3059. this.maskId = '';
  3060. }
  3061. SVGExtraState.prototype = {
  3062. clone: function SVGExtraState_clone() {
  3063. return Object.create(this);
  3064. },
  3065. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3066. this.x = x;
  3067. this.y = y;
  3068. }
  3069. };
  3070. return SVGExtraState;
  3071. })();
  3072. var SVGGraphics = (function SVGGraphicsClosure() {
  3073. function createScratchSVG(width, height) {
  3074. var NS = 'http://www.w3.org/2000/svg';
  3075. var svg = document.createElementNS(NS, 'svg:svg');
  3076. svg.setAttributeNS(null, 'version', '1.1');
  3077. svg.setAttributeNS(null, 'width', width + 'px');
  3078. svg.setAttributeNS(null, 'height', height + 'px');
  3079. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3080. return svg;
  3081. }
  3082. function opListToTree(opList) {
  3083. var opTree = [];
  3084. var tmp = [];
  3085. var opListLen = opList.length;
  3086. for (var x = 0; x < opListLen; x++) {
  3087. if (opList[x].fn === 'save') {
  3088. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3089. tmp.push(opTree);
  3090. opTree = opTree[opTree.length - 1].items;
  3091. continue;
  3092. }
  3093. if(opList[x].fn === 'restore') {
  3094. opTree = tmp.pop();
  3095. } else {
  3096. opTree.push(opList[x]);
  3097. }
  3098. }
  3099. return opTree;
  3100. }
  3101. /**
  3102. * Formats float number.
  3103. * @param value {number} number to format.
  3104. * @returns {string}
  3105. */
  3106. function pf(value) {
  3107. if (value === (value | 0)) { // integer number
  3108. return value.toString();
  3109. }
  3110. var s = value.toFixed(10);
  3111. var i = s.length - 1;
  3112. if (s[i] !== '0') {
  3113. return s;
  3114. }
  3115. // removing trailing zeros
  3116. do {
  3117. i--;
  3118. } while (s[i] === '0');
  3119. return s.substr(0, s[i] === '.' ? i : i + 1);
  3120. }
  3121. /**
  3122. * Formats transform matrix. The standard rotation, scale and translate
  3123. * matrices are replaced by their shorter forms, and for identity matrix
  3124. * returns empty string to save the memory.
  3125. * @param m {Array} matrix to format.
  3126. * @returns {string}
  3127. */
  3128. function pm(m) {
  3129. if (m[4] === 0 && m[5] === 0) {
  3130. if (m[1] === 0 && m[2] === 0) {
  3131. if (m[0] === 1 && m[3] === 1) {
  3132. return '';
  3133. }
  3134. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3135. }
  3136. if (m[0] === m[3] && m[1] === -m[2]) {
  3137. var a = Math.acos(m[0]) * 180 / Math.PI;
  3138. return 'rotate(' + pf(a) + ')';
  3139. }
  3140. } else {
  3141. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3142. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3143. }
  3144. }
  3145. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3146. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3147. }
  3148. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3149. this.current = new SVGExtraState();
  3150. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3151. this.transformStack = [];
  3152. this.extraStack = [];
  3153. this.commonObjs = commonObjs;
  3154. this.objs = objs;
  3155. this.pendingEOFill = false;
  3156. this.embedFonts = false;
  3157. this.embeddedFonts = Object.create(null);
  3158. this.cssStyle = null;
  3159. this.forceDataSchema = !!forceDataSchema;
  3160. }
  3161. var NS = 'http://www.w3.org/2000/svg';
  3162. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3163. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3164. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3165. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3166. var clipCount = 0;
  3167. var maskCount = 0;
  3168. SVGGraphics.prototype = {
  3169. save: function SVGGraphics_save() {
  3170. this.transformStack.push(this.transformMatrix);
  3171. var old = this.current;
  3172. this.extraStack.push(old);
  3173. this.current = old.clone();
  3174. },
  3175. restore: function SVGGraphics_restore() {
  3176. this.transformMatrix = this.transformStack.pop();
  3177. this.current = this.extraStack.pop();
  3178. this.tgrp = document.createElementNS(NS, 'svg:g');
  3179. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3180. this.pgrp.appendChild(this.tgrp);
  3181. },
  3182. group: function SVGGraphics_group(items) {
  3183. this.save();
  3184. this.executeOpTree(items);
  3185. this.restore();
  3186. },
  3187. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3188. var fnArray = operatorList.fnArray;
  3189. var fnArrayLen = fnArray.length;
  3190. var argsArray = operatorList.argsArray;
  3191. var self = this;
  3192. for (var i = 0; i < fnArrayLen; i++) {
  3193. if (OPS.dependency === fnArray[i]) {
  3194. var deps = argsArray[i];
  3195. for (var n = 0, nn = deps.length; n < nn; n++) {
  3196. var obj = deps[n];
  3197. var common = obj.substring(0, 2) === 'g_';
  3198. var promise;
  3199. if (common) {
  3200. promise = new Promise(function(resolve) {
  3201. self.commonObjs.get(obj, resolve);
  3202. });
  3203. } else {
  3204. promise = new Promise(function(resolve) {
  3205. self.objs.get(obj, resolve);
  3206. });
  3207. }
  3208. this.current.dependencies.push(promise);
  3209. }
  3210. }
  3211. }
  3212. return Promise.all(this.current.dependencies);
  3213. },
  3214. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3215. var transformMatrix = [a, b, c, d, e, f];
  3216. this.transformMatrix = Util.transform(this.transformMatrix,
  3217. transformMatrix);
  3218. this.tgrp = document.createElementNS(NS, 'svg:g');
  3219. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3220. },
  3221. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3222. this.svg = createScratchSVG(viewport.width, viewport.height);
  3223. this.viewport = viewport;
  3224. return this.loadDependencies(operatorList).then(function () {
  3225. this.transformMatrix = IDENTITY_MATRIX;
  3226. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3227. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3228. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3229. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3230. this.defs = document.createElementNS(NS, 'svg:defs');
  3231. this.pgrp.appendChild(this.defs);
  3232. this.pgrp.appendChild(this.tgrp);
  3233. this.svg.appendChild(this.pgrp);
  3234. var opTree = this.convertOpList(operatorList);
  3235. this.executeOpTree(opTree);
  3236. return this.svg;
  3237. }.bind(this));
  3238. },
  3239. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3240. var argsArray = operatorList.argsArray;
  3241. var fnArray = operatorList.fnArray;
  3242. var fnArrayLen = fnArray.length;
  3243. var REVOPS = [];
  3244. var opList = [];
  3245. for (var op in OPS) {
  3246. REVOPS[OPS[op]] = op;
  3247. }
  3248. for (var x = 0; x < fnArrayLen; x++) {
  3249. var fnId = fnArray[x];
  3250. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3251. }
  3252. return opListToTree(opList);
  3253. },
  3254. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3255. var opTreeLen = opTree.length;
  3256. for(var x = 0; x < opTreeLen; x++) {
  3257. var fn = opTree[x].fn;
  3258. var fnId = opTree[x].fnId;
  3259. var args = opTree[x].args;
  3260. switch (fnId | 0) {
  3261. case OPS.beginText:
  3262. this.beginText();
  3263. break;
  3264. case OPS.setLeading:
  3265. this.setLeading(args);
  3266. break;
  3267. case OPS.setLeadingMoveText:
  3268. this.setLeadingMoveText(args[0], args[1]);
  3269. break;
  3270. case OPS.setFont:
  3271. this.setFont(args);
  3272. break;
  3273. case OPS.showText:
  3274. this.showText(args[0]);
  3275. break;
  3276. case OPS.showSpacedText:
  3277. this.showText(args[0]);
  3278. break;
  3279. case OPS.endText:
  3280. this.endText();
  3281. break;
  3282. case OPS.moveText:
  3283. this.moveText(args[0], args[1]);
  3284. break;
  3285. case OPS.setCharSpacing:
  3286. this.setCharSpacing(args[0]);
  3287. break;
  3288. case OPS.setWordSpacing:
  3289. this.setWordSpacing(args[0]);
  3290. break;
  3291. case OPS.setHScale:
  3292. this.setHScale(args[0]);
  3293. break;
  3294. case OPS.setTextMatrix:
  3295. this.setTextMatrix(args[0], args[1], args[2],
  3296. args[3], args[4], args[5]);
  3297. break;
  3298. case OPS.setLineWidth:
  3299. this.setLineWidth(args[0]);
  3300. break;
  3301. case OPS.setLineJoin:
  3302. this.setLineJoin(args[0]);
  3303. break;
  3304. case OPS.setLineCap:
  3305. this.setLineCap(args[0]);
  3306. break;
  3307. case OPS.setMiterLimit:
  3308. this.setMiterLimit(args[0]);
  3309. break;
  3310. case OPS.setFillRGBColor:
  3311. this.setFillRGBColor(args[0], args[1], args[2]);
  3312. break;
  3313. case OPS.setStrokeRGBColor:
  3314. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3315. break;
  3316. case OPS.setDash:
  3317. this.setDash(args[0], args[1]);
  3318. break;
  3319. case OPS.setGState:
  3320. this.setGState(args[0]);
  3321. break;
  3322. case OPS.fill:
  3323. this.fill();
  3324. break;
  3325. case OPS.eoFill:
  3326. this.eoFill();
  3327. break;
  3328. case OPS.stroke:
  3329. this.stroke();
  3330. break;
  3331. case OPS.fillStroke:
  3332. this.fillStroke();
  3333. break;
  3334. case OPS.eoFillStroke:
  3335. this.eoFillStroke();
  3336. break;
  3337. case OPS.clip:
  3338. this.clip('nonzero');
  3339. break;
  3340. case OPS.eoClip:
  3341. this.clip('evenodd');
  3342. break;
  3343. case OPS.paintSolidColorImageMask:
  3344. this.paintSolidColorImageMask();
  3345. break;
  3346. case OPS.paintJpegXObject:
  3347. this.paintJpegXObject(args[0], args[1], args[2]);
  3348. break;
  3349. case OPS.paintImageXObject:
  3350. this.paintImageXObject(args[0]);
  3351. break;
  3352. case OPS.paintInlineImageXObject:
  3353. this.paintInlineImageXObject(args[0]);
  3354. break;
  3355. case OPS.paintImageMaskXObject:
  3356. this.paintImageMaskXObject(args[0]);
  3357. break;
  3358. case OPS.paintFormXObjectBegin:
  3359. this.paintFormXObjectBegin(args[0], args[1]);
  3360. break;
  3361. case OPS.paintFormXObjectEnd:
  3362. this.paintFormXObjectEnd();
  3363. break;
  3364. case OPS.closePath:
  3365. this.closePath();
  3366. break;
  3367. case OPS.closeStroke:
  3368. this.closeStroke();
  3369. break;
  3370. case OPS.closeFillStroke:
  3371. this.closeFillStroke();
  3372. break;
  3373. case OPS.nextLine:
  3374. this.nextLine();
  3375. break;
  3376. case OPS.transform:
  3377. this.transform(args[0], args[1], args[2], args[3],
  3378. args[4], args[5]);
  3379. break;
  3380. case OPS.constructPath:
  3381. this.constructPath(args[0], args[1]);
  3382. break;
  3383. case OPS.endPath:
  3384. this.endPath();
  3385. break;
  3386. case 92:
  3387. this.group(opTree[x].items);
  3388. break;
  3389. default:
  3390. warn('Unimplemented method '+ fn);
  3391. break;
  3392. }
  3393. }
  3394. },
  3395. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3396. this.current.wordSpacing = wordSpacing;
  3397. },
  3398. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3399. this.current.charSpacing = charSpacing;
  3400. },
  3401. nextLine: function SVGGraphics_nextLine() {
  3402. this.moveText(0, this.current.leading);
  3403. },
  3404. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3405. var current = this.current;
  3406. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3407. this.current.x = this.current.lineX = 0;
  3408. this.current.y = this.current.lineY = 0;
  3409. current.xcoords = [];
  3410. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3411. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3412. current.tspan.setAttributeNS(null, 'font-size',
  3413. pf(current.fontSize) + 'px');
  3414. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3415. current.txtElement = document.createElementNS(NS, 'svg:text');
  3416. current.txtElement.appendChild(current.tspan);
  3417. },
  3418. beginText: function SVGGraphics_beginText() {
  3419. this.current.x = this.current.lineX = 0;
  3420. this.current.y = this.current.lineY = 0;
  3421. this.current.textMatrix = IDENTITY_MATRIX;
  3422. this.current.lineMatrix = IDENTITY_MATRIX;
  3423. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3424. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3425. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3426. this.current.xcoords = [];
  3427. },
  3428. moveText: function SVGGraphics_moveText(x, y) {
  3429. var current = this.current;
  3430. this.current.x = this.current.lineX += x;
  3431. this.current.y = this.current.lineY += y;
  3432. current.xcoords = [];
  3433. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3434. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3435. current.tspan.setAttributeNS(null, 'font-size',
  3436. pf(current.fontSize) + 'px');
  3437. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3438. },
  3439. showText: function SVGGraphics_showText(glyphs) {
  3440. var current = this.current;
  3441. var font = current.font;
  3442. var fontSize = current.fontSize;
  3443. if (fontSize === 0) {
  3444. return;
  3445. }
  3446. var charSpacing = current.charSpacing;
  3447. var wordSpacing = current.wordSpacing;
  3448. var fontDirection = current.fontDirection;
  3449. var textHScale = current.textHScale * fontDirection;
  3450. var glyphsLength = glyphs.length;
  3451. var vertical = font.vertical;
  3452. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3453. var x = 0, i;
  3454. for (i = 0; i < glyphsLength; ++i) {
  3455. var glyph = glyphs[i];
  3456. if (glyph === null) {
  3457. // word break
  3458. x += fontDirection * wordSpacing;
  3459. continue;
  3460. } else if (isNum(glyph)) {
  3461. x += -glyph * fontSize * 0.001;
  3462. continue;
  3463. }
  3464. current.xcoords.push(current.x + x * textHScale);
  3465. var width = glyph.width;
  3466. var character = glyph.fontChar;
  3467. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3468. x += charWidth;
  3469. current.tspan.textContent += character;
  3470. }
  3471. if (vertical) {
  3472. current.y -= x * textHScale;
  3473. } else {
  3474. current.x += x * textHScale;
  3475. }
  3476. current.tspan.setAttributeNS(null, 'x',
  3477. current.xcoords.map(pf).join(' '));
  3478. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3479. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3480. current.tspan.setAttributeNS(null, 'font-size',
  3481. pf(current.fontSize) + 'px');
  3482. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3483. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3484. }
  3485. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3486. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3487. }
  3488. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3489. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3490. }
  3491. current.txtElement.setAttributeNS(null, 'transform',
  3492. pm(current.textMatrix) +
  3493. ' scale(1, -1)' );
  3494. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3495. current.txtElement.appendChild(current.tspan);
  3496. current.txtgrp.appendChild(current.txtElement);
  3497. this.tgrp.appendChild(current.txtElement);
  3498. },
  3499. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3500. this.setLeading(-y);
  3501. this.moveText(x, y);
  3502. },
  3503. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3504. if (!this.cssStyle) {
  3505. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3506. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3507. this.defs.appendChild(this.cssStyle);
  3508. }
  3509. var url = createObjectURL(fontObj.data, fontObj.mimetype,
  3510. this.forceDataSchema);
  3511. this.cssStyle.textContent +=
  3512. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3513. ' src: url(' + url + '); }\n';
  3514. },
  3515. setFont: function SVGGraphics_setFont(details) {
  3516. var current = this.current;
  3517. var fontObj = this.commonObjs.get(details[0]);
  3518. var size = details[1];
  3519. this.current.font = fontObj;
  3520. if (this.embedFonts && fontObj.data &&
  3521. !this.embeddedFonts[fontObj.loadedName]) {
  3522. this.addFontStyle(fontObj);
  3523. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3524. }
  3525. current.fontMatrix = (fontObj.fontMatrix ?
  3526. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3527. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3528. (fontObj.bold ? 'bold' : 'normal');
  3529. var italic = fontObj.italic ? 'italic' : 'normal';
  3530. if (size < 0) {
  3531. size = -size;
  3532. current.fontDirection = -1;
  3533. } else {
  3534. current.fontDirection = 1;
  3535. }
  3536. current.fontSize = size;
  3537. current.fontFamily = fontObj.loadedName;
  3538. current.fontWeight = bold;
  3539. current.fontStyle = italic;
  3540. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3541. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3542. current.xcoords = [];
  3543. },
  3544. endText: function SVGGraphics_endText() {
  3545. if (this.current.pendingClip) {
  3546. this.cgrp.appendChild(this.tgrp);
  3547. this.pgrp.appendChild(this.cgrp);
  3548. } else {
  3549. this.pgrp.appendChild(this.tgrp);
  3550. }
  3551. this.tgrp = document.createElementNS(NS, 'svg:g');
  3552. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3553. },
  3554. // Path properties
  3555. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3556. this.current.lineWidth = width;
  3557. },
  3558. setLineCap: function SVGGraphics_setLineCap(style) {
  3559. this.current.lineCap = LINE_CAP_STYLES[style];
  3560. },
  3561. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3562. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3563. },
  3564. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3565. this.current.miterLimit = limit;
  3566. },
  3567. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3568. var color = Util.makeCssRgb(r, g, b);
  3569. this.current.strokeColor = color;
  3570. },
  3571. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3572. var color = Util.makeCssRgb(r, g, b);
  3573. this.current.fillColor = color;
  3574. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3575. this.current.xcoords = [];
  3576. },
  3577. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3578. this.current.dashArray = dashArray;
  3579. this.current.dashPhase = dashPhase;
  3580. },
  3581. constructPath: function SVGGraphics_constructPath(ops, args) {
  3582. var current = this.current;
  3583. var x = current.x, y = current.y;
  3584. current.path = document.createElementNS(NS, 'svg:path');
  3585. var d = [];
  3586. var opLength = ops.length;
  3587. for (var i = 0, j = 0; i < opLength; i++) {
  3588. switch (ops[i] | 0) {
  3589. case OPS.rectangle:
  3590. x = args[j++];
  3591. y = args[j++];
  3592. var width = args[j++];
  3593. var height = args[j++];
  3594. var xw = x + width;
  3595. var yh = y + height;
  3596. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  3597. 'L', pf(x), pf(yh), 'Z');
  3598. break;
  3599. case OPS.moveTo:
  3600. x = args[j++];
  3601. y = args[j++];
  3602. d.push('M', pf(x), pf(y));
  3603. break;
  3604. case OPS.lineTo:
  3605. x = args[j++];
  3606. y = args[j++];
  3607. d.push('L', pf(x) , pf(y));
  3608. break;
  3609. case OPS.curveTo:
  3610. x = args[j + 4];
  3611. y = args[j + 5];
  3612. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  3613. pf(args[j + 3]), pf(x), pf(y));
  3614. j += 6;
  3615. break;
  3616. case OPS.curveTo2:
  3617. x = args[j + 2];
  3618. y = args[j + 3];
  3619. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  3620. pf(args[j + 2]), pf(args[j + 3]));
  3621. j += 4;
  3622. break;
  3623. case OPS.curveTo3:
  3624. x = args[j + 2];
  3625. y = args[j + 3];
  3626. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  3627. pf(x), pf(y));
  3628. j += 4;
  3629. break;
  3630. case OPS.closePath:
  3631. d.push('Z');
  3632. break;
  3633. }
  3634. }
  3635. current.path.setAttributeNS(null, 'd', d.join(' '));
  3636. current.path.setAttributeNS(null, 'stroke-miterlimit',
  3637. pf(current.miterLimit));
  3638. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3639. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3640. current.path.setAttributeNS(null, 'stroke-width',
  3641. pf(current.lineWidth) + 'px');
  3642. current.path.setAttributeNS(null, 'stroke-dasharray',
  3643. current.dashArray.map(pf).join(' '));
  3644. current.path.setAttributeNS(null, 'stroke-dashoffset',
  3645. pf(current.dashPhase) + 'px');
  3646. current.path.setAttributeNS(null, 'fill', 'none');
  3647. this.tgrp.appendChild(current.path);
  3648. if (current.pendingClip) {
  3649. this.cgrp.appendChild(this.tgrp);
  3650. this.pgrp.appendChild(this.cgrp);
  3651. } else {
  3652. this.pgrp.appendChild(this.tgrp);
  3653. }
  3654. // Saving a reference in current.element so that it can be addressed
  3655. // in 'fill' and 'stroke'
  3656. current.element = current.path;
  3657. current.setCurrentPoint(x, y);
  3658. },
  3659. endPath: function SVGGraphics_endPath() {
  3660. var current = this.current;
  3661. if (current.pendingClip) {
  3662. this.cgrp.appendChild(this.tgrp);
  3663. this.pgrp.appendChild(this.cgrp);
  3664. } else {
  3665. this.pgrp.appendChild(this.tgrp);
  3666. }
  3667. this.tgrp = document.createElementNS(NS, 'svg:g');
  3668. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3669. },
  3670. clip: function SVGGraphics_clip(type) {
  3671. var current = this.current;
  3672. // Add current path to clipping path
  3673. current.clipId = 'clippath' + clipCount;
  3674. clipCount++;
  3675. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3676. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3677. var clipElement = current.element.cloneNode();
  3678. if (type === 'evenodd') {
  3679. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3680. } else {
  3681. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3682. }
  3683. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3684. this.clippath.appendChild(clipElement);
  3685. this.defs.appendChild(this.clippath);
  3686. // Create a new group with that attribute
  3687. current.pendingClip = true;
  3688. this.cgrp = document.createElementNS(NS, 'svg:g');
  3689. this.cgrp.setAttributeNS(null, 'clip-path',
  3690. 'url(#' + current.clipId + ')');
  3691. this.pgrp.appendChild(this.cgrp);
  3692. },
  3693. closePath: function SVGGraphics_closePath() {
  3694. var current = this.current;
  3695. var d = current.path.getAttributeNS(null, 'd');
  3696. d += 'Z';
  3697. current.path.setAttributeNS(null, 'd', d);
  3698. },
  3699. setLeading: function SVGGraphics_setLeading(leading) {
  3700. this.current.leading = -leading;
  3701. },
  3702. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3703. this.current.textRise = textRise;
  3704. },
  3705. setHScale: function SVGGraphics_setHScale(scale) {
  3706. this.current.textHScale = scale / 100;
  3707. },
  3708. setGState: function SVGGraphics_setGState(states) {
  3709. for (var i = 0, ii = states.length; i < ii; i++) {
  3710. var state = states[i];
  3711. var key = state[0];
  3712. var value = state[1];
  3713. switch (key) {
  3714. case 'LW':
  3715. this.setLineWidth(value);
  3716. break;
  3717. case 'LC':
  3718. this.setLineCap(value);
  3719. break;
  3720. case 'LJ':
  3721. this.setLineJoin(value);
  3722. break;
  3723. case 'ML':
  3724. this.setMiterLimit(value);
  3725. break;
  3726. case 'D':
  3727. this.setDash(value[0], value[1]);
  3728. break;
  3729. case 'RI':
  3730. break;
  3731. case 'FL':
  3732. break;
  3733. case 'Font':
  3734. this.setFont(value);
  3735. break;
  3736. case 'CA':
  3737. break;
  3738. case 'ca':
  3739. break;
  3740. case 'BM':
  3741. break;
  3742. case 'SMask':
  3743. break;
  3744. }
  3745. }
  3746. },
  3747. fill: function SVGGraphics_fill() {
  3748. var current = this.current;
  3749. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3750. },
  3751. stroke: function SVGGraphics_stroke() {
  3752. var current = this.current;
  3753. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3754. current.element.setAttributeNS(null, 'fill', 'none');
  3755. },
  3756. eoFill: function SVGGraphics_eoFill() {
  3757. var current = this.current;
  3758. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3759. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3760. },
  3761. fillStroke: function SVGGraphics_fillStroke() {
  3762. // Order is important since stroke wants fill to be none.
  3763. // First stroke, then if fill needed, it will be overwritten.
  3764. this.stroke();
  3765. this.fill();
  3766. },
  3767. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3768. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3769. this.fillStroke();
  3770. },
  3771. closeStroke: function SVGGraphics_closeStroke() {
  3772. this.closePath();
  3773. this.stroke();
  3774. },
  3775. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3776. this.closePath();
  3777. this.fillStroke();
  3778. },
  3779. paintSolidColorImageMask:
  3780. function SVGGraphics_paintSolidColorImageMask() {
  3781. var current = this.current;
  3782. var rect = document.createElementNS(NS, 'svg:rect');
  3783. rect.setAttributeNS(null, 'x', '0');
  3784. rect.setAttributeNS(null, 'y', '0');
  3785. rect.setAttributeNS(null, 'width', '1px');
  3786. rect.setAttributeNS(null, 'height', '1px');
  3787. rect.setAttributeNS(null, 'fill', current.fillColor);
  3788. this.tgrp.appendChild(rect);
  3789. },
  3790. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3791. var current = this.current;
  3792. var imgObj = this.objs.get(objId);
  3793. var imgEl = document.createElementNS(NS, 'svg:image');
  3794. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3795. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3796. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3797. imgEl.setAttributeNS(null, 'x', '0');
  3798. imgEl.setAttributeNS(null, 'y', pf(-h));
  3799. imgEl.setAttributeNS(null, 'transform',
  3800. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3801. this.tgrp.appendChild(imgEl);
  3802. if (current.pendingClip) {
  3803. this.cgrp.appendChild(this.tgrp);
  3804. this.pgrp.appendChild(this.cgrp);
  3805. } else {
  3806. this.pgrp.appendChild(this.tgrp);
  3807. }
  3808. },
  3809. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3810. var imgData = this.objs.get(objId);
  3811. if (!imgData) {
  3812. warn('Dependent image isn\'t ready yet');
  3813. return;
  3814. }
  3815. this.paintInlineImageXObject(imgData);
  3816. },
  3817. paintInlineImageXObject:
  3818. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3819. var current = this.current;
  3820. var width = imgData.width;
  3821. var height = imgData.height;
  3822. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3823. var cliprect = document.createElementNS(NS, 'svg:rect');
  3824. cliprect.setAttributeNS(null, 'x', '0');
  3825. cliprect.setAttributeNS(null, 'y', '0');
  3826. cliprect.setAttributeNS(null, 'width', pf(width));
  3827. cliprect.setAttributeNS(null, 'height', pf(height));
  3828. current.element = cliprect;
  3829. this.clip('nonzero');
  3830. var imgEl = document.createElementNS(NS, 'svg:image');
  3831. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3832. imgEl.setAttributeNS(null, 'x', '0');
  3833. imgEl.setAttributeNS(null, 'y', pf(-height));
  3834. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3835. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3836. imgEl.setAttributeNS(null, 'transform',
  3837. 'scale(' + pf(1 / width) + ' ' +
  3838. pf(-1 / height) + ')');
  3839. if (mask) {
  3840. mask.appendChild(imgEl);
  3841. } else {
  3842. this.tgrp.appendChild(imgEl);
  3843. }
  3844. if (current.pendingClip) {
  3845. this.cgrp.appendChild(this.tgrp);
  3846. this.pgrp.appendChild(this.cgrp);
  3847. } else {
  3848. this.pgrp.appendChild(this.tgrp);
  3849. }
  3850. },
  3851. paintImageMaskXObject:
  3852. function SVGGraphics_paintImageMaskXObject(imgData) {
  3853. var current = this.current;
  3854. var width = imgData.width;
  3855. var height = imgData.height;
  3856. var fillColor = current.fillColor;
  3857. current.maskId = 'mask' + maskCount++;
  3858. var mask = document.createElementNS(NS, 'svg:mask');
  3859. mask.setAttributeNS(null, 'id', current.maskId);
  3860. var rect = document.createElementNS(NS, 'svg:rect');
  3861. rect.setAttributeNS(null, 'x', '0');
  3862. rect.setAttributeNS(null, 'y', '0');
  3863. rect.setAttributeNS(null, 'width', pf(width));
  3864. rect.setAttributeNS(null, 'height', pf(height));
  3865. rect.setAttributeNS(null, 'fill', fillColor);
  3866. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  3867. this.defs.appendChild(mask);
  3868. this.tgrp.appendChild(rect);
  3869. this.paintInlineImageXObject(imgData, mask);
  3870. },
  3871. paintFormXObjectBegin:
  3872. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3873. this.save();
  3874. if (isArray(matrix) && matrix.length === 6) {
  3875. this.transform(matrix[0], matrix[1], matrix[2],
  3876. matrix[3], matrix[4], matrix[5]);
  3877. }
  3878. if (isArray(bbox) && bbox.length === 4) {
  3879. var width = bbox[2] - bbox[0];
  3880. var height = bbox[3] - bbox[1];
  3881. var cliprect = document.createElementNS(NS, 'svg:rect');
  3882. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3883. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3884. cliprect.setAttributeNS(null, 'width', pf(width));
  3885. cliprect.setAttributeNS(null, 'height', pf(height));
  3886. this.current.element = cliprect;
  3887. this.clip('nonzero');
  3888. this.endPath();
  3889. }
  3890. },
  3891. paintFormXObjectEnd:
  3892. function SVGGraphics_paintFormXObjectEnd() {
  3893. this.restore();
  3894. }
  3895. };
  3896. return SVGGraphics;
  3897. })();
  3898. exports.SVGGraphics = SVGGraphics;
  3899. }));
  3900. (function (root, factory) {
  3901. {
  3902. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  3903. root.pdfjsDisplayDOMUtils);
  3904. }
  3905. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3906. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3907. var AnnotationType = sharedUtil.AnnotationType;
  3908. var Util = sharedUtil.Util;
  3909. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3910. var LinkTarget = displayDOMUtils.LinkTarget;
  3911. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3912. var warn = sharedUtil.warn;
  3913. var CustomStyle = displayDOMUtils.CustomStyle;
  3914. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3915. /**
  3916. * @typedef {Object} AnnotationElementParameters
  3917. * @property {Object} data
  3918. * @property {HTMLDivElement} layer
  3919. * @property {PDFPage} page
  3920. * @property {PageViewport} viewport
  3921. * @property {IPDFLinkService} linkService
  3922. * @property {DownloadManager} downloadManager
  3923. * @property {string} imageResourcesPath
  3924. * @property {boolean} renderInteractiveForms
  3925. */
  3926. /**
  3927. * @class
  3928. * @alias AnnotationElementFactory
  3929. */
  3930. function AnnotationElementFactory() {}
  3931. AnnotationElementFactory.prototype =
  3932. /** @lends AnnotationElementFactory.prototype */ {
  3933. /**
  3934. * @param {AnnotationElementParameters} parameters
  3935. * @returns {AnnotationElement}
  3936. */
  3937. create: function AnnotationElementFactory_create(parameters) {
  3938. var subtype = parameters.data.annotationType;
  3939. switch (subtype) {
  3940. case AnnotationType.LINK:
  3941. return new LinkAnnotationElement(parameters);
  3942. case AnnotationType.TEXT:
  3943. return new TextAnnotationElement(parameters);
  3944. case AnnotationType.WIDGET:
  3945. var fieldType = parameters.data.fieldType;
  3946. switch (fieldType) {
  3947. case 'Tx':
  3948. return new TextWidgetAnnotationElement(parameters);
  3949. }
  3950. return new WidgetAnnotationElement(parameters);
  3951. case AnnotationType.POPUP:
  3952. return new PopupAnnotationElement(parameters);
  3953. case AnnotationType.HIGHLIGHT:
  3954. return new HighlightAnnotationElement(parameters);
  3955. case AnnotationType.UNDERLINE:
  3956. return new UnderlineAnnotationElement(parameters);
  3957. case AnnotationType.SQUIGGLY:
  3958. return new SquigglyAnnotationElement(parameters);
  3959. case AnnotationType.STRIKEOUT:
  3960. return new StrikeOutAnnotationElement(parameters);
  3961. case AnnotationType.FILEATTACHMENT:
  3962. return new FileAttachmentAnnotationElement(parameters);
  3963. default:
  3964. return new AnnotationElement(parameters);
  3965. }
  3966. }
  3967. };
  3968. /**
  3969. * @class
  3970. * @alias AnnotationElement
  3971. */
  3972. var AnnotationElement = (function AnnotationElementClosure() {
  3973. function AnnotationElement(parameters, isRenderable) {
  3974. this.isRenderable = isRenderable || false;
  3975. this.data = parameters.data;
  3976. this.layer = parameters.layer;
  3977. this.page = parameters.page;
  3978. this.viewport = parameters.viewport;
  3979. this.linkService = parameters.linkService;
  3980. this.downloadManager = parameters.downloadManager;
  3981. this.imageResourcesPath = parameters.imageResourcesPath;
  3982. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3983. if (isRenderable) {
  3984. this.container = this._createContainer();
  3985. }
  3986. }
  3987. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  3988. /**
  3989. * Create an empty container for the annotation's HTML element.
  3990. *
  3991. * @private
  3992. * @memberof AnnotationElement
  3993. * @returns {HTMLSectionElement}
  3994. */
  3995. _createContainer: function AnnotationElement_createContainer() {
  3996. var data = this.data, page = this.page, viewport = this.viewport;
  3997. var container = document.createElement('section');
  3998. var width = data.rect[2] - data.rect[0];
  3999. var height = data.rect[3] - data.rect[1];
  4000. container.setAttribute('data-annotation-id', data.id);
  4001. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4002. // position on subsequent calls to `_createContainer` (see issue 6804).
  4003. var rect = Util.normalizeRect([
  4004. data.rect[0],
  4005. page.view[3] - data.rect[1] + page.view[1],
  4006. data.rect[2],
  4007. page.view[3] - data.rect[3] + page.view[1]
  4008. ]);
  4009. CustomStyle.setProp('transform', container,
  4010. 'matrix(' + viewport.transform.join(',') + ')');
  4011. CustomStyle.setProp('transformOrigin', container,
  4012. -rect[0] + 'px ' + -rect[1] + 'px');
  4013. if (data.borderStyle.width > 0) {
  4014. container.style.borderWidth = data.borderStyle.width + 'px';
  4015. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4016. // Underline styles only have a bottom border, so we do not need
  4017. // to adjust for all borders. This yields a similar result as
  4018. // Adobe Acrobat/Reader.
  4019. width = width - 2 * data.borderStyle.width;
  4020. height = height - 2 * data.borderStyle.width;
  4021. }
  4022. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4023. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4024. if (horizontalRadius > 0 || verticalRadius > 0) {
  4025. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4026. CustomStyle.setProp('borderRadius', container, radius);
  4027. }
  4028. switch (data.borderStyle.style) {
  4029. case AnnotationBorderStyleType.SOLID:
  4030. container.style.borderStyle = 'solid';
  4031. break;
  4032. case AnnotationBorderStyleType.DASHED:
  4033. container.style.borderStyle = 'dashed';
  4034. break;
  4035. case AnnotationBorderStyleType.BEVELED:
  4036. warn('Unimplemented border style: beveled');
  4037. break;
  4038. case AnnotationBorderStyleType.INSET:
  4039. warn('Unimplemented border style: inset');
  4040. break;
  4041. case AnnotationBorderStyleType.UNDERLINE:
  4042. container.style.borderBottomStyle = 'solid';
  4043. break;
  4044. default:
  4045. break;
  4046. }
  4047. if (data.color) {
  4048. container.style.borderColor =
  4049. Util.makeCssRgb(data.color[0] | 0,
  4050. data.color[1] | 0,
  4051. data.color[2] | 0);
  4052. } else {
  4053. // Transparent (invisible) border, so do not draw it at all.
  4054. container.style.borderWidth = 0;
  4055. }
  4056. }
  4057. container.style.left = rect[0] + 'px';
  4058. container.style.top = rect[1] + 'px';
  4059. container.style.width = width + 'px';
  4060. container.style.height = height + 'px';
  4061. return container;
  4062. },
  4063. /**
  4064. * Create a popup for the annotation's HTML element. This is used for
  4065. * annotations that do not have a Popup entry in the dictionary, but
  4066. * are of a type that works with popups (such as Highlight annotations).
  4067. *
  4068. * @private
  4069. * @param {HTMLSectionElement} container
  4070. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4071. * @param {Object} data
  4072. * @memberof AnnotationElement
  4073. */
  4074. _createPopup:
  4075. function AnnotationElement_createPopup(container, trigger, data) {
  4076. // If no trigger element is specified, create it.
  4077. if (!trigger) {
  4078. trigger = document.createElement('div');
  4079. trigger.style.height = container.style.height;
  4080. trigger.style.width = container.style.width;
  4081. container.appendChild(trigger);
  4082. }
  4083. var popupElement = new PopupElement({
  4084. container: container,
  4085. trigger: trigger,
  4086. color: data.color,
  4087. title: data.title,
  4088. contents: data.contents,
  4089. hideWrapper: true
  4090. });
  4091. var popup = popupElement.render();
  4092. // Position the popup next to the annotation's container.
  4093. popup.style.left = container.style.width;
  4094. container.appendChild(popup);
  4095. },
  4096. /**
  4097. * Render the annotation's HTML element in the empty container.
  4098. *
  4099. * @public
  4100. * @memberof AnnotationElement
  4101. */
  4102. render: function AnnotationElement_render() {
  4103. throw new Error('Abstract method AnnotationElement.render called');
  4104. }
  4105. };
  4106. return AnnotationElement;
  4107. })();
  4108. /**
  4109. * @class
  4110. * @alias LinkAnnotationElement
  4111. */
  4112. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  4113. function LinkAnnotationElement(parameters) {
  4114. AnnotationElement.call(this, parameters, true);
  4115. }
  4116. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4117. /**
  4118. * Render the link annotation's HTML element in the empty container.
  4119. *
  4120. * @public
  4121. * @memberof LinkAnnotationElement
  4122. * @returns {HTMLSectionElement}
  4123. */
  4124. render: function LinkAnnotationElement_render() {
  4125. this.container.className = 'linkAnnotation';
  4126. var link = document.createElement('a');
  4127. addLinkAttributes(link, {
  4128. url: this.data.url,
  4129. target: (this.data.newWindow ? LinkTarget.BLANK : undefined),
  4130. });
  4131. if (!this.data.url) {
  4132. if (this.data.action) {
  4133. this._bindNamedAction(link, this.data.action);
  4134. } else {
  4135. this._bindLink(link, (this.data.dest || null));
  4136. }
  4137. }
  4138. this.container.appendChild(link);
  4139. return this.container;
  4140. },
  4141. /**
  4142. * Bind internal links to the link element.
  4143. *
  4144. * @private
  4145. * @param {Object} link
  4146. * @param {Object} destination
  4147. * @memberof LinkAnnotationElement
  4148. */
  4149. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4150. var self = this;
  4151. link.href = this.linkService.getDestinationHash(destination);
  4152. link.onclick = function() {
  4153. if (destination) {
  4154. self.linkService.navigateTo(destination);
  4155. }
  4156. return false;
  4157. };
  4158. if (destination) {
  4159. link.className = 'internalLink';
  4160. }
  4161. },
  4162. /**
  4163. * Bind named actions to the link element.
  4164. *
  4165. * @private
  4166. * @param {Object} link
  4167. * @param {Object} action
  4168. * @memberof LinkAnnotationElement
  4169. */
  4170. _bindNamedAction:
  4171. function LinkAnnotationElement_bindNamedAction(link, action) {
  4172. var self = this;
  4173. link.href = this.linkService.getAnchorUrl('');
  4174. link.onclick = function() {
  4175. self.linkService.executeNamedAction(action);
  4176. return false;
  4177. };
  4178. link.className = 'internalLink';
  4179. }
  4180. });
  4181. return LinkAnnotationElement;
  4182. })();
  4183. /**
  4184. * @class
  4185. * @alias TextAnnotationElement
  4186. */
  4187. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  4188. function TextAnnotationElement(parameters) {
  4189. var isRenderable = !!(parameters.data.hasPopup ||
  4190. parameters.data.title || parameters.data.contents);
  4191. AnnotationElement.call(this, parameters, isRenderable);
  4192. }
  4193. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4194. /**
  4195. * Render the text annotation's HTML element in the empty container.
  4196. *
  4197. * @public
  4198. * @memberof TextAnnotationElement
  4199. * @returns {HTMLSectionElement}
  4200. */
  4201. render: function TextAnnotationElement_render() {
  4202. this.container.className = 'textAnnotation';
  4203. var image = document.createElement('img');
  4204. image.style.height = this.container.style.height;
  4205. image.style.width = this.container.style.width;
  4206. image.src = this.imageResourcesPath + 'annotation-' +
  4207. this.data.name.toLowerCase() + '.svg';
  4208. image.alt = '[{{type}} Annotation]';
  4209. image.dataset.l10nId = 'text_annotation_type';
  4210. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  4211. if (!this.data.hasPopup) {
  4212. this._createPopup(this.container, image, this.data);
  4213. }
  4214. this.container.appendChild(image);
  4215. return this.container;
  4216. }
  4217. });
  4218. return TextAnnotationElement;
  4219. })();
  4220. /**
  4221. * @class
  4222. * @alias WidgetAnnotationElement
  4223. */
  4224. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  4225. function WidgetAnnotationElement(parameters) {
  4226. var isRenderable = parameters.renderInteractiveForms ||
  4227. (!parameters.data.hasAppearance && !!parameters.data.fieldValue);
  4228. AnnotationElement.call(this, parameters, isRenderable);
  4229. }
  4230. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4231. /**
  4232. * Render the widget annotation's HTML element in the empty container.
  4233. *
  4234. * @public
  4235. * @memberof WidgetAnnotationElement
  4236. * @returns {HTMLSectionElement}
  4237. */
  4238. render: function WidgetAnnotationElement_render() {
  4239. // Show only the container for unsupported field types.
  4240. return this.container;
  4241. }
  4242. });
  4243. return WidgetAnnotationElement;
  4244. })();
  4245. /**
  4246. * @class
  4247. * @alias TextWidgetAnnotationElement
  4248. */
  4249. var TextWidgetAnnotationElement = (
  4250. function TextWidgetAnnotationElementClosure() {
  4251. var TEXT_ALIGNMENT = ['left', 'center', 'right'];
  4252. function TextWidgetAnnotationElement(parameters) {
  4253. WidgetAnnotationElement.call(this, parameters);
  4254. }
  4255. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4256. /**
  4257. * Render the text widget annotation's HTML element in the empty container.
  4258. *
  4259. * @public
  4260. * @memberof TextWidgetAnnotationElement
  4261. * @returns {HTMLSectionElement}
  4262. */
  4263. render: function TextWidgetAnnotationElement_render() {
  4264. this.container.className = 'textWidgetAnnotation';
  4265. var element = null;
  4266. if (this.renderInteractiveForms) {
  4267. if (this.data.multiLine) {
  4268. element = document.createElement('textarea');
  4269. } else {
  4270. element = document.createElement('input');
  4271. element.type = 'text';
  4272. }
  4273. element.value = this.data.fieldValue;
  4274. element.disabled = this.data.readOnly;
  4275. if (this.data.maxLen !== null) {
  4276. element.maxLength = this.data.maxLen;
  4277. }
  4278. } else {
  4279. element = document.createElement('div');
  4280. element.textContent = this.data.fieldValue;
  4281. element.style.verticalAlign = 'middle';
  4282. element.style.display = 'table-cell';
  4283. var font = null;
  4284. if (this.data.fontRefName) {
  4285. font = this.page.commonObjs.getData(this.data.fontRefName);
  4286. }
  4287. this._setTextStyle(element, font);
  4288. }
  4289. if (this.data.textAlignment !== null) {
  4290. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4291. }
  4292. this.container.appendChild(element);
  4293. return this.container;
  4294. },
  4295. /**
  4296. * Apply text styles to the text in the element.
  4297. *
  4298. * @private
  4299. * @param {HTMLDivElement} element
  4300. * @param {Object} font
  4301. * @memberof TextWidgetAnnotationElement
  4302. */
  4303. _setTextStyle:
  4304. function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4305. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4306. var style = element.style;
  4307. style.fontSize = this.data.fontSize + 'px';
  4308. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  4309. if (!font) {
  4310. return;
  4311. }
  4312. style.fontWeight = (font.black ?
  4313. (font.bold ? '900' : 'bold') :
  4314. (font.bold ? 'bold' : 'normal'));
  4315. style.fontStyle = (font.italic ? 'italic' : 'normal');
  4316. // Use a reasonable default font if the font doesn't specify a fallback.
  4317. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4318. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4319. style.fontFamily = fontFamily + fallbackName;
  4320. }
  4321. });
  4322. return TextWidgetAnnotationElement;
  4323. })();
  4324. /**
  4325. * @class
  4326. * @alias PopupAnnotationElement
  4327. */
  4328. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  4329. function PopupAnnotationElement(parameters) {
  4330. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4331. AnnotationElement.call(this, parameters, isRenderable);
  4332. }
  4333. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4334. /**
  4335. * Render the popup annotation's HTML element in the empty container.
  4336. *
  4337. * @public
  4338. * @memberof PopupAnnotationElement
  4339. * @returns {HTMLSectionElement}
  4340. */
  4341. render: function PopupAnnotationElement_render() {
  4342. this.container.className = 'popupAnnotation';
  4343. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4344. var parentElement = this.layer.querySelector(selector);
  4345. if (!parentElement) {
  4346. return this.container;
  4347. }
  4348. var popup = new PopupElement({
  4349. container: this.container,
  4350. trigger: parentElement,
  4351. color: this.data.color,
  4352. title: this.data.title,
  4353. contents: this.data.contents
  4354. });
  4355. // Position the popup next to the parent annotation's container.
  4356. // PDF viewers ignore a popup annotation's rectangle.
  4357. var parentLeft = parseFloat(parentElement.style.left);
  4358. var parentWidth = parseFloat(parentElement.style.width);
  4359. CustomStyle.setProp('transformOrigin', this.container,
  4360. -(parentLeft + parentWidth) + 'px -' +
  4361. parentElement.style.top);
  4362. this.container.style.left = (parentLeft + parentWidth) + 'px';
  4363. this.container.appendChild(popup.render());
  4364. return this.container;
  4365. }
  4366. });
  4367. return PopupAnnotationElement;
  4368. })();
  4369. /**
  4370. * @class
  4371. * @alias PopupElement
  4372. */
  4373. var PopupElement = (function PopupElementClosure() {
  4374. var BACKGROUND_ENLIGHT = 0.7;
  4375. function PopupElement(parameters) {
  4376. this.container = parameters.container;
  4377. this.trigger = parameters.trigger;
  4378. this.color = parameters.color;
  4379. this.title = parameters.title;
  4380. this.contents = parameters.contents;
  4381. this.hideWrapper = parameters.hideWrapper || false;
  4382. this.pinned = false;
  4383. }
  4384. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  4385. /**
  4386. * Render the popup's HTML element.
  4387. *
  4388. * @public
  4389. * @memberof PopupElement
  4390. * @returns {HTMLSectionElement}
  4391. */
  4392. render: function PopupElement_render() {
  4393. var wrapper = document.createElement('div');
  4394. wrapper.className = 'popupWrapper';
  4395. // For Popup annotations we hide the entire section because it contains
  4396. // only the popup. However, for Text annotations without a separate Popup
  4397. // annotation, we cannot hide the entire container as the image would
  4398. // disappear too. In that special case, hiding the wrapper suffices.
  4399. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  4400. this.hideElement.setAttribute('hidden', true);
  4401. var popup = document.createElement('div');
  4402. popup.className = 'popup';
  4403. var color = this.color;
  4404. if (color) {
  4405. // Enlighten the color.
  4406. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4407. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4408. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4409. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4410. }
  4411. var contents = this._formatContents(this.contents);
  4412. var title = document.createElement('h1');
  4413. title.textContent = this.title;
  4414. // Attach the event listeners to the trigger element.
  4415. this.trigger.addEventListener('click', this._toggle.bind(this));
  4416. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4417. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4418. popup.addEventListener('click', this._hide.bind(this, true));
  4419. popup.appendChild(title);
  4420. popup.appendChild(contents);
  4421. wrapper.appendChild(popup);
  4422. return wrapper;
  4423. },
  4424. /**
  4425. * Format the contents of the popup by adding newlines where necessary.
  4426. *
  4427. * @private
  4428. * @param {string} contents
  4429. * @memberof PopupElement
  4430. * @returns {HTMLParagraphElement}
  4431. */
  4432. _formatContents: function PopupElement_formatContents(contents) {
  4433. var p = document.createElement('p');
  4434. var lines = contents.split(/(?:\r\n?|\n)/);
  4435. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4436. var line = lines[i];
  4437. p.appendChild(document.createTextNode(line));
  4438. if (i < (ii - 1)) {
  4439. p.appendChild(document.createElement('br'));
  4440. }
  4441. }
  4442. return p;
  4443. },
  4444. /**
  4445. * Toggle the visibility of the popup.
  4446. *
  4447. * @private
  4448. * @memberof PopupElement
  4449. */
  4450. _toggle: function PopupElement_toggle() {
  4451. if (this.pinned) {
  4452. this._hide(true);
  4453. } else {
  4454. this._show(true);
  4455. }
  4456. },
  4457. /**
  4458. * Show the popup.
  4459. *
  4460. * @private
  4461. * @param {boolean} pin
  4462. * @memberof PopupElement
  4463. */
  4464. _show: function PopupElement_show(pin) {
  4465. if (pin) {
  4466. this.pinned = true;
  4467. }
  4468. if (this.hideElement.hasAttribute('hidden')) {
  4469. this.hideElement.removeAttribute('hidden');
  4470. this.container.style.zIndex += 1;
  4471. }
  4472. },
  4473. /**
  4474. * Hide the popup.
  4475. *
  4476. * @private
  4477. * @param {boolean} unpin
  4478. * @memberof PopupElement
  4479. */
  4480. _hide: function PopupElement_hide(unpin) {
  4481. if (unpin) {
  4482. this.pinned = false;
  4483. }
  4484. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4485. this.hideElement.setAttribute('hidden', true);
  4486. this.container.style.zIndex -= 1;
  4487. }
  4488. }
  4489. };
  4490. return PopupElement;
  4491. })();
  4492. /**
  4493. * @class
  4494. * @alias HighlightAnnotationElement
  4495. */
  4496. var HighlightAnnotationElement = (
  4497. function HighlightAnnotationElementClosure() {
  4498. function HighlightAnnotationElement(parameters) {
  4499. var isRenderable = !!(parameters.data.hasPopup ||
  4500. parameters.data.title || parameters.data.contents);
  4501. AnnotationElement.call(this, parameters, isRenderable);
  4502. }
  4503. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4504. /**
  4505. * Render the highlight annotation's HTML element in the empty container.
  4506. *
  4507. * @public
  4508. * @memberof HighlightAnnotationElement
  4509. * @returns {HTMLSectionElement}
  4510. */
  4511. render: function HighlightAnnotationElement_render() {
  4512. this.container.className = 'highlightAnnotation';
  4513. if (!this.data.hasPopup) {
  4514. this._createPopup(this.container, null, this.data);
  4515. }
  4516. return this.container;
  4517. }
  4518. });
  4519. return HighlightAnnotationElement;
  4520. })();
  4521. /**
  4522. * @class
  4523. * @alias UnderlineAnnotationElement
  4524. */
  4525. var UnderlineAnnotationElement = (
  4526. function UnderlineAnnotationElementClosure() {
  4527. function UnderlineAnnotationElement(parameters) {
  4528. var isRenderable = !!(parameters.data.hasPopup ||
  4529. parameters.data.title || parameters.data.contents);
  4530. AnnotationElement.call(this, parameters, isRenderable);
  4531. }
  4532. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4533. /**
  4534. * Render the underline annotation's HTML element in the empty container.
  4535. *
  4536. * @public
  4537. * @memberof UnderlineAnnotationElement
  4538. * @returns {HTMLSectionElement}
  4539. */
  4540. render: function UnderlineAnnotationElement_render() {
  4541. this.container.className = 'underlineAnnotation';
  4542. if (!this.data.hasPopup) {
  4543. this._createPopup(this.container, null, this.data);
  4544. }
  4545. return this.container;
  4546. }
  4547. });
  4548. return UnderlineAnnotationElement;
  4549. })();
  4550. /**
  4551. * @class
  4552. * @alias SquigglyAnnotationElement
  4553. */
  4554. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  4555. function SquigglyAnnotationElement(parameters) {
  4556. var isRenderable = !!(parameters.data.hasPopup ||
  4557. parameters.data.title || parameters.data.contents);
  4558. AnnotationElement.call(this, parameters, isRenderable);
  4559. }
  4560. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4561. /**
  4562. * Render the squiggly annotation's HTML element in the empty container.
  4563. *
  4564. * @public
  4565. * @memberof SquigglyAnnotationElement
  4566. * @returns {HTMLSectionElement}
  4567. */
  4568. render: function SquigglyAnnotationElement_render() {
  4569. this.container.className = 'squigglyAnnotation';
  4570. if (!this.data.hasPopup) {
  4571. this._createPopup(this.container, null, this.data);
  4572. }
  4573. return this.container;
  4574. }
  4575. });
  4576. return SquigglyAnnotationElement;
  4577. })();
  4578. /**
  4579. * @class
  4580. * @alias StrikeOutAnnotationElement
  4581. */
  4582. var StrikeOutAnnotationElement = (
  4583. function StrikeOutAnnotationElementClosure() {
  4584. function StrikeOutAnnotationElement(parameters) {
  4585. var isRenderable = !!(parameters.data.hasPopup ||
  4586. parameters.data.title || parameters.data.contents);
  4587. AnnotationElement.call(this, parameters, isRenderable);
  4588. }
  4589. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4590. /**
  4591. * Render the strikeout annotation's HTML element in the empty container.
  4592. *
  4593. * @public
  4594. * @memberof StrikeOutAnnotationElement
  4595. * @returns {HTMLSectionElement}
  4596. */
  4597. render: function StrikeOutAnnotationElement_render() {
  4598. this.container.className = 'strikeoutAnnotation';
  4599. if (!this.data.hasPopup) {
  4600. this._createPopup(this.container, null, this.data);
  4601. }
  4602. return this.container;
  4603. }
  4604. });
  4605. return StrikeOutAnnotationElement;
  4606. })();
  4607. /**
  4608. * @class
  4609. * @alias FileAttachmentAnnotationElement
  4610. */
  4611. var FileAttachmentAnnotationElement = (
  4612. function FileAttachmentAnnotationElementClosure() {
  4613. function FileAttachmentAnnotationElement(parameters) {
  4614. AnnotationElement.call(this, parameters, true);
  4615. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4616. this.content = parameters.data.file.content;
  4617. }
  4618. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4619. /**
  4620. * Render the file attachment annotation's HTML element in the empty
  4621. * container.
  4622. *
  4623. * @public
  4624. * @memberof FileAttachmentAnnotationElement
  4625. * @returns {HTMLSectionElement}
  4626. */
  4627. render: function FileAttachmentAnnotationElement_render() {
  4628. this.container.className = 'fileAttachmentAnnotation';
  4629. var trigger = document.createElement('div');
  4630. trigger.style.height = this.container.style.height;
  4631. trigger.style.width = this.container.style.width;
  4632. trigger.addEventListener('dblclick', this._download.bind(this));
  4633. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4634. this._createPopup(this.container, trigger, this.data);
  4635. }
  4636. this.container.appendChild(trigger);
  4637. return this.container;
  4638. },
  4639. /**
  4640. * Download the file attachment associated with this annotation.
  4641. *
  4642. * @private
  4643. * @memberof FileAttachmentAnnotationElement
  4644. */
  4645. _download: function FileAttachmentAnnotationElement_download() {
  4646. if (!this.downloadManager) {
  4647. warn('Download cannot be started due to unavailable download manager');
  4648. return;
  4649. }
  4650. this.downloadManager.downloadData(this.content, this.filename, '');
  4651. }
  4652. });
  4653. return FileAttachmentAnnotationElement;
  4654. })();
  4655. /**
  4656. * @typedef {Object} AnnotationLayerParameters
  4657. * @property {PageViewport} viewport
  4658. * @property {HTMLDivElement} div
  4659. * @property {Array} annotations
  4660. * @property {PDFPage} page
  4661. * @property {IPDFLinkService} linkService
  4662. * @property {string} imageResourcesPath
  4663. * @property {boolean} renderInteractiveForms
  4664. */
  4665. /**
  4666. * @class
  4667. * @alias AnnotationLayer
  4668. */
  4669. var AnnotationLayer = (function AnnotationLayerClosure() {
  4670. return {
  4671. /**
  4672. * Render a new annotation layer with all annotation elements.
  4673. *
  4674. * @public
  4675. * @param {AnnotationLayerParameters} parameters
  4676. * @memberof AnnotationLayer
  4677. */
  4678. render: function AnnotationLayer_render(parameters) {
  4679. var annotationElementFactory = new AnnotationElementFactory();
  4680. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4681. var data = parameters.annotations[i];
  4682. if (!data) {
  4683. continue;
  4684. }
  4685. var properties = {
  4686. data: data,
  4687. layer: parameters.div,
  4688. page: parameters.page,
  4689. viewport: parameters.viewport,
  4690. linkService: parameters.linkService,
  4691. downloadManager: parameters.downloadManager,
  4692. imageResourcesPath: parameters.imageResourcesPath ||
  4693. getDefaultSetting('imageResourcesPath'),
  4694. renderInteractiveForms: parameters.renderInteractiveForms || false,
  4695. };
  4696. var element = annotationElementFactory.create(properties);
  4697. if (element.isRenderable) {
  4698. parameters.div.appendChild(element.render());
  4699. }
  4700. }
  4701. },
  4702. /**
  4703. * Update the annotation elements on existing annotation layer.
  4704. *
  4705. * @public
  4706. * @param {AnnotationLayerParameters} parameters
  4707. * @memberof AnnotationLayer
  4708. */
  4709. update: function AnnotationLayer_update(parameters) {
  4710. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4711. var data = parameters.annotations[i];
  4712. var element = parameters.div.querySelector(
  4713. '[data-annotation-id="' + data.id + '"]');
  4714. if (element) {
  4715. CustomStyle.setProp('transform', element,
  4716. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4717. }
  4718. }
  4719. parameters.div.removeAttribute('hidden');
  4720. }
  4721. };
  4722. })();
  4723. exports.AnnotationLayer = AnnotationLayer;
  4724. }));
  4725. (function (root, factory) {
  4726. {
  4727. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4728. root.pdfjsDisplayDOMUtils);
  4729. }
  4730. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4731. var Util = sharedUtil.Util;
  4732. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4733. var CustomStyle = displayDOMUtils.CustomStyle;
  4734. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4735. /**
  4736. * Text layer render parameters.
  4737. *
  4738. * @typedef {Object} TextLayerRenderParameters
  4739. * @property {TextContent} textContent - Text content to render (the object is
  4740. * returned by the page's getTextContent() method).
  4741. * @property {HTMLElement} container - HTML element that will contain text runs.
  4742. * @property {PageViewport} viewport - The target viewport to properly
  4743. * layout the text runs.
  4744. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4745. * the text items of the textContent input. This is output and shall be
  4746. * initially be set to empty array.
  4747. * @property {number} timeout - (optional) Delay in milliseconds before
  4748. * rendering of the text runs occurs.
  4749. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4750. * text selection enhancement.
  4751. */
  4752. var renderTextLayer = (function renderTextLayerClosure() {
  4753. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4754. var NonWhitespaceRegexp = /\S/;
  4755. function isAllWhitespace(str) {
  4756. return !NonWhitespaceRegexp.test(str);
  4757. }
  4758. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  4759. // creating many intermediate strings when building their 'style' properties.
  4760. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0,
  4761. 'px; font-family: ', '', ';'];
  4762. function appendText(task, geom, styles) {
  4763. // Initialize all used properties to keep the caches monomorphic.
  4764. var textDiv = document.createElement('div');
  4765. var textDivProperties = {
  4766. style: null,
  4767. angle: 0,
  4768. canvasWidth: 0,
  4769. isWhitespace: false,
  4770. originalTransform: null,
  4771. paddingBottom: 0,
  4772. paddingLeft: 0,
  4773. paddingRight: 0,
  4774. paddingTop: 0,
  4775. scale: 1,
  4776. };
  4777. task._textDivs.push(textDiv);
  4778. if (isAllWhitespace(geom.str)) {
  4779. textDivProperties.isWhitespace = true;
  4780. task._textDivProperties.set(textDiv, textDivProperties);
  4781. return;
  4782. }
  4783. var tx = Util.transform(task._viewport.transform, geom.transform);
  4784. var angle = Math.atan2(tx[1], tx[0]);
  4785. var style = styles[geom.fontName];
  4786. if (style.vertical) {
  4787. angle += Math.PI / 2;
  4788. }
  4789. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4790. var fontAscent = fontHeight;
  4791. if (style.ascent) {
  4792. fontAscent = style.ascent * fontAscent;
  4793. } else if (style.descent) {
  4794. fontAscent = (1 + style.descent) * fontAscent;
  4795. }
  4796. var left;
  4797. var top;
  4798. if (angle === 0) {
  4799. left = tx[4];
  4800. top = tx[5] - fontAscent;
  4801. } else {
  4802. left = tx[4] + (fontAscent * Math.sin(angle));
  4803. top = tx[5] - (fontAscent * Math.cos(angle));
  4804. }
  4805. styleBuf[1] = left;
  4806. styleBuf[3] = top;
  4807. styleBuf[5] = fontHeight;
  4808. styleBuf[7] = style.fontFamily;
  4809. textDivProperties.style = styleBuf.join('');
  4810. textDiv.setAttribute('style', textDivProperties.style);
  4811. textDiv.textContent = geom.str;
  4812. // |fontName| is only used by the Font Inspector. This test will succeed
  4813. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4814. // not worth the effort to do a more accurate test. We only use `dataset`
  4815. // here to make the font name available for the debugger.
  4816. if (getDefaultSetting('pdfBug')) {
  4817. textDiv.dataset.fontName = geom.fontName;
  4818. }
  4819. if (angle !== 0) {
  4820. textDivProperties.angle = angle * (180 / Math.PI);
  4821. }
  4822. // We don't bother scaling single-char text divs, because it has very
  4823. // little effect on text highlighting. This makes scrolling on docs with
  4824. // lots of such divs a lot faster.
  4825. if (geom.str.length > 1) {
  4826. if (style.vertical) {
  4827. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4828. } else {
  4829. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4830. }
  4831. }
  4832. task._textDivProperties.set(textDiv, textDivProperties);
  4833. if (task._enhanceTextSelection) {
  4834. var angleCos = 1, angleSin = 0;
  4835. if (angle !== 0) {
  4836. angleCos = Math.cos(angle);
  4837. angleSin = Math.sin(angle);
  4838. }
  4839. var divWidth = (style.vertical ? geom.height : geom.width) *
  4840. task._viewport.scale;
  4841. var divHeight = fontHeight;
  4842. var m, b;
  4843. if (angle !== 0) {
  4844. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  4845. b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  4846. } else {
  4847. b = [left, top, left + divWidth, top + divHeight];
  4848. }
  4849. task._bounds.push({
  4850. left: b[0],
  4851. top: b[1],
  4852. right: b[2],
  4853. bottom: b[3],
  4854. div: textDiv,
  4855. size: [divWidth, divHeight],
  4856. m: m
  4857. });
  4858. }
  4859. }
  4860. function render(task) {
  4861. if (task._canceled) {
  4862. return;
  4863. }
  4864. var textLayerFrag = task._container;
  4865. var textDivs = task._textDivs;
  4866. var capability = task._capability;
  4867. var textDivsLength = textDivs.length;
  4868. // No point in rendering many divs as it would make the browser
  4869. // unusable even after the divs are rendered.
  4870. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4871. task._renderingDone = true;
  4872. capability.resolve();
  4873. return;
  4874. }
  4875. var canvas = document.createElement('canvas');
  4876. canvas.mozOpaque = true;
  4877. var ctx = canvas.getContext('2d', {alpha: false});
  4878. var lastFontSize;
  4879. var lastFontFamily;
  4880. for (var i = 0; i < textDivsLength; i++) {
  4881. var textDiv = textDivs[i];
  4882. var textDivProperties = task._textDivProperties.get(textDiv);
  4883. if (textDivProperties.isWhitespace) {
  4884. continue;
  4885. }
  4886. var fontSize = textDiv.style.fontSize;
  4887. var fontFamily = textDiv.style.fontFamily;
  4888. // Only build font string and set to context if different from last.
  4889. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4890. ctx.font = fontSize + ' ' + fontFamily;
  4891. lastFontSize = fontSize;
  4892. lastFontFamily = fontFamily;
  4893. }
  4894. var width = ctx.measureText(textDiv.textContent).width;
  4895. textLayerFrag.appendChild(textDiv);
  4896. var transform = '';
  4897. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4898. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4899. transform = 'scaleX(' + textDivProperties.scale + ')';
  4900. }
  4901. if (textDivProperties.angle !== 0) {
  4902. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4903. }
  4904. if (transform !== '') {
  4905. textDivProperties.originalTransform = transform;
  4906. CustomStyle.setProp('transform', textDiv, transform);
  4907. }
  4908. task._textDivProperties.set(textDiv, textDivProperties);
  4909. }
  4910. task._renderingDone = true;
  4911. capability.resolve();
  4912. }
  4913. function expand(task) {
  4914. var bounds = task._bounds;
  4915. var viewport = task._viewport;
  4916. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4917. for (var i = 0; i < expanded.length; i++) {
  4918. var div = bounds[i].div;
  4919. var divProperties = task._textDivProperties.get(div);
  4920. if (divProperties.angle === 0) {
  4921. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4922. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4923. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4924. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4925. task._textDivProperties.set(div, divProperties);
  4926. continue;
  4927. }
  4928. // Box is rotated -- trying to find padding so rotated div will not
  4929. // exceed its expanded bounds.
  4930. var e = expanded[i], b = bounds[i];
  4931. var m = b.m, c = m[0], s = m[1];
  4932. // Finding intersections with expanded box.
  4933. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  4934. var ts = new Float64Array(64);
  4935. points.forEach(function (p, i) {
  4936. var t = Util.applyTransform(p, m);
  4937. ts[i + 0] = c && (e.left - t[0]) / c;
  4938. ts[i + 4] = s && (e.top - t[1]) / s;
  4939. ts[i + 8] = c && (e.right - t[0]) / c;
  4940. ts[i + 12] = s && (e.bottom - t[1]) / s;
  4941. ts[i + 16] = s && (e.left - t[0]) / -s;
  4942. ts[i + 20] = c && (e.top - t[1]) / c;
  4943. ts[i + 24] = s && (e.right - t[0]) / -s;
  4944. ts[i + 28] = c && (e.bottom - t[1]) / c;
  4945. ts[i + 32] = c && (e.left - t[0]) / -c;
  4946. ts[i + 36] = s && (e.top - t[1]) / -s;
  4947. ts[i + 40] = c && (e.right - t[0]) / -c;
  4948. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  4949. ts[i + 48] = s && (e.left - t[0]) / s;
  4950. ts[i + 52] = c && (e.top - t[1]) / -c;
  4951. ts[i + 56] = s && (e.right - t[0]) / s;
  4952. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  4953. });
  4954. var findPositiveMin = function (ts, offset, count) {
  4955. var result = 0;
  4956. for (var i = 0; i < count; i++) {
  4957. var t = ts[offset++];
  4958. if (t > 0) {
  4959. result = result ? Math.min(t, result) : t;
  4960. }
  4961. }
  4962. return result;
  4963. };
  4964. // Not based on math, but to simplify calculations, using cos and sin
  4965. // absolute values to not exceed the box (it can but insignificantly).
  4966. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  4967. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  4968. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  4969. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  4970. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  4971. task._textDivProperties.set(div, divProperties);
  4972. }
  4973. }
  4974. function expandBounds(width, height, boxes) {
  4975. var bounds = boxes.map(function (box, i) {
  4976. return {
  4977. x1: box.left,
  4978. y1: box.top,
  4979. x2: box.right,
  4980. y2: box.bottom,
  4981. index: i,
  4982. x1New: undefined,
  4983. x2New: undefined
  4984. };
  4985. });
  4986. expandBoundsLTR(width, bounds);
  4987. var expanded = new Array(boxes.length);
  4988. bounds.forEach(function (b) {
  4989. var i = b.index;
  4990. expanded[i] = {
  4991. left: b.x1New,
  4992. top: 0,
  4993. right: b.x2New,
  4994. bottom: 0
  4995. };
  4996. });
  4997. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  4998. // array and objects.
  4999. boxes.map(function (box, i) {
  5000. var e = expanded[i], b = bounds[i];
  5001. b.x1 = box.top;
  5002. b.y1 = width - e.right;
  5003. b.x2 = box.bottom;
  5004. b.y2 = width - e.left;
  5005. b.index = i;
  5006. b.x1New = undefined;
  5007. b.x2New = undefined;
  5008. });
  5009. expandBoundsLTR(height, bounds);
  5010. bounds.forEach(function (b) {
  5011. var i = b.index;
  5012. expanded[i].top = b.x1New;
  5013. expanded[i].bottom = b.x2New;
  5014. });
  5015. return expanded;
  5016. }
  5017. function expandBoundsLTR(width, bounds) {
  5018. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5019. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; });
  5020. // First we see on the horizon is a fake boundary.
  5021. var fakeBoundary = {
  5022. x1: -Infinity,
  5023. y1: -Infinity,
  5024. x2: 0,
  5025. y2: Infinity,
  5026. index: -1,
  5027. x1New: 0,
  5028. x2New: 0
  5029. };
  5030. var horizon = [{
  5031. start: -Infinity,
  5032. end: Infinity,
  5033. boundary: fakeBoundary
  5034. }];
  5035. bounds.forEach(function (boundary) {
  5036. // Searching for the affected part of horizon.
  5037. // TODO red-black tree or simple binary search
  5038. var i = 0;
  5039. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5040. i++;
  5041. }
  5042. var j = horizon.length - 1;
  5043. while(j >= 0 && horizon[j].start >= boundary.y2) {
  5044. j--;
  5045. }
  5046. var horizonPart, affectedBoundary;
  5047. var q, k, maxXNew = -Infinity;
  5048. for (q = i; q <= j; q++) {
  5049. horizonPart = horizon[q];
  5050. affectedBoundary = horizonPart.boundary;
  5051. var xNew;
  5052. if (affectedBoundary.x2 > boundary.x1) {
  5053. // In the middle of the previous element, new x shall be at the
  5054. // boundary start. Extending if further if the affected bondary
  5055. // placed on top of the current one.
  5056. xNew = affectedBoundary.index > boundary.index ?
  5057. affectedBoundary.x1New : boundary.x1;
  5058. } else if (affectedBoundary.x2New === undefined) {
  5059. // We have some space in between, new x in middle will be a fair
  5060. // choice.
  5061. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5062. } else {
  5063. // Affected boundary has x2new set, using it as new x.
  5064. xNew = affectedBoundary.x2New;
  5065. }
  5066. if (xNew > maxXNew) {
  5067. maxXNew = xNew;
  5068. }
  5069. }
  5070. // Set new x1 for current boundary.
  5071. boundary.x1New = maxXNew;
  5072. // Adjusts new x2 for the affected boundaries.
  5073. for (q = i; q <= j; q++) {
  5074. horizonPart = horizon[q];
  5075. affectedBoundary = horizonPart.boundary;
  5076. if (affectedBoundary.x2New === undefined) {
  5077. // Was not set yet, choosing new x if possible.
  5078. if (affectedBoundary.x2 > boundary.x1) {
  5079. // Current and affected boundaries intersect. If affected boundary
  5080. // is placed on top of the current, shrinking the affected.
  5081. if (affectedBoundary.index > boundary.index) {
  5082. affectedBoundary.x2New = affectedBoundary.x2;
  5083. }
  5084. } else {
  5085. affectedBoundary.x2New = maxXNew;
  5086. }
  5087. } else if (affectedBoundary.x2New > maxXNew) {
  5088. // Affected boundary is touching new x, pushing it back.
  5089. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5090. }
  5091. }
  5092. // Fixing the horizon.
  5093. var changedHorizon = [], lastBoundary = null;
  5094. for (q = i; q <= j; q++) {
  5095. horizonPart = horizon[q];
  5096. affectedBoundary = horizonPart.boundary;
  5097. // Checking which boundary will be visible.
  5098. var useBoundary = affectedBoundary.x2 > boundary.x2 ?
  5099. affectedBoundary : boundary;
  5100. if (lastBoundary === useBoundary) {
  5101. // Merging with previous.
  5102. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5103. } else {
  5104. changedHorizon.push({
  5105. start: horizonPart.start,
  5106. end: horizonPart.end,
  5107. boundary: useBoundary
  5108. });
  5109. lastBoundary = useBoundary;
  5110. }
  5111. }
  5112. if (horizon[i].start < boundary.y1) {
  5113. changedHorizon[0].start = boundary.y1;
  5114. changedHorizon.unshift({
  5115. start: horizon[i].start,
  5116. end: boundary.y1,
  5117. boundary: horizon[i].boundary
  5118. });
  5119. }
  5120. if (boundary.y2 < horizon[j].end) {
  5121. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5122. changedHorizon.push({
  5123. start: boundary.y2,
  5124. end: horizon[j].end,
  5125. boundary: horizon[j].boundary
  5126. });
  5127. }
  5128. // Set x2 new of boundary that is no longer visible (see overlapping case
  5129. // above).
  5130. // TODO more efficient, e.g. via reference counting.
  5131. for (q = i; q <= j; q++) {
  5132. horizonPart = horizon[q];
  5133. affectedBoundary = horizonPart.boundary;
  5134. if (affectedBoundary.x2New !== undefined) {
  5135. continue;
  5136. }
  5137. var used = false;
  5138. for (k = i - 1; !used && k >= 0 &&
  5139. horizon[k].start >= affectedBoundary.y1; k--) {
  5140. used = horizon[k].boundary === affectedBoundary;
  5141. }
  5142. for (k = j + 1; !used && k < horizon.length &&
  5143. horizon[k].end <= affectedBoundary.y2; k++) {
  5144. used = horizon[k].boundary === affectedBoundary;
  5145. }
  5146. for (k = 0; !used && k < changedHorizon.length; k++) {
  5147. used = changedHorizon[k].boundary === affectedBoundary;
  5148. }
  5149. if (!used) {
  5150. affectedBoundary.x2New = maxXNew;
  5151. }
  5152. }
  5153. Array.prototype.splice.apply(horizon,
  5154. [i, j - i + 1].concat(changedHorizon));
  5155. });
  5156. // Set new x2 for all unset boundaries.
  5157. horizon.forEach(function (horizonPart) {
  5158. var affectedBoundary = horizonPart.boundary;
  5159. if (affectedBoundary.x2New === undefined) {
  5160. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5161. }
  5162. });
  5163. }
  5164. /**
  5165. * Text layer rendering task.
  5166. *
  5167. * @param {TextContent} textContent
  5168. * @param {HTMLElement} container
  5169. * @param {PageViewport} viewport
  5170. * @param {Array} textDivs
  5171. * @param {boolean} enhanceTextSelection
  5172. * @private
  5173. */
  5174. function TextLayerRenderTask(textContent, container, viewport, textDivs,
  5175. enhanceTextSelection) {
  5176. this._textContent = textContent;
  5177. this._container = container;
  5178. this._viewport = viewport;
  5179. this._textDivs = textDivs || [];
  5180. this._textDivProperties = new WeakMap();
  5181. this._renderingDone = false;
  5182. this._canceled = false;
  5183. this._capability = createPromiseCapability();
  5184. this._renderTimer = null;
  5185. this._bounds = [];
  5186. this._enhanceTextSelection = !!enhanceTextSelection;
  5187. }
  5188. TextLayerRenderTask.prototype = {
  5189. get promise() {
  5190. return this._capability.promise;
  5191. },
  5192. cancel: function TextLayer_cancel() {
  5193. this._canceled = true;
  5194. if (this._renderTimer !== null) {
  5195. clearTimeout(this._renderTimer);
  5196. this._renderTimer = null;
  5197. }
  5198. this._capability.reject('canceled');
  5199. },
  5200. _render: function TextLayer_render(timeout) {
  5201. var textItems = this._textContent.items;
  5202. var textStyles = this._textContent.styles;
  5203. for (var i = 0, len = textItems.length; i < len; i++) {
  5204. appendText(this, textItems[i], textStyles);
  5205. }
  5206. if (!timeout) { // Render right away
  5207. render(this);
  5208. } else { // Schedule
  5209. var self = this;
  5210. this._renderTimer = setTimeout(function() {
  5211. render(self);
  5212. self._renderTimer = null;
  5213. }, timeout);
  5214. }
  5215. },
  5216. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5217. if (!this._enhanceTextSelection || !this._renderingDone) {
  5218. return;
  5219. }
  5220. if (this._bounds !== null) {
  5221. expand(this);
  5222. this._bounds = null;
  5223. }
  5224. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5225. var div = this._textDivs[i];
  5226. var divProperties = this._textDivProperties.get(div);
  5227. if (divProperties.isWhitespace) {
  5228. continue;
  5229. }
  5230. if (expandDivs) {
  5231. var transform = '', padding = '';
  5232. if (divProperties.scale !== 1) {
  5233. transform = 'scaleX(' + divProperties.scale + ')';
  5234. }
  5235. if (divProperties.angle !== 0) {
  5236. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5237. }
  5238. if (divProperties.paddingLeft !== 0) {
  5239. padding += ' padding-left: ' +
  5240. (divProperties.paddingLeft / divProperties.scale) + 'px;';
  5241. transform += ' translateX(' +
  5242. (-divProperties.paddingLeft / divProperties.scale) + 'px)';
  5243. }
  5244. if (divProperties.paddingTop !== 0) {
  5245. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5246. transform += ' translateY(' + (-divProperties.paddingTop) + 'px)';
  5247. }
  5248. if (divProperties.paddingRight !== 0) {
  5249. padding += ' padding-right: ' +
  5250. (divProperties.paddingRight / divProperties.scale) + 'px;';
  5251. }
  5252. if (divProperties.paddingBottom !== 0) {
  5253. padding += ' padding-bottom: ' +
  5254. divProperties.paddingBottom + 'px;';
  5255. }
  5256. if (padding !== '') {
  5257. div.setAttribute('style', divProperties.style + padding);
  5258. }
  5259. if (transform !== '') {
  5260. CustomStyle.setProp('transform', div, transform);
  5261. }
  5262. } else {
  5263. div.style.padding = 0;
  5264. CustomStyle.setProp('transform', div,
  5265. divProperties.originalTransform || '');
  5266. }
  5267. }
  5268. },
  5269. };
  5270. /**
  5271. * Starts rendering of the text layer.
  5272. *
  5273. * @param {TextLayerRenderParameters} renderParameters
  5274. * @returns {TextLayerRenderTask}
  5275. */
  5276. function renderTextLayer(renderParameters) {
  5277. var task = new TextLayerRenderTask(renderParameters.textContent,
  5278. renderParameters.container,
  5279. renderParameters.viewport,
  5280. renderParameters.textDivs,
  5281. renderParameters.enhanceTextSelection);
  5282. task._render(renderParameters.timeout);
  5283. return task;
  5284. }
  5285. return renderTextLayer;
  5286. })();
  5287. exports.renderTextLayer = renderTextLayer;
  5288. }));
  5289. (function (root, factory) {
  5290. {
  5291. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil,
  5292. root.pdfjsDisplayDOMUtils);
  5293. }
  5294. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5295. var shadow = sharedUtil.shadow;
  5296. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5297. var WebGLUtils = (function WebGLUtilsClosure() {
  5298. function loadShader(gl, code, shaderType) {
  5299. var shader = gl.createShader(shaderType);
  5300. gl.shaderSource(shader, code);
  5301. gl.compileShader(shader);
  5302. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5303. if (!compiled) {
  5304. var errorMsg = gl.getShaderInfoLog(shader);
  5305. throw new Error('Error during shader compilation: ' + errorMsg);
  5306. }
  5307. return shader;
  5308. }
  5309. function createVertexShader(gl, code) {
  5310. return loadShader(gl, code, gl.VERTEX_SHADER);
  5311. }
  5312. function createFragmentShader(gl, code) {
  5313. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5314. }
  5315. function createProgram(gl, shaders) {
  5316. var program = gl.createProgram();
  5317. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5318. gl.attachShader(program, shaders[i]);
  5319. }
  5320. gl.linkProgram(program);
  5321. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5322. if (!linked) {
  5323. var errorMsg = gl.getProgramInfoLog(program);
  5324. throw new Error('Error during program linking: ' + errorMsg);
  5325. }
  5326. return program;
  5327. }
  5328. function createTexture(gl, image, textureId) {
  5329. gl.activeTexture(textureId);
  5330. var texture = gl.createTexture();
  5331. gl.bindTexture(gl.TEXTURE_2D, texture);
  5332. // Set the parameters so we can render any size image.
  5333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5337. // Upload the image into the texture.
  5338. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5339. return texture;
  5340. }
  5341. var currentGL, currentCanvas;
  5342. function generateGL() {
  5343. if (currentGL) {
  5344. return;
  5345. }
  5346. currentCanvas = document.createElement('canvas');
  5347. currentGL = currentCanvas.getContext('webgl',
  5348. { premultipliedalpha: false });
  5349. }
  5350. var smaskVertexShaderCode = '\
  5351. attribute vec2 a_position; \
  5352. attribute vec2 a_texCoord; \
  5353. \
  5354. uniform vec2 u_resolution; \
  5355. \
  5356. varying vec2 v_texCoord; \
  5357. \
  5358. void main() { \
  5359. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5360. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5361. \
  5362. v_texCoord = a_texCoord; \
  5363. } ';
  5364. var smaskFragmentShaderCode = '\
  5365. precision mediump float; \
  5366. \
  5367. uniform vec4 u_backdrop; \
  5368. uniform int u_subtype; \
  5369. uniform sampler2D u_image; \
  5370. uniform sampler2D u_mask; \
  5371. \
  5372. varying vec2 v_texCoord; \
  5373. \
  5374. void main() { \
  5375. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5376. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5377. if (u_backdrop.a > 0.0) { \
  5378. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5379. u_backdrop.rgb * (1.0 - maskColor.a); \
  5380. } \
  5381. float lum; \
  5382. if (u_subtype == 0) { \
  5383. lum = maskColor.a; \
  5384. } else { \
  5385. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5386. maskColor.b * 0.11; \
  5387. } \
  5388. imageColor.a *= lum; \
  5389. imageColor.rgb *= imageColor.a; \
  5390. gl_FragColor = imageColor; \
  5391. } ';
  5392. var smaskCache = null;
  5393. function initSmaskGL() {
  5394. var canvas, gl;
  5395. generateGL();
  5396. canvas = currentCanvas;
  5397. currentCanvas = null;
  5398. gl = currentGL;
  5399. currentGL = null;
  5400. // setup a GLSL program
  5401. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5402. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5403. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5404. gl.useProgram(program);
  5405. var cache = {};
  5406. cache.gl = gl;
  5407. cache.canvas = canvas;
  5408. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5409. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5410. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5411. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5412. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5413. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5414. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5415. // provide texture coordinates for the rectangle.
  5416. var texCoordBuffer = gl.createBuffer();
  5417. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5418. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5419. 0.0, 0.0,
  5420. 1.0, 0.0,
  5421. 0.0, 1.0,
  5422. 0.0, 1.0,
  5423. 1.0, 0.0,
  5424. 1.0, 1.0]), gl.STATIC_DRAW);
  5425. gl.enableVertexAttribArray(texCoordLocation);
  5426. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5427. gl.uniform1i(texLayerLocation, 0);
  5428. gl.uniform1i(texMaskLocation, 1);
  5429. smaskCache = cache;
  5430. }
  5431. function composeSMask(layer, mask, properties) {
  5432. var width = layer.width, height = layer.height;
  5433. if (!smaskCache) {
  5434. initSmaskGL();
  5435. }
  5436. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5437. canvas.width = width;
  5438. canvas.height = height;
  5439. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5440. gl.uniform2f(cache.resolutionLocation, width, height);
  5441. if (properties.backdrop) {
  5442. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5443. properties.backdrop[1], properties.backdrop[2], 1);
  5444. } else {
  5445. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5446. }
  5447. gl.uniform1i(cache.subtypeLocation,
  5448. properties.subtype === 'Luminosity' ? 1 : 0);
  5449. // Create a textures
  5450. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5451. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5452. // Create a buffer and put a single clipspace rectangle in
  5453. // it (2 triangles)
  5454. var buffer = gl.createBuffer();
  5455. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5456. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5457. 0, 0,
  5458. width, 0,
  5459. 0, height,
  5460. 0, height,
  5461. width, 0,
  5462. width, height]), gl.STATIC_DRAW);
  5463. gl.enableVertexAttribArray(cache.positionLocation);
  5464. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5465. // draw
  5466. gl.clearColor(0, 0, 0, 0);
  5467. gl.enable(gl.BLEND);
  5468. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5469. gl.clear(gl.COLOR_BUFFER_BIT);
  5470. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5471. gl.flush();
  5472. gl.deleteTexture(texture);
  5473. gl.deleteTexture(maskTexture);
  5474. gl.deleteBuffer(buffer);
  5475. return canvas;
  5476. }
  5477. var figuresVertexShaderCode = '\
  5478. attribute vec2 a_position; \
  5479. attribute vec3 a_color; \
  5480. \
  5481. uniform vec2 u_resolution; \
  5482. uniform vec2 u_scale; \
  5483. uniform vec2 u_offset; \
  5484. \
  5485. varying vec4 v_color; \
  5486. \
  5487. void main() { \
  5488. vec2 position = (a_position + u_offset) * u_scale; \
  5489. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5490. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5491. \
  5492. v_color = vec4(a_color / 255.0, 1.0); \
  5493. } ';
  5494. var figuresFragmentShaderCode = '\
  5495. precision mediump float; \
  5496. \
  5497. varying vec4 v_color; \
  5498. \
  5499. void main() { \
  5500. gl_FragColor = v_color; \
  5501. } ';
  5502. var figuresCache = null;
  5503. function initFiguresGL() {
  5504. var canvas, gl;
  5505. generateGL();
  5506. canvas = currentCanvas;
  5507. currentCanvas = null;
  5508. gl = currentGL;
  5509. currentGL = null;
  5510. // setup a GLSL program
  5511. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5512. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5513. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5514. gl.useProgram(program);
  5515. var cache = {};
  5516. cache.gl = gl;
  5517. cache.canvas = canvas;
  5518. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5519. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5520. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5521. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5522. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5523. figuresCache = cache;
  5524. }
  5525. function drawFigures(width, height, backgroundColor, figures, context) {
  5526. if (!figuresCache) {
  5527. initFiguresGL();
  5528. }
  5529. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5530. canvas.width = width;
  5531. canvas.height = height;
  5532. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5533. gl.uniform2f(cache.resolutionLocation, width, height);
  5534. // count triangle points
  5535. var count = 0;
  5536. var i, ii, rows;
  5537. for (i = 0, ii = figures.length; i < ii; i++) {
  5538. switch (figures[i].type) {
  5539. case 'lattice':
  5540. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5541. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5542. break;
  5543. case 'triangles':
  5544. count += figures[i].coords.length;
  5545. break;
  5546. }
  5547. }
  5548. // transfer data
  5549. var coords = new Float32Array(count * 2);
  5550. var colors = new Uint8Array(count * 3);
  5551. var coordsMap = context.coords, colorsMap = context.colors;
  5552. var pIndex = 0, cIndex = 0;
  5553. for (i = 0, ii = figures.length; i < ii; i++) {
  5554. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5555. switch (figure.type) {
  5556. case 'lattice':
  5557. var cols = figure.verticesPerRow;
  5558. rows = (ps.length / cols) | 0;
  5559. for (var row = 1; row < rows; row++) {
  5560. var offset = row * cols + 1;
  5561. for (var col = 1; col < cols; col++, offset++) {
  5562. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5563. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5564. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5565. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5566. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5567. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5568. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5569. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5570. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5571. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5572. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5573. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5574. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5575. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5576. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5577. coords[pIndex + 6] = coords[pIndex + 2];
  5578. coords[pIndex + 7] = coords[pIndex + 3];
  5579. coords[pIndex + 8] = coords[pIndex + 4];
  5580. coords[pIndex + 9] = coords[pIndex + 5];
  5581. coords[pIndex + 10] = coordsMap[ps[offset]];
  5582. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5583. colors[cIndex + 9] = colors[cIndex + 3];
  5584. colors[cIndex + 10] = colors[cIndex + 4];
  5585. colors[cIndex + 11] = colors[cIndex + 5];
  5586. colors[cIndex + 12] = colors[cIndex + 6];
  5587. colors[cIndex + 13] = colors[cIndex + 7];
  5588. colors[cIndex + 14] = colors[cIndex + 8];
  5589. colors[cIndex + 15] = colorsMap[cs[offset]];
  5590. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5591. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5592. pIndex += 12;
  5593. cIndex += 18;
  5594. }
  5595. }
  5596. break;
  5597. case 'triangles':
  5598. for (var j = 0, jj = ps.length; j < jj; j++) {
  5599. coords[pIndex] = coordsMap[ps[j]];
  5600. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5601. colors[cIndex] = colorsMap[cs[j]];
  5602. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5603. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5604. pIndex += 2;
  5605. cIndex += 3;
  5606. }
  5607. break;
  5608. }
  5609. }
  5610. // draw
  5611. if (backgroundColor) {
  5612. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5613. backgroundColor[2] / 255, 1.0);
  5614. } else {
  5615. gl.clearColor(0, 0, 0, 0);
  5616. }
  5617. gl.clear(gl.COLOR_BUFFER_BIT);
  5618. var coordsBuffer = gl.createBuffer();
  5619. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5620. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5621. gl.enableVertexAttribArray(cache.positionLocation);
  5622. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5623. var colorsBuffer = gl.createBuffer();
  5624. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5625. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5626. gl.enableVertexAttribArray(cache.colorLocation);
  5627. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5628. 0, 0);
  5629. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5630. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5631. gl.drawArrays(gl.TRIANGLES, 0, count);
  5632. gl.flush();
  5633. gl.deleteBuffer(coordsBuffer);
  5634. gl.deleteBuffer(colorsBuffer);
  5635. return canvas;
  5636. }
  5637. function cleanup() {
  5638. if (smaskCache && smaskCache.canvas) {
  5639. smaskCache.canvas.width = 0;
  5640. smaskCache.canvas.height = 0;
  5641. }
  5642. if (figuresCache && figuresCache.canvas) {
  5643. figuresCache.canvas.width = 0;
  5644. figuresCache.canvas.height = 0;
  5645. }
  5646. smaskCache = null;
  5647. figuresCache = null;
  5648. }
  5649. return {
  5650. get isEnabled() {
  5651. if (getDefaultSetting('disableWebGL')) {
  5652. return false;
  5653. }
  5654. var enabled = false;
  5655. try {
  5656. generateGL();
  5657. enabled = !!currentGL;
  5658. } catch (e) { }
  5659. return shadow(this, 'isEnabled', enabled);
  5660. },
  5661. composeSMask: composeSMask,
  5662. drawFigures: drawFigures,
  5663. clear: cleanup
  5664. };
  5665. })();
  5666. exports.WebGLUtils = WebGLUtils;
  5667. }));
  5668. (function (root, factory) {
  5669. {
  5670. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  5671. root.pdfjsDisplayWebGL);
  5672. }
  5673. }(this, function (exports, sharedUtil, displayWebGL) {
  5674. var Util = sharedUtil.Util;
  5675. var info = sharedUtil.info;
  5676. var isArray = sharedUtil.isArray;
  5677. var error = sharedUtil.error;
  5678. var WebGLUtils = displayWebGL.WebGLUtils;
  5679. var ShadingIRs = {};
  5680. ShadingIRs.RadialAxial = {
  5681. fromIR: function RadialAxial_fromIR(raw) {
  5682. var type = raw[1];
  5683. var colorStops = raw[2];
  5684. var p0 = raw[3];
  5685. var p1 = raw[4];
  5686. var r0 = raw[5];
  5687. var r1 = raw[6];
  5688. return {
  5689. type: 'Pattern',
  5690. getPattern: function RadialAxial_getPattern(ctx) {
  5691. var grad;
  5692. if (type === 'axial') {
  5693. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5694. } else if (type === 'radial') {
  5695. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5696. }
  5697. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5698. var c = colorStops[i];
  5699. grad.addColorStop(c[0], c[1]);
  5700. }
  5701. return grad;
  5702. }
  5703. };
  5704. }
  5705. };
  5706. var createMeshCanvas = (function createMeshCanvasClosure() {
  5707. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5708. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5709. var coords = context.coords, colors = context.colors;
  5710. var bytes = data.data, rowSize = data.width * 4;
  5711. var tmp;
  5712. if (coords[p1 + 1] > coords[p2 + 1]) {
  5713. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5714. }
  5715. if (coords[p2 + 1] > coords[p3 + 1]) {
  5716. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5717. }
  5718. if (coords[p1 + 1] > coords[p2 + 1]) {
  5719. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5720. }
  5721. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5722. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5723. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5724. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5725. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5726. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5727. if (y1 >= y3) {
  5728. return;
  5729. }
  5730. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5731. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5732. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5733. var minY = Math.round(y1), maxY = Math.round(y3);
  5734. var xa, car, cag, cab;
  5735. var xb, cbr, cbg, cbb;
  5736. var k;
  5737. for (var y = minY; y <= maxY; y++) {
  5738. if (y < y2) {
  5739. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5740. xa = x1 - (x1 - x2) * k;
  5741. car = c1r - (c1r - c2r) * k;
  5742. cag = c1g - (c1g - c2g) * k;
  5743. cab = c1b - (c1b - c2b) * k;
  5744. } else {
  5745. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5746. xa = x2 - (x2 - x3) * k;
  5747. car = c2r - (c2r - c3r) * k;
  5748. cag = c2g - (c2g - c3g) * k;
  5749. cab = c2b - (c2b - c3b) * k;
  5750. }
  5751. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5752. xb = x1 - (x1 - x3) * k;
  5753. cbr = c1r - (c1r - c3r) * k;
  5754. cbg = c1g - (c1g - c3g) * k;
  5755. cbb = c1b - (c1b - c3b) * k;
  5756. var x1_ = Math.round(Math.min(xa, xb));
  5757. var x2_ = Math.round(Math.max(xa, xb));
  5758. var j = rowSize * y + x1_ * 4;
  5759. for (var x = x1_; x <= x2_; x++) {
  5760. k = (xa - x) / (xa - xb);
  5761. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5762. bytes[j++] = (car - (car - cbr) * k) | 0;
  5763. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5764. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5765. bytes[j++] = 255;
  5766. }
  5767. }
  5768. }
  5769. function drawFigure(data, figure, context) {
  5770. var ps = figure.coords;
  5771. var cs = figure.colors;
  5772. var i, ii;
  5773. switch (figure.type) {
  5774. case 'lattice':
  5775. var verticesPerRow = figure.verticesPerRow;
  5776. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5777. var cols = verticesPerRow - 1;
  5778. for (i = 0; i < rows; i++) {
  5779. var q = i * verticesPerRow;
  5780. for (var j = 0; j < cols; j++, q++) {
  5781. drawTriangle(data, context,
  5782. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5783. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5784. drawTriangle(data, context,
  5785. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5786. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5787. }
  5788. }
  5789. break;
  5790. case 'triangles':
  5791. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5792. drawTriangle(data, context,
  5793. ps[i], ps[i + 1], ps[i + 2],
  5794. cs[i], cs[i + 1], cs[i + 2]);
  5795. }
  5796. break;
  5797. default:
  5798. error('illigal figure');
  5799. break;
  5800. }
  5801. }
  5802. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5803. backgroundColor, cachedCanvases) {
  5804. // we will increase scale on some weird factor to let antialiasing take
  5805. // care of "rough" edges
  5806. var EXPECTED_SCALE = 1.1;
  5807. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5808. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5809. // We need to keep transparent border around our pattern for fill():
  5810. // createPattern with 'no-repeat' will bleed edges across entire area.
  5811. var BORDER_SIZE = 2;
  5812. var offsetX = Math.floor(bounds[0]);
  5813. var offsetY = Math.floor(bounds[1]);
  5814. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5815. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5816. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5817. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5818. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5819. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5820. var scaleX = boundsWidth / width;
  5821. var scaleY = boundsHeight / height;
  5822. var context = {
  5823. coords: coords,
  5824. colors: colors,
  5825. offsetX: -offsetX,
  5826. offsetY: -offsetY,
  5827. scaleX: 1 / scaleX,
  5828. scaleY: 1 / scaleY
  5829. };
  5830. var paddedWidth = width + BORDER_SIZE * 2;
  5831. var paddedHeight = height + BORDER_SIZE * 2;
  5832. var canvas, tmpCanvas, i, ii;
  5833. if (WebGLUtils.isEnabled) {
  5834. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5835. figures, context);
  5836. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5837. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5838. false);
  5839. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5840. canvas = tmpCanvas.canvas;
  5841. } else {
  5842. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight,
  5843. false);
  5844. var tmpCtx = tmpCanvas.context;
  5845. var data = tmpCtx.createImageData(width, height);
  5846. if (backgroundColor) {
  5847. var bytes = data.data;
  5848. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5849. bytes[i] = backgroundColor[0];
  5850. bytes[i + 1] = backgroundColor[1];
  5851. bytes[i + 2] = backgroundColor[2];
  5852. bytes[i + 3] = 255;
  5853. }
  5854. }
  5855. for (i = 0; i < figures.length; i++) {
  5856. drawFigure(data, figures[i], context);
  5857. }
  5858. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5859. canvas = tmpCanvas.canvas;
  5860. }
  5861. return {canvas: canvas,
  5862. offsetX: offsetX - BORDER_SIZE * scaleX,
  5863. offsetY: offsetY - BORDER_SIZE * scaleY,
  5864. scaleX: scaleX, scaleY: scaleY};
  5865. }
  5866. return createMeshCanvas;
  5867. })();
  5868. ShadingIRs.Mesh = {
  5869. fromIR: function Mesh_fromIR(raw) {
  5870. //var type = raw[1];
  5871. var coords = raw[2];
  5872. var colors = raw[3];
  5873. var figures = raw[4];
  5874. var bounds = raw[5];
  5875. var matrix = raw[6];
  5876. //var bbox = raw[7];
  5877. var background = raw[8];
  5878. return {
  5879. type: 'Pattern',
  5880. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5881. var scale;
  5882. if (shadingFill) {
  5883. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5884. } else {
  5885. // Obtain scale from matrix and current transformation matrix.
  5886. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5887. if (matrix) {
  5888. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5889. scale = [scale[0] * matrixScale[0],
  5890. scale[1] * matrixScale[1]];
  5891. }
  5892. }
  5893. // Rasterizing on the main thread since sending/queue large canvases
  5894. // might cause OOM.
  5895. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5896. colors, figures, shadingFill ? null : background,
  5897. owner.cachedCanvases);
  5898. if (!shadingFill) {
  5899. ctx.setTransform.apply(ctx, owner.baseTransform);
  5900. if (matrix) {
  5901. ctx.transform.apply(ctx, matrix);
  5902. }
  5903. }
  5904. ctx.translate(temporaryPatternCanvas.offsetX,
  5905. temporaryPatternCanvas.offsetY);
  5906. ctx.scale(temporaryPatternCanvas.scaleX,
  5907. temporaryPatternCanvas.scaleY);
  5908. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5909. }
  5910. };
  5911. }
  5912. };
  5913. ShadingIRs.Dummy = {
  5914. fromIR: function Dummy_fromIR() {
  5915. return {
  5916. type: 'Pattern',
  5917. getPattern: function Dummy_fromIR_getPattern() {
  5918. return 'hotpink';
  5919. }
  5920. };
  5921. }
  5922. };
  5923. function getShadingPatternFromIR(raw) {
  5924. var shadingIR = ShadingIRs[raw[0]];
  5925. if (!shadingIR) {
  5926. error('Unknown IR type: ' + raw[0]);
  5927. }
  5928. return shadingIR.fromIR(raw);
  5929. }
  5930. var TilingPattern = (function TilingPatternClosure() {
  5931. var PaintType = {
  5932. COLORED: 1,
  5933. UNCOLORED: 2
  5934. };
  5935. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5936. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5937. this.operatorList = IR[2];
  5938. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5939. this.bbox = IR[4];
  5940. this.xstep = IR[5];
  5941. this.ystep = IR[6];
  5942. this.paintType = IR[7];
  5943. this.tilingType = IR[8];
  5944. this.color = color;
  5945. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5946. this.baseTransform = baseTransform;
  5947. this.type = 'Pattern';
  5948. this.ctx = ctx;
  5949. }
  5950. TilingPattern.prototype = {
  5951. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5952. var operatorList = this.operatorList;
  5953. var bbox = this.bbox;
  5954. var xstep = this.xstep;
  5955. var ystep = this.ystep;
  5956. var paintType = this.paintType;
  5957. var tilingType = this.tilingType;
  5958. var color = this.color;
  5959. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5960. info('TilingType: ' + tilingType);
  5961. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5962. var topLeft = [x0, y0];
  5963. // we want the canvas to be as large as the step size
  5964. var botRight = [x0 + xstep, y0 + ystep];
  5965. var width = botRight[0] - topLeft[0];
  5966. var height = botRight[1] - topLeft[1];
  5967. // Obtain scale from matrix and current transformation matrix.
  5968. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5969. var curMatrixScale = Util.singularValueDecompose2dScale(
  5970. this.baseTransform);
  5971. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5972. matrixScale[1] * curMatrixScale[1]];
  5973. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5974. // Use width and height values that are as close as possible to the end
  5975. // result when the pattern is used. Too low value makes the pattern look
  5976. // blurry. Too large value makes it look too crispy.
  5977. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5978. MAX_PATTERN_SIZE);
  5979. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5980. MAX_PATTERN_SIZE);
  5981. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5982. width, height, true);
  5983. var tmpCtx = tmpCanvas.context;
  5984. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5985. graphics.groupLevel = owner.groupLevel;
  5986. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5987. this.setScale(width, height, xstep, ystep);
  5988. this.transformToScale(graphics);
  5989. // transform coordinates to pattern space
  5990. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5991. graphics.transform.apply(graphics, tmpTranslate);
  5992. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5993. graphics.executeOperatorList(operatorList);
  5994. return tmpCanvas.canvas;
  5995. },
  5996. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5997. this.scale = [width / xstep, height / ystep];
  5998. },
  5999. transformToScale: function TilingPattern_transformToScale(graphics) {
  6000. var scale = this.scale;
  6001. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  6002. graphics.transform.apply(graphics, tmpScale);
  6003. },
  6004. scaleToContext: function TilingPattern_scaleToContext() {
  6005. var scale = this.scale;
  6006. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6007. },
  6008. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6009. if (bbox && isArray(bbox) && bbox.length === 4) {
  6010. var bboxWidth = x1 - x0;
  6011. var bboxHeight = y1 - y0;
  6012. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6013. graphics.clip();
  6014. graphics.endPath();
  6015. }
  6016. },
  6017. setFillAndStrokeStyleToContext:
  6018. function setFillAndStrokeStyleToContext(context, paintType, color) {
  6019. switch (paintType) {
  6020. case PaintType.COLORED:
  6021. var ctx = this.ctx;
  6022. context.fillStyle = ctx.fillStyle;
  6023. context.strokeStyle = ctx.strokeStyle;
  6024. break;
  6025. case PaintType.UNCOLORED:
  6026. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6027. context.fillStyle = cssColor;
  6028. context.strokeStyle = cssColor;
  6029. break;
  6030. default:
  6031. error('Unsupported paint type: ' + paintType);
  6032. }
  6033. },
  6034. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6035. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6036. ctx = this.ctx;
  6037. ctx.setTransform.apply(ctx, this.baseTransform);
  6038. ctx.transform.apply(ctx, this.matrix);
  6039. this.scaleToContext();
  6040. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6041. }
  6042. };
  6043. return TilingPattern;
  6044. })();
  6045. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6046. exports.TilingPattern = TilingPattern;
  6047. }));
  6048. (function (root, factory) {
  6049. {
  6050. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  6051. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper,
  6052. root.pdfjsDisplayWebGL);
  6053. }
  6054. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper,
  6055. displayWebGL) {
  6056. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6057. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6058. var ImageKind = sharedUtil.ImageKind;
  6059. var OPS = sharedUtil.OPS;
  6060. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6061. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6062. var Util = sharedUtil.Util;
  6063. var assert = sharedUtil.assert;
  6064. var info = sharedUtil.info;
  6065. var isNum = sharedUtil.isNum;
  6066. var isArray = sharedUtil.isArray;
  6067. var isLittleEndian = sharedUtil.isLittleEndian;
  6068. var error = sharedUtil.error;
  6069. var shadow = sharedUtil.shadow;
  6070. var warn = sharedUtil.warn;
  6071. var TilingPattern = displayPatternHelper.TilingPattern;
  6072. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6073. var WebGLUtils = displayWebGL.WebGLUtils;
  6074. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6075. // <canvas> contexts store most of the state we need natively.
  6076. // However, PDF needs a bit more state, which we store here.
  6077. // Minimal font size that would be used during canvas fillText operations.
  6078. var MIN_FONT_SIZE = 16;
  6079. // Maximum font size that would be used during canvas fillText operations.
  6080. var MAX_FONT_SIZE = 100;
  6081. var MAX_GROUP_SIZE = 4096;
  6082. // Heuristic value used when enforcing minimum line widths.
  6083. var MIN_WIDTH_FACTOR = 0.65;
  6084. var COMPILE_TYPE3_GLYPHS = true;
  6085. var MAX_SIZE_TO_COMPILE = 1000;
  6086. var FULL_CHUNK_HEIGHT = 16;
  6087. var HasCanvasTypedArraysCached = {
  6088. get value() {
  6089. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6090. }
  6091. };
  6092. var IsLittleEndianCached = {
  6093. get value() {
  6094. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6095. }
  6096. };
  6097. function createScratchCanvas(width, height) {
  6098. var canvas = document.createElement('canvas');
  6099. canvas.width = width;
  6100. canvas.height = height;
  6101. return canvas;
  6102. }
  6103. function addContextCurrentTransform(ctx) {
  6104. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6105. if (!ctx.mozCurrentTransform) {
  6106. ctx._originalSave = ctx.save;
  6107. ctx._originalRestore = ctx.restore;
  6108. ctx._originalRotate = ctx.rotate;
  6109. ctx._originalScale = ctx.scale;
  6110. ctx._originalTranslate = ctx.translate;
  6111. ctx._originalTransform = ctx.transform;
  6112. ctx._originalSetTransform = ctx.setTransform;
  6113. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  6114. ctx._transformStack = [];
  6115. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6116. get: function getCurrentTransform() {
  6117. return this._transformMatrix;
  6118. }
  6119. });
  6120. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6121. get: function getCurrentTransformInverse() {
  6122. // Calculation done using WolframAlpha:
  6123. // http://www.wolframalpha.com/input/?
  6124. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6125. var m = this._transformMatrix;
  6126. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6127. var ad_bc = a * d - b * c;
  6128. var bc_ad = b * c - a * d;
  6129. return [
  6130. d / ad_bc,
  6131. b / bc_ad,
  6132. c / bc_ad,
  6133. a / ad_bc,
  6134. (d * e - c * f) / bc_ad,
  6135. (b * e - a * f) / ad_bc
  6136. ];
  6137. }
  6138. });
  6139. ctx.save = function ctxSave() {
  6140. var old = this._transformMatrix;
  6141. this._transformStack.push(old);
  6142. this._transformMatrix = old.slice(0, 6);
  6143. this._originalSave();
  6144. };
  6145. ctx.restore = function ctxRestore() {
  6146. var prev = this._transformStack.pop();
  6147. if (prev) {
  6148. this._transformMatrix = prev;
  6149. this._originalRestore();
  6150. }
  6151. };
  6152. ctx.translate = function ctxTranslate(x, y) {
  6153. var m = this._transformMatrix;
  6154. m[4] = m[0] * x + m[2] * y + m[4];
  6155. m[5] = m[1] * x + m[3] * y + m[5];
  6156. this._originalTranslate(x, y);
  6157. };
  6158. ctx.scale = function ctxScale(x, y) {
  6159. var m = this._transformMatrix;
  6160. m[0] = m[0] * x;
  6161. m[1] = m[1] * x;
  6162. m[2] = m[2] * y;
  6163. m[3] = m[3] * y;
  6164. this._originalScale(x, y);
  6165. };
  6166. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6167. var m = this._transformMatrix;
  6168. this._transformMatrix = [
  6169. m[0] * a + m[2] * b,
  6170. m[1] * a + m[3] * b,
  6171. m[0] * c + m[2] * d,
  6172. m[1] * c + m[3] * d,
  6173. m[0] * e + m[2] * f + m[4],
  6174. m[1] * e + m[3] * f + m[5]
  6175. ];
  6176. ctx._originalTransform(a, b, c, d, e, f);
  6177. };
  6178. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6179. this._transformMatrix = [a, b, c, d, e, f];
  6180. ctx._originalSetTransform(a, b, c, d, e, f);
  6181. };
  6182. ctx.rotate = function ctxRotate(angle) {
  6183. var cosValue = Math.cos(angle);
  6184. var sinValue = Math.sin(angle);
  6185. var m = this._transformMatrix;
  6186. this._transformMatrix = [
  6187. m[0] * cosValue + m[2] * sinValue,
  6188. m[1] * cosValue + m[3] * sinValue,
  6189. m[0] * (-sinValue) + m[2] * cosValue,
  6190. m[1] * (-sinValue) + m[3] * cosValue,
  6191. m[4],
  6192. m[5]
  6193. ];
  6194. this._originalRotate(angle);
  6195. };
  6196. }
  6197. }
  6198. var CachedCanvases = (function CachedCanvasesClosure() {
  6199. function CachedCanvases() {
  6200. this.cache = Object.create(null);
  6201. }
  6202. CachedCanvases.prototype = {
  6203. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  6204. trackTransform) {
  6205. var canvasEntry;
  6206. if (this.cache[id] !== undefined) {
  6207. canvasEntry = this.cache[id];
  6208. canvasEntry.canvas.width = width;
  6209. canvasEntry.canvas.height = height;
  6210. // reset canvas transform for emulated mozCurrentTransform, if needed
  6211. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6212. } else {
  6213. var canvas = createScratchCanvas(width, height);
  6214. var ctx = canvas.getContext('2d');
  6215. if (trackTransform) {
  6216. addContextCurrentTransform(ctx);
  6217. }
  6218. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  6219. }
  6220. return canvasEntry;
  6221. },
  6222. clear: function () {
  6223. for (var id in this.cache) {
  6224. var canvasEntry = this.cache[id];
  6225. // Zeroing the width and height causes Firefox to release graphics
  6226. // resources immediately, which can greatly reduce memory consumption.
  6227. canvasEntry.canvas.width = 0;
  6228. canvasEntry.canvas.height = 0;
  6229. delete this.cache[id];
  6230. }
  6231. }
  6232. };
  6233. return CachedCanvases;
  6234. })();
  6235. function compileType3Glyph(imgData) {
  6236. var POINT_TO_PROCESS_LIMIT = 1000;
  6237. var width = imgData.width, height = imgData.height;
  6238. var i, j, j0, width1 = width + 1;
  6239. var points = new Uint8Array(width1 * (height + 1));
  6240. var POINT_TYPES =
  6241. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6242. // decodes bit-packed mask data
  6243. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  6244. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6245. for (i = 0, ii = data0.length; i < ii; i++) {
  6246. var mask = 128, elem = data0[i];
  6247. while (mask > 0) {
  6248. data[pos++] = (elem & mask) ? 0 : 255;
  6249. mask >>= 1;
  6250. }
  6251. }
  6252. // finding iteresting points: every point is located between mask pixels,
  6253. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6254. // will have flags assigned based on neighboring mask pixels:
  6255. // 4 | 8
  6256. // --P--
  6257. // 2 | 1
  6258. // We are interested only in points with the flags:
  6259. // - outside corners: 1, 2, 4, 8;
  6260. // - inside corners: 7, 11, 13, 14;
  6261. // - and, intersections: 5, 10.
  6262. var count = 0;
  6263. pos = 0;
  6264. if (data[pos] !== 0) {
  6265. points[0] = 1;
  6266. ++count;
  6267. }
  6268. for (j = 1; j < width; j++) {
  6269. if (data[pos] !== data[pos + 1]) {
  6270. points[j] = data[pos] ? 2 : 1;
  6271. ++count;
  6272. }
  6273. pos++;
  6274. }
  6275. if (data[pos] !== 0) {
  6276. points[j] = 2;
  6277. ++count;
  6278. }
  6279. for (i = 1; i < height; i++) {
  6280. pos = i * lineSize;
  6281. j0 = i * width1;
  6282. if (data[pos - lineSize] !== data[pos]) {
  6283. points[j0] = data[pos] ? 1 : 8;
  6284. ++count;
  6285. }
  6286. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6287. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6288. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6289. for (j = 1; j < width; j++) {
  6290. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  6291. (data[pos - lineSize + 1] ? 8 : 0);
  6292. if (POINT_TYPES[sum]) {
  6293. points[j0 + j] = POINT_TYPES[sum];
  6294. ++count;
  6295. }
  6296. pos++;
  6297. }
  6298. if (data[pos - lineSize] !== data[pos]) {
  6299. points[j0 + j] = data[pos] ? 2 : 4;
  6300. ++count;
  6301. }
  6302. if (count > POINT_TO_PROCESS_LIMIT) {
  6303. return null;
  6304. }
  6305. }
  6306. pos = lineSize * (height - 1);
  6307. j0 = i * width1;
  6308. if (data[pos] !== 0) {
  6309. points[j0] = 8;
  6310. ++count;
  6311. }
  6312. for (j = 1; j < width; j++) {
  6313. if (data[pos] !== data[pos + 1]) {
  6314. points[j0 + j] = data[pos] ? 4 : 8;
  6315. ++count;
  6316. }
  6317. pos++;
  6318. }
  6319. if (data[pos] !== 0) {
  6320. points[j0 + j] = 4;
  6321. ++count;
  6322. }
  6323. if (count > POINT_TO_PROCESS_LIMIT) {
  6324. return null;
  6325. }
  6326. // building outlines
  6327. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6328. var outlines = [];
  6329. for (i = 0; count && i <= height; i++) {
  6330. var p = i * width1;
  6331. var end = p + width;
  6332. while (p < end && !points[p]) {
  6333. p++;
  6334. }
  6335. if (p === end) {
  6336. continue;
  6337. }
  6338. var coords = [p % width1, i];
  6339. var type = points[p], p0 = p, pp;
  6340. do {
  6341. var step = steps[type];
  6342. do {
  6343. p += step;
  6344. } while (!points[p]);
  6345. pp = points[p];
  6346. if (pp !== 5 && pp !== 10) {
  6347. // set new direction
  6348. type = pp;
  6349. // delete mark
  6350. points[p] = 0;
  6351. } else { // type is 5 or 10, ie, a crossing
  6352. // set new direction
  6353. type = pp & ((0x33 * type) >> 4);
  6354. // set new type for "future hit"
  6355. points[p] &= (type >> 2 | type << 2);
  6356. }
  6357. coords.push(p % width1);
  6358. coords.push((p / width1) | 0);
  6359. --count;
  6360. } while (p0 !== p);
  6361. outlines.push(coords);
  6362. --i;
  6363. }
  6364. var drawOutline = function(c) {
  6365. c.save();
  6366. // the path shall be painted in [0..1]x[0..1] space
  6367. c.scale(1 / width, -1 / height);
  6368. c.translate(0, -height);
  6369. c.beginPath();
  6370. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6371. var o = outlines[i];
  6372. c.moveTo(o[0], o[1]);
  6373. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6374. c.lineTo(o[j], o[j+1]);
  6375. }
  6376. }
  6377. c.fill();
  6378. c.beginPath();
  6379. c.restore();
  6380. };
  6381. return drawOutline;
  6382. }
  6383. var CanvasExtraState = (function CanvasExtraStateClosure() {
  6384. function CanvasExtraState(old) {
  6385. // Are soft masks and alpha values shapes or opacities?
  6386. this.alphaIsShape = false;
  6387. this.fontSize = 0;
  6388. this.fontSizeScale = 1;
  6389. this.textMatrix = IDENTITY_MATRIX;
  6390. this.textMatrixScale = 1;
  6391. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6392. this.leading = 0;
  6393. // Current point (in user coordinates)
  6394. this.x = 0;
  6395. this.y = 0;
  6396. // Start of text line (in text coordinates)
  6397. this.lineX = 0;
  6398. this.lineY = 0;
  6399. // Character and word spacing
  6400. this.charSpacing = 0;
  6401. this.wordSpacing = 0;
  6402. this.textHScale = 1;
  6403. this.textRenderingMode = TextRenderingMode.FILL;
  6404. this.textRise = 0;
  6405. // Default fore and background colors
  6406. this.fillColor = '#000000';
  6407. this.strokeColor = '#000000';
  6408. this.patternFill = false;
  6409. // Note: fill alpha applies to all non-stroking operations
  6410. this.fillAlpha = 1;
  6411. this.strokeAlpha = 1;
  6412. this.lineWidth = 1;
  6413. this.activeSMask = null;
  6414. this.resumeSMaskCtx = null; // nonclonable field (see the save method below)
  6415. this.old = old;
  6416. }
  6417. CanvasExtraState.prototype = {
  6418. clone: function CanvasExtraState_clone() {
  6419. return Object.create(this);
  6420. },
  6421. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6422. this.x = x;
  6423. this.y = y;
  6424. }
  6425. };
  6426. return CanvasExtraState;
  6427. })();
  6428. var CanvasGraphics = (function CanvasGraphicsClosure() {
  6429. // Defines the time the executeOperatorList is going to be executing
  6430. // before it stops and shedules a continue of execution.
  6431. var EXECUTION_TIME = 15;
  6432. // Defines the number of steps before checking the execution time
  6433. var EXECUTION_STEPS = 10;
  6434. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6435. this.ctx = canvasCtx;
  6436. this.current = new CanvasExtraState();
  6437. this.stateStack = [];
  6438. this.pendingClip = null;
  6439. this.pendingEOFill = false;
  6440. this.res = null;
  6441. this.xobjs = null;
  6442. this.commonObjs = commonObjs;
  6443. this.objs = objs;
  6444. this.imageLayer = imageLayer;
  6445. this.groupStack = [];
  6446. this.processingType3 = null;
  6447. // Patterns are painted relative to the initial page/form transform, see pdf
  6448. // spec 8.7.2 NOTE 1.
  6449. this.baseTransform = null;
  6450. this.baseTransformStack = [];
  6451. this.groupLevel = 0;
  6452. this.smaskStack = [];
  6453. this.smaskCounter = 0;
  6454. this.tempSMask = null;
  6455. this.cachedCanvases = new CachedCanvases();
  6456. if (canvasCtx) {
  6457. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6458. // the transformation must already be set in canvasCtx._transformMatrix.
  6459. addContextCurrentTransform(canvasCtx);
  6460. }
  6461. this.cachedGetSinglePixelWidth = null;
  6462. }
  6463. function putBinaryImageData(ctx, imgData) {
  6464. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6465. ctx.putImageData(imgData, 0, 0);
  6466. return;
  6467. }
  6468. // Put the image data to the canvas in chunks, rather than putting the
  6469. // whole image at once. This saves JS memory, because the ImageData object
  6470. // is smaller. It also possibly saves C++ memory within the implementation
  6471. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6472. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6473. // because too many putImageData() calls will slow things down.
  6474. //
  6475. // Note: as written, if the last chunk is partial, the putImageData() call
  6476. // will (conceptually) put pixels past the bounds of the canvas. But
  6477. // that's ok; any such pixels are ignored.
  6478. var height = imgData.height, width = imgData.width;
  6479. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6480. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6481. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6482. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6483. var srcPos = 0, destPos;
  6484. var src = imgData.data;
  6485. var dest = chunkImgData.data;
  6486. var i, j, thisChunkHeight, elemsInThisChunk;
  6487. // There are multiple forms in which the pixel data can be passed, and
  6488. // imgData.kind tells us which one this is.
  6489. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6490. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6491. var srcLength = src.byteLength;
  6492. var dest32 = HasCanvasTypedArraysCached.value ?
  6493. new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6494. var dest32DataLength = dest32.length;
  6495. var fullSrcDiff = (width + 7) >> 3;
  6496. var white = 0xFFFFFFFF;
  6497. var black = (IsLittleEndianCached.value ||
  6498. !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF;
  6499. for (i = 0; i < totalChunks; i++) {
  6500. thisChunkHeight =
  6501. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6502. destPos = 0;
  6503. for (j = 0; j < thisChunkHeight; j++) {
  6504. var srcDiff = srcLength - srcPos;
  6505. var k = 0;
  6506. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  6507. var kEndUnrolled = kEnd & ~7;
  6508. var mask = 0;
  6509. var srcByte = 0;
  6510. for (; k < kEndUnrolled; k += 8) {
  6511. srcByte = src[srcPos++];
  6512. dest32[destPos++] = (srcByte & 128) ? white : black;
  6513. dest32[destPos++] = (srcByte & 64) ? white : black;
  6514. dest32[destPos++] = (srcByte & 32) ? white : black;
  6515. dest32[destPos++] = (srcByte & 16) ? white : black;
  6516. dest32[destPos++] = (srcByte & 8) ? white : black;
  6517. dest32[destPos++] = (srcByte & 4) ? white : black;
  6518. dest32[destPos++] = (srcByte & 2) ? white : black;
  6519. dest32[destPos++] = (srcByte & 1) ? white : black;
  6520. }
  6521. for (; k < kEnd; k++) {
  6522. if (mask === 0) {
  6523. srcByte = src[srcPos++];
  6524. mask = 128;
  6525. }
  6526. dest32[destPos++] = (srcByte & mask) ? white : black;
  6527. mask >>= 1;
  6528. }
  6529. }
  6530. // We ran out of input. Make all remaining pixels transparent.
  6531. while (destPos < dest32DataLength) {
  6532. dest32[destPos++] = 0;
  6533. }
  6534. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6535. }
  6536. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6537. // RGBA, 32-bits per pixel.
  6538. j = 0;
  6539. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6540. for (i = 0; i < fullChunks; i++) {
  6541. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6542. srcPos += elemsInThisChunk;
  6543. ctx.putImageData(chunkImgData, 0, j);
  6544. j += FULL_CHUNK_HEIGHT;
  6545. }
  6546. if (i < totalChunks) {
  6547. elemsInThisChunk = width * partialChunkHeight * 4;
  6548. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6549. ctx.putImageData(chunkImgData, 0, j);
  6550. }
  6551. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6552. // RGB, 24-bits per pixel.
  6553. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6554. elemsInThisChunk = width * thisChunkHeight;
  6555. for (i = 0; i < totalChunks; i++) {
  6556. if (i >= fullChunks) {
  6557. thisChunkHeight = partialChunkHeight;
  6558. elemsInThisChunk = width * thisChunkHeight;
  6559. }
  6560. destPos = 0;
  6561. for (j = elemsInThisChunk; j--;) {
  6562. dest[destPos++] = src[srcPos++];
  6563. dest[destPos++] = src[srcPos++];
  6564. dest[destPos++] = src[srcPos++];
  6565. dest[destPos++] = 255;
  6566. }
  6567. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6568. }
  6569. } else {
  6570. error('bad image kind: ' + imgData.kind);
  6571. }
  6572. }
  6573. function putBinaryImageMask(ctx, imgData) {
  6574. var height = imgData.height, width = imgData.width;
  6575. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6576. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6577. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6578. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6579. var srcPos = 0;
  6580. var src = imgData.data;
  6581. var dest = chunkImgData.data;
  6582. for (var i = 0; i < totalChunks; i++) {
  6583. var thisChunkHeight =
  6584. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6585. // Expand the mask so it can be used by the canvas. Any required
  6586. // inversion has already been handled.
  6587. var destPos = 3; // alpha component offset
  6588. for (var j = 0; j < thisChunkHeight; j++) {
  6589. var mask = 0;
  6590. for (var k = 0; k < width; k++) {
  6591. if (!mask) {
  6592. var elem = src[srcPos++];
  6593. mask = 128;
  6594. }
  6595. dest[destPos] = (elem & mask) ? 0 : 255;
  6596. destPos += 4;
  6597. mask >>= 1;
  6598. }
  6599. }
  6600. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6601. }
  6602. }
  6603. function copyCtxState(sourceCtx, destCtx) {
  6604. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  6605. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  6606. 'globalCompositeOperation', 'font'];
  6607. for (var i = 0, ii = properties.length; i < ii; i++) {
  6608. var property = properties[i];
  6609. if (sourceCtx[property] !== undefined) {
  6610. destCtx[property] = sourceCtx[property];
  6611. }
  6612. }
  6613. if (sourceCtx.setLineDash !== undefined) {
  6614. destCtx.setLineDash(sourceCtx.getLineDash());
  6615. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6616. }
  6617. }
  6618. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6619. var length = bytes.length;
  6620. for (var i = 3; i < length; i += 4) {
  6621. var alpha = bytes[i];
  6622. if (alpha === 0) {
  6623. bytes[i - 3] = r0;
  6624. bytes[i - 2] = g0;
  6625. bytes[i - 1] = b0;
  6626. } else if (alpha < 255) {
  6627. var alpha_ = 255 - alpha;
  6628. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  6629. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  6630. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  6631. }
  6632. }
  6633. }
  6634. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6635. var length = maskData.length;
  6636. var scale = 1 / 255;
  6637. for (var i = 3; i < length; i += 4) {
  6638. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6639. layerData[i] = (layerData[i] * alpha * scale) | 0;
  6640. }
  6641. }
  6642. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6643. var length = maskData.length;
  6644. for (var i = 3; i < length; i += 4) {
  6645. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  6646. (maskData[i - 2] * 152) + // * 0.59 ....
  6647. (maskData[i - 1] * 28); // * 0.11 ....
  6648. layerData[i] = transferMap ?
  6649. (layerData[i] * transferMap[y >> 8]) >> 8 :
  6650. (layerData[i] * y) >> 16;
  6651. }
  6652. }
  6653. function genericComposeSMask(maskCtx, layerCtx, width, height,
  6654. subtype, backdrop, transferMap) {
  6655. var hasBackdrop = !!backdrop;
  6656. var r0 = hasBackdrop ? backdrop[0] : 0;
  6657. var g0 = hasBackdrop ? backdrop[1] : 0;
  6658. var b0 = hasBackdrop ? backdrop[2] : 0;
  6659. var composeFn;
  6660. if (subtype === 'Luminosity') {
  6661. composeFn = composeSMaskLuminosity;
  6662. } else {
  6663. composeFn = composeSMaskAlpha;
  6664. }
  6665. // processing image in chunks to save memory
  6666. var PIXELS_TO_PROCESS = 1048576;
  6667. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6668. for (var row = 0; row < height; row += chunkSize) {
  6669. var chunkHeight = Math.min(chunkSize, height - row);
  6670. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6671. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6672. if (hasBackdrop) {
  6673. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6674. }
  6675. composeFn(maskData.data, layerData.data, transferMap);
  6676. maskCtx.putImageData(layerData, 0, row);
  6677. }
  6678. }
  6679. function composeSMask(ctx, smask, layerCtx) {
  6680. var mask = smask.canvas;
  6681. var maskCtx = smask.context;
  6682. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  6683. smask.offsetX, smask.offsetY);
  6684. var backdrop = smask.backdrop || null;
  6685. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6686. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  6687. {subtype: smask.subtype, backdrop: backdrop});
  6688. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6689. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6690. return;
  6691. }
  6692. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  6693. smask.subtype, backdrop, smask.transferMap);
  6694. ctx.drawImage(mask, 0, 0);
  6695. }
  6696. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6697. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6698. var NORMAL_CLIP = {};
  6699. var EO_CLIP = {};
  6700. CanvasGraphics.prototype = {
  6701. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  6702. transparency) {
  6703. // For pdfs that use blend modes we have to clear the canvas else certain
  6704. // blend modes can look wrong since we'd be blending with a white
  6705. // backdrop. The problem with a transparent backdrop though is we then
  6706. // don't get sub pixel anti aliasing on text, creating temporary
  6707. // transparent canvas when we have blend modes.
  6708. var width = this.ctx.canvas.width;
  6709. var height = this.ctx.canvas.height;
  6710. this.ctx.save();
  6711. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6712. this.ctx.fillRect(0, 0, width, height);
  6713. this.ctx.restore();
  6714. if (transparency) {
  6715. var transparentCanvas = this.cachedCanvases.getCanvas(
  6716. 'transparent', width, height, true);
  6717. this.compositeCtx = this.ctx;
  6718. this.transparentCanvas = transparentCanvas.canvas;
  6719. this.ctx = transparentCanvas.context;
  6720. this.ctx.save();
  6721. // The transform can be applied before rendering, transferring it to
  6722. // the new canvas.
  6723. this.ctx.transform.apply(this.ctx,
  6724. this.compositeCtx.mozCurrentTransform);
  6725. }
  6726. this.ctx.save();
  6727. if (transform) {
  6728. this.ctx.transform.apply(this.ctx, transform);
  6729. }
  6730. this.ctx.transform.apply(this.ctx, viewport.transform);
  6731. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6732. if (this.imageLayer) {
  6733. this.imageLayer.beginLayout();
  6734. }
  6735. },
  6736. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6737. operatorList,
  6738. executionStartIdx, continueCallback,
  6739. stepper) {
  6740. var argsArray = operatorList.argsArray;
  6741. var fnArray = operatorList.fnArray;
  6742. var i = executionStartIdx || 0;
  6743. var argsArrayLen = argsArray.length;
  6744. // Sometimes the OperatorList to execute is empty.
  6745. if (argsArrayLen === i) {
  6746. return i;
  6747. }
  6748. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6749. typeof continueCallback === 'function');
  6750. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6751. var steps = 0;
  6752. var commonObjs = this.commonObjs;
  6753. var objs = this.objs;
  6754. var fnId;
  6755. while (true) {
  6756. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6757. stepper.breakIt(i, continueCallback);
  6758. return i;
  6759. }
  6760. fnId = fnArray[i];
  6761. if (fnId !== OPS.dependency) {
  6762. this[fnId].apply(this, argsArray[i]);
  6763. } else {
  6764. var deps = argsArray[i];
  6765. for (var n = 0, nn = deps.length; n < nn; n++) {
  6766. var depObjId = deps[n];
  6767. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6768. var objsPool = common ? commonObjs : objs;
  6769. // If the promise isn't resolved yet, add the continueCallback
  6770. // to the promise and bail out.
  6771. if (!objsPool.isResolved(depObjId)) {
  6772. objsPool.get(depObjId, continueCallback);
  6773. return i;
  6774. }
  6775. }
  6776. }
  6777. i++;
  6778. // If the entire operatorList was executed, stop as were done.
  6779. if (i === argsArrayLen) {
  6780. return i;
  6781. }
  6782. // If the execution took longer then a certain amount of time and
  6783. // `continueCallback` is specified, interrupt the execution.
  6784. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6785. if (Date.now() > endTime) {
  6786. continueCallback();
  6787. return i;
  6788. }
  6789. steps = 0;
  6790. }
  6791. // If the operatorList isn't executed completely yet OR the execution
  6792. // time was short enough, do another execution round.
  6793. }
  6794. },
  6795. endDrawing: function CanvasGraphics_endDrawing() {
  6796. // Finishing all opened operations such as SMask group painting.
  6797. if (this.current.activeSMask !== null) {
  6798. this.endSMaskGroup();
  6799. }
  6800. this.ctx.restore();
  6801. if (this.transparentCanvas) {
  6802. this.ctx = this.compositeCtx;
  6803. this.ctx.save();
  6804. this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice
  6805. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6806. this.ctx.restore();
  6807. this.transparentCanvas = null;
  6808. }
  6809. this.cachedCanvases.clear();
  6810. WebGLUtils.clear();
  6811. if (this.imageLayer) {
  6812. this.imageLayer.endLayout();
  6813. }
  6814. },
  6815. // Graphics state
  6816. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6817. this.current.lineWidth = width;
  6818. this.ctx.lineWidth = width;
  6819. },
  6820. setLineCap: function CanvasGraphics_setLineCap(style) {
  6821. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6822. },
  6823. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6824. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6825. },
  6826. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6827. this.ctx.miterLimit = limit;
  6828. },
  6829. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6830. var ctx = this.ctx;
  6831. if (ctx.setLineDash !== undefined) {
  6832. ctx.setLineDash(dashArray);
  6833. ctx.lineDashOffset = dashPhase;
  6834. }
  6835. },
  6836. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6837. // Maybe if we one day fully support color spaces this will be important
  6838. // for now we can ignore.
  6839. // TODO set rendering intent?
  6840. },
  6841. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6842. // There's no way to control this with canvas, but we can safely ignore.
  6843. // TODO set flatness?
  6844. },
  6845. setGState: function CanvasGraphics_setGState(states) {
  6846. for (var i = 0, ii = states.length; i < ii; i++) {
  6847. var state = states[i];
  6848. var key = state[0];
  6849. var value = state[1];
  6850. switch (key) {
  6851. case 'LW':
  6852. this.setLineWidth(value);
  6853. break;
  6854. case 'LC':
  6855. this.setLineCap(value);
  6856. break;
  6857. case 'LJ':
  6858. this.setLineJoin(value);
  6859. break;
  6860. case 'ML':
  6861. this.setMiterLimit(value);
  6862. break;
  6863. case 'D':
  6864. this.setDash(value[0], value[1]);
  6865. break;
  6866. case 'RI':
  6867. this.setRenderingIntent(value);
  6868. break;
  6869. case 'FL':
  6870. this.setFlatness(value);
  6871. break;
  6872. case 'Font':
  6873. this.setFont(value[0], value[1]);
  6874. break;
  6875. case 'CA':
  6876. this.current.strokeAlpha = state[1];
  6877. break;
  6878. case 'ca':
  6879. this.current.fillAlpha = state[1];
  6880. this.ctx.globalAlpha = state[1];
  6881. break;
  6882. case 'BM':
  6883. if (value && value.name && (value.name !== 'Normal')) {
  6884. var mode = value.name.replace(/([A-Z])/g,
  6885. function(c) {
  6886. return '-' + c.toLowerCase();
  6887. }
  6888. ).substring(1);
  6889. this.ctx.globalCompositeOperation = mode;
  6890. if (this.ctx.globalCompositeOperation !== mode) {
  6891. warn('globalCompositeOperation "' + mode +
  6892. '" is not supported');
  6893. }
  6894. } else {
  6895. this.ctx.globalCompositeOperation = 'source-over';
  6896. }
  6897. break;
  6898. case 'SMask':
  6899. if (this.current.activeSMask) {
  6900. // If SMask is currrenly used, it needs to be suspended or
  6901. // finished. Suspend only makes sense when at least one save()
  6902. // was performed and state needs to be reverted on restore().
  6903. if (this.stateStack.length > 0 &&
  6904. (this.stateStack[this.stateStack.length - 1].activeSMask ===
  6905. this.current.activeSMask)) {
  6906. this.suspendSMaskGroup();
  6907. } else {
  6908. this.endSMaskGroup();
  6909. }
  6910. }
  6911. this.current.activeSMask = value ? this.tempSMask : null;
  6912. if (this.current.activeSMask) {
  6913. this.beginSMaskGroup();
  6914. }
  6915. this.tempSMask = null;
  6916. break;
  6917. }
  6918. }
  6919. },
  6920. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6921. var activeSMask = this.current.activeSMask;
  6922. var drawnWidth = activeSMask.canvas.width;
  6923. var drawnHeight = activeSMask.canvas.height;
  6924. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6925. var scratchCanvas = this.cachedCanvases.getCanvas(
  6926. cacheId, drawnWidth, drawnHeight, true);
  6927. var currentCtx = this.ctx;
  6928. var currentTransform = currentCtx.mozCurrentTransform;
  6929. this.ctx.save();
  6930. var groupCtx = scratchCanvas.context;
  6931. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6932. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6933. groupCtx.transform.apply(groupCtx, currentTransform);
  6934. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6935. copyCtxState(currentCtx, groupCtx);
  6936. this.ctx = groupCtx;
  6937. this.setGState([
  6938. ['BM', 'Normal'],
  6939. ['ca', 1],
  6940. ['CA', 1]
  6941. ]);
  6942. this.groupStack.push(currentCtx);
  6943. this.groupLevel++;
  6944. },
  6945. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6946. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  6947. // and future ctx state restored.
  6948. var groupCtx = this.ctx;
  6949. this.groupLevel--;
  6950. this.ctx = this.groupStack.pop();
  6951. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6952. this.ctx.restore();
  6953. this.ctx.save(); // save is needed since SMask will be resumed.
  6954. copyCtxState(groupCtx, this.ctx);
  6955. // Saving state for resuming.
  6956. this.current.resumeSMaskCtx = groupCtx;
  6957. // Transform was changed in the SMask canvas, reflecting this change on
  6958. // this.ctx.
  6959. var deltaTransform = Util.transform(
  6960. this.current.activeSMask.startTransformInverse,
  6961. groupCtx.mozCurrentTransform);
  6962. this.ctx.transform.apply(this.ctx, deltaTransform);
  6963. // SMask was composed, the results at the groupCtx can be cleared.
  6964. groupCtx.save();
  6965. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  6966. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  6967. groupCtx.restore();
  6968. },
  6969. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6970. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  6971. // any groupCtx state since restore() command (the only caller) will do
  6972. // that for us. See also beginSMaskGroup.
  6973. var groupCtx = this.current.resumeSMaskCtx;
  6974. var currentCtx = this.ctx;
  6975. this.ctx = groupCtx;
  6976. this.groupStack.push(currentCtx);
  6977. this.groupLevel++;
  6978. },
  6979. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6980. var groupCtx = this.ctx;
  6981. this.groupLevel--;
  6982. this.ctx = this.groupStack.pop();
  6983. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6984. this.ctx.restore();
  6985. copyCtxState(groupCtx, this.ctx);
  6986. // Transform was changed in the SMask canvas, reflecting this change on
  6987. // this.ctx.
  6988. var deltaTransform = Util.transform(
  6989. this.current.activeSMask.startTransformInverse,
  6990. groupCtx.mozCurrentTransform);
  6991. this.ctx.transform.apply(this.ctx, deltaTransform);
  6992. },
  6993. save: function CanvasGraphics_save() {
  6994. this.ctx.save();
  6995. var old = this.current;
  6996. this.stateStack.push(old);
  6997. this.current = old.clone();
  6998. this.current.resumeSMaskCtx = null;
  6999. },
  7000. restore: function CanvasGraphics_restore() {
  7001. // SMask was suspended, we just need to resume it.
  7002. if (this.current.resumeSMaskCtx) {
  7003. this.resumeSMaskGroup();
  7004. }
  7005. // SMask has to be finished once there is no states that are using the
  7006. // same SMask.
  7007. if (this.current.activeSMask !== null && (this.stateStack.length === 0 ||
  7008. this.stateStack[this.stateStack.length - 1].activeSMask !==
  7009. this.current.activeSMask)) {
  7010. this.endSMaskGroup();
  7011. }
  7012. if (this.stateStack.length !== 0) {
  7013. this.current = this.stateStack.pop();
  7014. this.ctx.restore();
  7015. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7016. this.pendingClip = null;
  7017. this.cachedGetSinglePixelWidth = null;
  7018. }
  7019. },
  7020. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7021. this.ctx.transform(a, b, c, d, e, f);
  7022. this.cachedGetSinglePixelWidth = null;
  7023. },
  7024. // Path
  7025. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7026. var ctx = this.ctx;
  7027. var current = this.current;
  7028. var x = current.x, y = current.y;
  7029. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7030. switch (ops[i] | 0) {
  7031. case OPS.rectangle:
  7032. x = args[j++];
  7033. y = args[j++];
  7034. var width = args[j++];
  7035. var height = args[j++];
  7036. if (width === 0) {
  7037. width = this.getSinglePixelWidth();
  7038. }
  7039. if (height === 0) {
  7040. height = this.getSinglePixelWidth();
  7041. }
  7042. var xw = x + width;
  7043. var yh = y + height;
  7044. this.ctx.moveTo(x, y);
  7045. this.ctx.lineTo(xw, y);
  7046. this.ctx.lineTo(xw, yh);
  7047. this.ctx.lineTo(x, yh);
  7048. this.ctx.lineTo(x, y);
  7049. this.ctx.closePath();
  7050. break;
  7051. case OPS.moveTo:
  7052. x = args[j++];
  7053. y = args[j++];
  7054. ctx.moveTo(x, y);
  7055. break;
  7056. case OPS.lineTo:
  7057. x = args[j++];
  7058. y = args[j++];
  7059. ctx.lineTo(x, y);
  7060. break;
  7061. case OPS.curveTo:
  7062. x = args[j + 4];
  7063. y = args[j + 5];
  7064. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  7065. x, y);
  7066. j += 6;
  7067. break;
  7068. case OPS.curveTo2:
  7069. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  7070. args[j + 2], args[j + 3]);
  7071. x = args[j + 2];
  7072. y = args[j + 3];
  7073. j += 4;
  7074. break;
  7075. case OPS.curveTo3:
  7076. x = args[j + 2];
  7077. y = args[j + 3];
  7078. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7079. j += 4;
  7080. break;
  7081. case OPS.closePath:
  7082. ctx.closePath();
  7083. break;
  7084. }
  7085. }
  7086. current.setCurrentPoint(x, y);
  7087. },
  7088. closePath: function CanvasGraphics_closePath() {
  7089. this.ctx.closePath();
  7090. },
  7091. stroke: function CanvasGraphics_stroke(consumePath) {
  7092. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7093. var ctx = this.ctx;
  7094. var strokeColor = this.current.strokeColor;
  7095. // Prevent drawing too thin lines by enforcing a minimum line width.
  7096. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  7097. this.current.lineWidth);
  7098. // For stroke we want to temporarily change the global alpha to the
  7099. // stroking alpha.
  7100. ctx.globalAlpha = this.current.strokeAlpha;
  7101. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  7102. strokeColor.type === 'Pattern') {
  7103. // for patterns, we transform to pattern space, calculate
  7104. // the pattern, call stroke, and restore to user space
  7105. ctx.save();
  7106. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7107. ctx.stroke();
  7108. ctx.restore();
  7109. } else {
  7110. ctx.stroke();
  7111. }
  7112. if (consumePath) {
  7113. this.consumePath();
  7114. }
  7115. // Restore the global alpha to the fill alpha
  7116. ctx.globalAlpha = this.current.fillAlpha;
  7117. },
  7118. closeStroke: function CanvasGraphics_closeStroke() {
  7119. this.closePath();
  7120. this.stroke();
  7121. },
  7122. fill: function CanvasGraphics_fill(consumePath) {
  7123. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7124. var ctx = this.ctx;
  7125. var fillColor = this.current.fillColor;
  7126. var isPatternFill = this.current.patternFill;
  7127. var needRestore = false;
  7128. if (isPatternFill) {
  7129. ctx.save();
  7130. if (this.baseTransform) {
  7131. ctx.setTransform.apply(ctx, this.baseTransform);
  7132. }
  7133. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7134. needRestore = true;
  7135. }
  7136. if (this.pendingEOFill) {
  7137. if (ctx.mozFillRule !== undefined) {
  7138. ctx.mozFillRule = 'evenodd';
  7139. ctx.fill();
  7140. ctx.mozFillRule = 'nonzero';
  7141. } else {
  7142. ctx.fill('evenodd');
  7143. }
  7144. this.pendingEOFill = false;
  7145. } else {
  7146. ctx.fill();
  7147. }
  7148. if (needRestore) {
  7149. ctx.restore();
  7150. }
  7151. if (consumePath) {
  7152. this.consumePath();
  7153. }
  7154. },
  7155. eoFill: function CanvasGraphics_eoFill() {
  7156. this.pendingEOFill = true;
  7157. this.fill();
  7158. },
  7159. fillStroke: function CanvasGraphics_fillStroke() {
  7160. this.fill(false);
  7161. this.stroke(false);
  7162. this.consumePath();
  7163. },
  7164. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7165. this.pendingEOFill = true;
  7166. this.fillStroke();
  7167. },
  7168. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7169. this.closePath();
  7170. this.fillStroke();
  7171. },
  7172. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7173. this.pendingEOFill = true;
  7174. this.closePath();
  7175. this.fillStroke();
  7176. },
  7177. endPath: function CanvasGraphics_endPath() {
  7178. this.consumePath();
  7179. },
  7180. // Clipping
  7181. clip: function CanvasGraphics_clip() {
  7182. this.pendingClip = NORMAL_CLIP;
  7183. },
  7184. eoClip: function CanvasGraphics_eoClip() {
  7185. this.pendingClip = EO_CLIP;
  7186. },
  7187. // Text
  7188. beginText: function CanvasGraphics_beginText() {
  7189. this.current.textMatrix = IDENTITY_MATRIX;
  7190. this.current.textMatrixScale = 1;
  7191. this.current.x = this.current.lineX = 0;
  7192. this.current.y = this.current.lineY = 0;
  7193. },
  7194. endText: function CanvasGraphics_endText() {
  7195. var paths = this.pendingTextPaths;
  7196. var ctx = this.ctx;
  7197. if (paths === undefined) {
  7198. ctx.beginPath();
  7199. return;
  7200. }
  7201. ctx.save();
  7202. ctx.beginPath();
  7203. for (var i = 0; i < paths.length; i++) {
  7204. var path = paths[i];
  7205. ctx.setTransform.apply(ctx, path.transform);
  7206. ctx.translate(path.x, path.y);
  7207. path.addToPath(ctx, path.fontSize);
  7208. }
  7209. ctx.restore();
  7210. ctx.clip();
  7211. ctx.beginPath();
  7212. delete this.pendingTextPaths;
  7213. },
  7214. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7215. this.current.charSpacing = spacing;
  7216. },
  7217. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7218. this.current.wordSpacing = spacing;
  7219. },
  7220. setHScale: function CanvasGraphics_setHScale(scale) {
  7221. this.current.textHScale = scale / 100;
  7222. },
  7223. setLeading: function CanvasGraphics_setLeading(leading) {
  7224. this.current.leading = -leading;
  7225. },
  7226. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7227. var fontObj = this.commonObjs.get(fontRefName);
  7228. var current = this.current;
  7229. if (!fontObj) {
  7230. error('Can\'t find font for ' + fontRefName);
  7231. }
  7232. current.fontMatrix = (fontObj.fontMatrix ?
  7233. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  7234. // A valid matrix needs all main diagonal elements to be non-zero
  7235. // This also ensures we bypass FF bugzilla bug #719844.
  7236. if (current.fontMatrix[0] === 0 ||
  7237. current.fontMatrix[3] === 0) {
  7238. warn('Invalid font matrix for font ' + fontRefName);
  7239. }
  7240. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7241. // and in some docs this can be negative (inverted x-y axes).
  7242. if (size < 0) {
  7243. size = -size;
  7244. current.fontDirection = -1;
  7245. } else {
  7246. current.fontDirection = 1;
  7247. }
  7248. this.current.font = fontObj;
  7249. this.current.fontSize = size;
  7250. if (fontObj.isType3Font) {
  7251. return; // we don't need ctx.font for Type3 fonts
  7252. }
  7253. var name = fontObj.loadedName || 'sans-serif';
  7254. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  7255. (fontObj.bold ? 'bold' : 'normal');
  7256. var italic = fontObj.italic ? 'italic' : 'normal';
  7257. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7258. // Some font backends cannot handle fonts below certain size.
  7259. // Keeping the font at minimal size and using the fontSizeScale to change
  7260. // the current transformation matrix before the fillText/strokeText.
  7261. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7262. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  7263. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7264. this.current.fontSizeScale = size / browserFontSize;
  7265. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7266. this.ctx.font = rule;
  7267. },
  7268. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7269. this.current.textRenderingMode = mode;
  7270. },
  7271. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7272. this.current.textRise = rise;
  7273. },
  7274. moveText: function CanvasGraphics_moveText(x, y) {
  7275. this.current.x = this.current.lineX += x;
  7276. this.current.y = this.current.lineY += y;
  7277. },
  7278. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7279. this.setLeading(-y);
  7280. this.moveText(x, y);
  7281. },
  7282. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7283. this.current.textMatrix = [a, b, c, d, e, f];
  7284. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7285. this.current.x = this.current.lineX = 0;
  7286. this.current.y = this.current.lineY = 0;
  7287. },
  7288. nextLine: function CanvasGraphics_nextLine() {
  7289. this.moveText(0, this.current.leading);
  7290. },
  7291. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7292. var ctx = this.ctx;
  7293. var current = this.current;
  7294. var font = current.font;
  7295. var textRenderingMode = current.textRenderingMode;
  7296. var fontSize = current.fontSize / current.fontSizeScale;
  7297. var fillStrokeMode = textRenderingMode &
  7298. TextRenderingMode.FILL_STROKE_MASK;
  7299. var isAddToPathSet = !!(textRenderingMode &
  7300. TextRenderingMode.ADD_TO_PATH_FLAG);
  7301. var addToPath;
  7302. if (font.disableFontFace || isAddToPathSet) {
  7303. addToPath = font.getPathGenerator(this.commonObjs, character);
  7304. }
  7305. if (font.disableFontFace) {
  7306. ctx.save();
  7307. ctx.translate(x, y);
  7308. ctx.beginPath();
  7309. addToPath(ctx, fontSize);
  7310. if (fillStrokeMode === TextRenderingMode.FILL ||
  7311. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7312. ctx.fill();
  7313. }
  7314. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7315. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7316. ctx.stroke();
  7317. }
  7318. ctx.restore();
  7319. } else {
  7320. if (fillStrokeMode === TextRenderingMode.FILL ||
  7321. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7322. ctx.fillText(character, x, y);
  7323. }
  7324. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7325. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7326. ctx.strokeText(character, x, y);
  7327. }
  7328. }
  7329. if (isAddToPathSet) {
  7330. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7331. paths.push({
  7332. transform: ctx.mozCurrentTransform,
  7333. x: x,
  7334. y: y,
  7335. fontSize: fontSize,
  7336. addToPath: addToPath
  7337. });
  7338. }
  7339. },
  7340. get isFontSubpixelAAEnabled() {
  7341. // Checks if anti-aliasing is enabled when scaled text is painted.
  7342. // On Windows GDI scaled fonts looks bad.
  7343. var ctx = document.createElement('canvas').getContext('2d');
  7344. ctx.scale(1.5, 1);
  7345. ctx.fillText('I', 0, 10);
  7346. var data = ctx.getImageData(0, 0, 10, 10).data;
  7347. var enabled = false;
  7348. for (var i = 3; i < data.length; i += 4) {
  7349. if (data[i] > 0 && data[i] < 255) {
  7350. enabled = true;
  7351. break;
  7352. }
  7353. }
  7354. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7355. },
  7356. showText: function CanvasGraphics_showText(glyphs) {
  7357. var current = this.current;
  7358. var font = current.font;
  7359. if (font.isType3Font) {
  7360. return this.showType3Text(glyphs);
  7361. }
  7362. var fontSize = current.fontSize;
  7363. if (fontSize === 0) {
  7364. return;
  7365. }
  7366. var ctx = this.ctx;
  7367. var fontSizeScale = current.fontSizeScale;
  7368. var charSpacing = current.charSpacing;
  7369. var wordSpacing = current.wordSpacing;
  7370. var fontDirection = current.fontDirection;
  7371. var textHScale = current.textHScale * fontDirection;
  7372. var glyphsLength = glyphs.length;
  7373. var vertical = font.vertical;
  7374. var spacingDir = vertical ? 1 : -1;
  7375. var defaultVMetrics = font.defaultVMetrics;
  7376. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7377. var simpleFillText =
  7378. current.textRenderingMode === TextRenderingMode.FILL &&
  7379. !font.disableFontFace;
  7380. ctx.save();
  7381. ctx.transform.apply(ctx, current.textMatrix);
  7382. ctx.translate(current.x, current.y + current.textRise);
  7383. if (current.patternFill) {
  7384. // TODO: Some shading patterns are not applied correctly to text,
  7385. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7386. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7387. }
  7388. if (fontDirection > 0) {
  7389. ctx.scale(textHScale, -1);
  7390. } else {
  7391. ctx.scale(textHScale, 1);
  7392. }
  7393. var lineWidth = current.lineWidth;
  7394. var scale = current.textMatrixScale;
  7395. if (scale === 0 || lineWidth === 0) {
  7396. var fillStrokeMode = current.textRenderingMode &
  7397. TextRenderingMode.FILL_STROKE_MASK;
  7398. if (fillStrokeMode === TextRenderingMode.STROKE ||
  7399. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7400. this.cachedGetSinglePixelWidth = null;
  7401. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7402. }
  7403. } else {
  7404. lineWidth /= scale;
  7405. }
  7406. if (fontSizeScale !== 1.0) {
  7407. ctx.scale(fontSizeScale, fontSizeScale);
  7408. lineWidth /= fontSizeScale;
  7409. }
  7410. ctx.lineWidth = lineWidth;
  7411. var x = 0, i;
  7412. for (i = 0; i < glyphsLength; ++i) {
  7413. var glyph = glyphs[i];
  7414. if (isNum(glyph)) {
  7415. x += spacingDir * glyph * fontSize / 1000;
  7416. continue;
  7417. }
  7418. var restoreNeeded = false;
  7419. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7420. var character = glyph.fontChar;
  7421. var accent = glyph.accent;
  7422. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7423. var width = glyph.width;
  7424. if (vertical) {
  7425. var vmetric, vx, vy;
  7426. vmetric = glyph.vmetric || defaultVMetrics;
  7427. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7428. vx = -vx * widthAdvanceScale;
  7429. vy = vmetric[2] * widthAdvanceScale;
  7430. width = vmetric ? -vmetric[0] : width;
  7431. scaledX = vx / fontSizeScale;
  7432. scaledY = (x + vy) / fontSizeScale;
  7433. } else {
  7434. scaledX = x / fontSizeScale;
  7435. scaledY = 0;
  7436. }
  7437. if (font.remeasure && width > 0) {
  7438. // Some standard fonts may not have the exact width: rescale per
  7439. // character if measured width is greater than expected glyph width
  7440. // and subpixel-aa is enabled, otherwise just center the glyph.
  7441. var measuredWidth = ctx.measureText(character).width * 1000 /
  7442. fontSize * fontSizeScale;
  7443. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7444. var characterScaleX = width / measuredWidth;
  7445. restoreNeeded = true;
  7446. ctx.save();
  7447. ctx.scale(characterScaleX, 1);
  7448. scaledX /= characterScaleX;
  7449. } else if (width !== measuredWidth) {
  7450. scaledX += (width - measuredWidth) / 2000 *
  7451. fontSize / fontSizeScale;
  7452. }
  7453. }
  7454. // Only attempt to draw the glyph if it is actually in the embedded font
  7455. // file or if there isn't a font file so the fallback font is shown.
  7456. if (glyph.isInFont || font.missingFile) {
  7457. if (simpleFillText && !accent) {
  7458. // common case
  7459. ctx.fillText(character, scaledX, scaledY);
  7460. } else {
  7461. this.paintChar(character, scaledX, scaledY);
  7462. if (accent) {
  7463. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7464. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7465. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7466. }
  7467. }
  7468. }
  7469. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7470. x += charWidth;
  7471. if (restoreNeeded) {
  7472. ctx.restore();
  7473. }
  7474. }
  7475. if (vertical) {
  7476. current.y -= x * textHScale;
  7477. } else {
  7478. current.x += x * textHScale;
  7479. }
  7480. ctx.restore();
  7481. },
  7482. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7483. // Type3 fonts - each glyph is a "mini-PDF"
  7484. var ctx = this.ctx;
  7485. var current = this.current;
  7486. var font = current.font;
  7487. var fontSize = current.fontSize;
  7488. var fontDirection = current.fontDirection;
  7489. var spacingDir = font.vertical ? 1 : -1;
  7490. var charSpacing = current.charSpacing;
  7491. var wordSpacing = current.wordSpacing;
  7492. var textHScale = current.textHScale * fontDirection;
  7493. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7494. var glyphsLength = glyphs.length;
  7495. var isTextInvisible =
  7496. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7497. var i, glyph, width, spacingLength;
  7498. if (isTextInvisible || fontSize === 0) {
  7499. return;
  7500. }
  7501. this.cachedGetSinglePixelWidth = null;
  7502. ctx.save();
  7503. ctx.transform.apply(ctx, current.textMatrix);
  7504. ctx.translate(current.x, current.y);
  7505. ctx.scale(textHScale, fontDirection);
  7506. for (i = 0; i < glyphsLength; ++i) {
  7507. glyph = glyphs[i];
  7508. if (isNum(glyph)) {
  7509. spacingLength = spacingDir * glyph * fontSize / 1000;
  7510. this.ctx.translate(spacingLength, 0);
  7511. current.x += spacingLength * textHScale;
  7512. continue;
  7513. }
  7514. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7515. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7516. if (!operatorList) {
  7517. warn('Type3 character \"' + glyph.operatorListId +
  7518. '\" is not available');
  7519. continue;
  7520. }
  7521. this.processingType3 = glyph;
  7522. this.save();
  7523. ctx.scale(fontSize, fontSize);
  7524. ctx.transform.apply(ctx, fontMatrix);
  7525. this.executeOperatorList(operatorList);
  7526. this.restore();
  7527. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  7528. width = transformed[0] * fontSize + spacing;
  7529. ctx.translate(width, 0);
  7530. current.x += width * textHScale;
  7531. }
  7532. ctx.restore();
  7533. this.processingType3 = null;
  7534. },
  7535. // Type3 fonts
  7536. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7537. // We can safely ignore this since the width should be the same
  7538. // as the width in the Widths array.
  7539. },
  7540. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  7541. yWidth,
  7542. llx,
  7543. lly,
  7544. urx,
  7545. ury) {
  7546. // TODO According to the spec we're also suppose to ignore any operators
  7547. // that set color or include images while processing this type3 font.
  7548. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7549. this.clip();
  7550. this.endPath();
  7551. },
  7552. // Color
  7553. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7554. var pattern;
  7555. if (IR[0] === 'TilingPattern') {
  7556. var color = IR[1];
  7557. var baseTransform = this.baseTransform ||
  7558. this.ctx.mozCurrentTransform.slice();
  7559. var self = this;
  7560. var canvasGraphicsFactory = {
  7561. createCanvasGraphics: function (ctx) {
  7562. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7563. }
  7564. };
  7565. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  7566. baseTransform);
  7567. } else {
  7568. pattern = getShadingPatternFromIR(IR);
  7569. }
  7570. return pattern;
  7571. },
  7572. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  7573. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7574. },
  7575. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  7576. this.current.fillColor = this.getColorN_Pattern(arguments);
  7577. this.current.patternFill = true;
  7578. },
  7579. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7580. var color = Util.makeCssRgb(r, g, b);
  7581. this.ctx.strokeStyle = color;
  7582. this.current.strokeColor = color;
  7583. },
  7584. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7585. var color = Util.makeCssRgb(r, g, b);
  7586. this.ctx.fillStyle = color;
  7587. this.current.fillColor = color;
  7588. this.current.patternFill = false;
  7589. },
  7590. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7591. var ctx = this.ctx;
  7592. this.save();
  7593. var pattern = getShadingPatternFromIR(patternIR);
  7594. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7595. var inv = ctx.mozCurrentTransformInverse;
  7596. if (inv) {
  7597. var canvas = ctx.canvas;
  7598. var width = canvas.width;
  7599. var height = canvas.height;
  7600. var bl = Util.applyTransform([0, 0], inv);
  7601. var br = Util.applyTransform([0, height], inv);
  7602. var ul = Util.applyTransform([width, 0], inv);
  7603. var ur = Util.applyTransform([width, height], inv);
  7604. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7605. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7606. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7607. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7608. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7609. } else {
  7610. // HACK to draw the gradient onto an infinite rectangle.
  7611. // PDF gradients are drawn across the entire image while
  7612. // Canvas only allows gradients to be drawn in a rectangle
  7613. // The following bug should allow us to remove this.
  7614. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7615. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7616. }
  7617. this.restore();
  7618. },
  7619. // Images
  7620. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7621. error('Should not call beginInlineImage');
  7622. },
  7623. beginImageData: function CanvasGraphics_beginImageData() {
  7624. error('Should not call beginImageData');
  7625. },
  7626. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  7627. bbox) {
  7628. this.save();
  7629. this.baseTransformStack.push(this.baseTransform);
  7630. if (isArray(matrix) && 6 === matrix.length) {
  7631. this.transform.apply(this, matrix);
  7632. }
  7633. this.baseTransform = this.ctx.mozCurrentTransform;
  7634. if (isArray(bbox) && 4 === bbox.length) {
  7635. var width = bbox[2] - bbox[0];
  7636. var height = bbox[3] - bbox[1];
  7637. this.ctx.rect(bbox[0], bbox[1], width, height);
  7638. this.clip();
  7639. this.endPath();
  7640. }
  7641. },
  7642. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7643. this.restore();
  7644. this.baseTransform = this.baseTransformStack.pop();
  7645. },
  7646. beginGroup: function CanvasGraphics_beginGroup(group) {
  7647. this.save();
  7648. var currentCtx = this.ctx;
  7649. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7650. // group results aren't usually that different and they even have tools
  7651. // that ignore this setting. Notes from Rik on implementing:
  7652. // - When you encounter an transparency group, create a new canvas with
  7653. // the dimensions of the bbox
  7654. // - copy the content from the previous canvas to the new canvas
  7655. // - draw as usual
  7656. // - remove the backdrop alpha:
  7657. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7658. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7659. // backdrop
  7660. // - remove background color:
  7661. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  7662. if (!group.isolated) {
  7663. info('TODO: Support non-isolated groups.');
  7664. }
  7665. // TODO knockout - supposedly possible with the clever use of compositing
  7666. // modes.
  7667. if (group.knockout) {
  7668. warn('Knockout groups not supported.');
  7669. }
  7670. var currentTransform = currentCtx.mozCurrentTransform;
  7671. if (group.matrix) {
  7672. currentCtx.transform.apply(currentCtx, group.matrix);
  7673. }
  7674. assert(group.bbox, 'Bounding box is required.');
  7675. // Based on the current transform figure out how big the bounding box
  7676. // will actually be.
  7677. var bounds = Util.getAxialAlignedBoundingBox(
  7678. group.bbox,
  7679. currentCtx.mozCurrentTransform);
  7680. // Clip the bounding box to the current canvas.
  7681. var canvasBounds = [0,
  7682. 0,
  7683. currentCtx.canvas.width,
  7684. currentCtx.canvas.height];
  7685. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7686. // Use ceil in case we're between sizes so we don't create canvas that is
  7687. // too small and make the canvas at least 1x1 pixels.
  7688. var offsetX = Math.floor(bounds[0]);
  7689. var offsetY = Math.floor(bounds[1]);
  7690. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7691. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7692. var scaleX = 1, scaleY = 1;
  7693. if (drawnWidth > MAX_GROUP_SIZE) {
  7694. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7695. drawnWidth = MAX_GROUP_SIZE;
  7696. }
  7697. if (drawnHeight > MAX_GROUP_SIZE) {
  7698. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7699. drawnHeight = MAX_GROUP_SIZE;
  7700. }
  7701. var cacheId = 'groupAt' + this.groupLevel;
  7702. if (group.smask) {
  7703. // Using two cache entries is case if masks are used one after another.
  7704. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  7705. }
  7706. var scratchCanvas = this.cachedCanvases.getCanvas(
  7707. cacheId, drawnWidth, drawnHeight, true);
  7708. var groupCtx = scratchCanvas.context;
  7709. // Since we created a new canvas that is just the size of the bounding box
  7710. // we have to translate the group ctx.
  7711. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7712. groupCtx.translate(-offsetX, -offsetY);
  7713. groupCtx.transform.apply(groupCtx, currentTransform);
  7714. if (group.smask) {
  7715. // Saving state and cached mask to be used in setGState.
  7716. this.smaskStack.push({
  7717. canvas: scratchCanvas.canvas,
  7718. context: groupCtx,
  7719. offsetX: offsetX,
  7720. offsetY: offsetY,
  7721. scaleX: scaleX,
  7722. scaleY: scaleY,
  7723. subtype: group.smask.subtype,
  7724. backdrop: group.smask.backdrop,
  7725. transferMap: group.smask.transferMap || null,
  7726. startTransformInverse: null, // used during suspend operation
  7727. });
  7728. } else {
  7729. // Setup the current ctx so when the group is popped we draw it at the
  7730. // right location.
  7731. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7732. currentCtx.translate(offsetX, offsetY);
  7733. currentCtx.scale(scaleX, scaleY);
  7734. }
  7735. // The transparency group inherits all off the current graphics state
  7736. // except the blend mode, soft mask, and alpha constants.
  7737. copyCtxState(currentCtx, groupCtx);
  7738. this.ctx = groupCtx;
  7739. this.setGState([
  7740. ['BM', 'Normal'],
  7741. ['ca', 1],
  7742. ['CA', 1]
  7743. ]);
  7744. this.groupStack.push(currentCtx);
  7745. this.groupLevel++;
  7746. // Reseting mask state, masks will be applied on restore of the group.
  7747. this.current.activeSMask = null;
  7748. },
  7749. endGroup: function CanvasGraphics_endGroup(group) {
  7750. this.groupLevel--;
  7751. var groupCtx = this.ctx;
  7752. this.ctx = this.groupStack.pop();
  7753. // Turn off image smoothing to avoid sub pixel interpolation which can
  7754. // look kind of blurry for some pdfs.
  7755. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7756. this.ctx.imageSmoothingEnabled = false;
  7757. } else {
  7758. this.ctx.mozImageSmoothingEnabled = false;
  7759. }
  7760. if (group.smask) {
  7761. this.tempSMask = this.smaskStack.pop();
  7762. } else {
  7763. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7764. }
  7765. this.restore();
  7766. },
  7767. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7768. this.save();
  7769. this.current = new CanvasExtraState();
  7770. if (this.baseTransform) {
  7771. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7772. }
  7773. },
  7774. endAnnotations: function CanvasGraphics_endAnnotations() {
  7775. this.restore();
  7776. },
  7777. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  7778. matrix) {
  7779. this.save();
  7780. if (isArray(rect) && 4 === rect.length) {
  7781. var width = rect[2] - rect[0];
  7782. var height = rect[3] - rect[1];
  7783. this.ctx.rect(rect[0], rect[1], width, height);
  7784. this.clip();
  7785. this.endPath();
  7786. }
  7787. this.transform.apply(this, transform);
  7788. this.transform.apply(this, matrix);
  7789. },
  7790. endAnnotation: function CanvasGraphics_endAnnotation() {
  7791. this.restore();
  7792. },
  7793. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7794. var domImage = this.objs.get(objId);
  7795. if (!domImage) {
  7796. warn('Dependent image isn\'t ready yet');
  7797. return;
  7798. }
  7799. this.save();
  7800. var ctx = this.ctx;
  7801. // scale the image to the unit square
  7802. ctx.scale(1 / w, -1 / h);
  7803. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7804. 0, -h, w, h);
  7805. if (this.imageLayer) {
  7806. var currentTransform = ctx.mozCurrentTransformInverse;
  7807. var position = this.getCanvasPosition(0, 0);
  7808. this.imageLayer.appendImage({
  7809. objId: objId,
  7810. left: position[0],
  7811. top: position[1],
  7812. width: w / currentTransform[0],
  7813. height: h / currentTransform[3]
  7814. });
  7815. }
  7816. this.restore();
  7817. },
  7818. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7819. var ctx = this.ctx;
  7820. var width = img.width, height = img.height;
  7821. var fillColor = this.current.fillColor;
  7822. var isPatternFill = this.current.patternFill;
  7823. var glyph = this.processingType3;
  7824. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7825. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7826. glyph.compiled =
  7827. compileType3Glyph({data: img.data, width: width, height: height});
  7828. } else {
  7829. glyph.compiled = null;
  7830. }
  7831. }
  7832. if (glyph && glyph.compiled) {
  7833. glyph.compiled(ctx);
  7834. return;
  7835. }
  7836. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7837. width, height);
  7838. var maskCtx = maskCanvas.context;
  7839. maskCtx.save();
  7840. putBinaryImageMask(maskCtx, img);
  7841. maskCtx.globalCompositeOperation = 'source-in';
  7842. maskCtx.fillStyle = isPatternFill ?
  7843. fillColor.getPattern(maskCtx, this) : fillColor;
  7844. maskCtx.fillRect(0, 0, width, height);
  7845. maskCtx.restore();
  7846. this.paintInlineImageXObject(maskCanvas.canvas);
  7847. },
  7848. paintImageMaskXObjectRepeat:
  7849. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7850. scaleY, positions) {
  7851. var width = imgData.width;
  7852. var height = imgData.height;
  7853. var fillColor = this.current.fillColor;
  7854. var isPatternFill = this.current.patternFill;
  7855. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7856. width, height);
  7857. var maskCtx = maskCanvas.context;
  7858. maskCtx.save();
  7859. putBinaryImageMask(maskCtx, imgData);
  7860. maskCtx.globalCompositeOperation = 'source-in';
  7861. maskCtx.fillStyle = isPatternFill ?
  7862. fillColor.getPattern(maskCtx, this) : fillColor;
  7863. maskCtx.fillRect(0, 0, width, height);
  7864. maskCtx.restore();
  7865. var ctx = this.ctx;
  7866. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7867. ctx.save();
  7868. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7869. ctx.scale(1, -1);
  7870. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7871. 0, -1, 1, 1);
  7872. ctx.restore();
  7873. }
  7874. },
  7875. paintImageMaskXObjectGroup:
  7876. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7877. var ctx = this.ctx;
  7878. var fillColor = this.current.fillColor;
  7879. var isPatternFill = this.current.patternFill;
  7880. for (var i = 0, ii = images.length; i < ii; i++) {
  7881. var image = images[i];
  7882. var width = image.width, height = image.height;
  7883. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7884. width, height);
  7885. var maskCtx = maskCanvas.context;
  7886. maskCtx.save();
  7887. putBinaryImageMask(maskCtx, image);
  7888. maskCtx.globalCompositeOperation = 'source-in';
  7889. maskCtx.fillStyle = isPatternFill ?
  7890. fillColor.getPattern(maskCtx, this) : fillColor;
  7891. maskCtx.fillRect(0, 0, width, height);
  7892. maskCtx.restore();
  7893. ctx.save();
  7894. ctx.transform.apply(ctx, image.transform);
  7895. ctx.scale(1, -1);
  7896. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7897. 0, -1, 1, 1);
  7898. ctx.restore();
  7899. }
  7900. },
  7901. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7902. var imgData = this.objs.get(objId);
  7903. if (!imgData) {
  7904. warn('Dependent image isn\'t ready yet');
  7905. return;
  7906. }
  7907. this.paintInlineImageXObject(imgData);
  7908. },
  7909. paintImageXObjectRepeat:
  7910. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7911. positions) {
  7912. var imgData = this.objs.get(objId);
  7913. if (!imgData) {
  7914. warn('Dependent image isn\'t ready yet');
  7915. return;
  7916. }
  7917. var width = imgData.width;
  7918. var height = imgData.height;
  7919. var map = [];
  7920. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7921. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7922. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7923. }
  7924. this.paintInlineImageXObjectGroup(imgData, map);
  7925. },
  7926. paintInlineImageXObject:
  7927. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7928. var width = imgData.width;
  7929. var height = imgData.height;
  7930. var ctx = this.ctx;
  7931. this.save();
  7932. // scale the image to the unit square
  7933. ctx.scale(1 / width, -1 / height);
  7934. var currentTransform = ctx.mozCurrentTransformInverse;
  7935. var a = currentTransform[0], b = currentTransform[1];
  7936. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7937. var c = currentTransform[2], d = currentTransform[3];
  7938. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7939. var imgToPaint, tmpCanvas;
  7940. // instanceof HTMLElement does not work in jsdom node.js module
  7941. if (imgData instanceof HTMLElement || !imgData.data) {
  7942. imgToPaint = imgData;
  7943. } else {
  7944. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7945. width, height);
  7946. var tmpCtx = tmpCanvas.context;
  7947. putBinaryImageData(tmpCtx, imgData);
  7948. imgToPaint = tmpCanvas.canvas;
  7949. }
  7950. var paintWidth = width, paintHeight = height;
  7951. var tmpCanvasId = 'prescale1';
  7952. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7953. // pixels during drawImage operation, painting on the temporary canvas(es)
  7954. // that are twice smaller in size
  7955. while ((widthScale > 2 && paintWidth > 1) ||
  7956. (heightScale > 2 && paintHeight > 1)) {
  7957. var newWidth = paintWidth, newHeight = paintHeight;
  7958. if (widthScale > 2 && paintWidth > 1) {
  7959. newWidth = Math.ceil(paintWidth / 2);
  7960. widthScale /= paintWidth / newWidth;
  7961. }
  7962. if (heightScale > 2 && paintHeight > 1) {
  7963. newHeight = Math.ceil(paintHeight / 2);
  7964. heightScale /= paintHeight / newHeight;
  7965. }
  7966. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7967. newWidth, newHeight);
  7968. tmpCtx = tmpCanvas.context;
  7969. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7970. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7971. 0, 0, newWidth, newHeight);
  7972. imgToPaint = tmpCanvas.canvas;
  7973. paintWidth = newWidth;
  7974. paintHeight = newHeight;
  7975. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7976. }
  7977. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7978. 0, -height, width, height);
  7979. if (this.imageLayer) {
  7980. var position = this.getCanvasPosition(0, -height);
  7981. this.imageLayer.appendImage({
  7982. imgData: imgData,
  7983. left: position[0],
  7984. top: position[1],
  7985. width: width / currentTransform[0],
  7986. height: height / currentTransform[3]
  7987. });
  7988. }
  7989. this.restore();
  7990. },
  7991. paintInlineImageXObjectGroup:
  7992. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7993. var ctx = this.ctx;
  7994. var w = imgData.width;
  7995. var h = imgData.height;
  7996. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7997. var tmpCtx = tmpCanvas.context;
  7998. putBinaryImageData(tmpCtx, imgData);
  7999. for (var i = 0, ii = map.length; i < ii; i++) {
  8000. var entry = map[i];
  8001. ctx.save();
  8002. ctx.transform.apply(ctx, entry.transform);
  8003. ctx.scale(1, -1);
  8004. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  8005. 0, -1, 1, 1);
  8006. if (this.imageLayer) {
  8007. var position = this.getCanvasPosition(entry.x, entry.y);
  8008. this.imageLayer.appendImage({
  8009. imgData: imgData,
  8010. left: position[0],
  8011. top: position[1],
  8012. width: w,
  8013. height: h
  8014. });
  8015. }
  8016. ctx.restore();
  8017. }
  8018. },
  8019. paintSolidColorImageMask:
  8020. function CanvasGraphics_paintSolidColorImageMask() {
  8021. this.ctx.fillRect(0, 0, 1, 1);
  8022. },
  8023. paintXObject: function CanvasGraphics_paintXObject() {
  8024. warn('Unsupported \'paintXObject\' command.');
  8025. },
  8026. // Marked content
  8027. markPoint: function CanvasGraphics_markPoint(tag) {
  8028. // TODO Marked content.
  8029. },
  8030. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8031. // TODO Marked content.
  8032. },
  8033. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8034. // TODO Marked content.
  8035. },
  8036. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  8037. tag, properties) {
  8038. // TODO Marked content.
  8039. },
  8040. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8041. // TODO Marked content.
  8042. },
  8043. // Compatibility
  8044. beginCompat: function CanvasGraphics_beginCompat() {
  8045. // TODO ignore undefined operators (should we do that anyway?)
  8046. },
  8047. endCompat: function CanvasGraphics_endCompat() {
  8048. // TODO stop ignoring undefined operators
  8049. },
  8050. // Helper functions
  8051. consumePath: function CanvasGraphics_consumePath() {
  8052. var ctx = this.ctx;
  8053. if (this.pendingClip) {
  8054. if (this.pendingClip === EO_CLIP) {
  8055. if (ctx.mozFillRule !== undefined) {
  8056. ctx.mozFillRule = 'evenodd';
  8057. ctx.clip();
  8058. ctx.mozFillRule = 'nonzero';
  8059. } else {
  8060. ctx.clip('evenodd');
  8061. }
  8062. } else {
  8063. ctx.clip();
  8064. }
  8065. this.pendingClip = null;
  8066. }
  8067. ctx.beginPath();
  8068. },
  8069. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8070. if (this.cachedGetSinglePixelWidth === null) {
  8071. // NOTE: The `save` and `restore` commands used below is a workaround
  8072. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8073. // from intermittently returning incorrect values in Firefox, see:
  8074. // https://github.com/mozilla/pdf.js/issues/7188.
  8075. this.ctx.save();
  8076. var inverse = this.ctx.mozCurrentTransformInverse;
  8077. this.ctx.restore();
  8078. // max of the current horizontal and vertical scale
  8079. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  8080. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  8081. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  8082. }
  8083. return this.cachedGetSinglePixelWidth;
  8084. },
  8085. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8086. var transform = this.ctx.mozCurrentTransform;
  8087. return [
  8088. transform[0] * x + transform[2] * y + transform[4],
  8089. transform[1] * x + transform[3] * y + transform[5]
  8090. ];
  8091. }
  8092. };
  8093. for (var op in OPS) {
  8094. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8095. }
  8096. return CanvasGraphics;
  8097. })();
  8098. exports.CanvasGraphics = CanvasGraphics;
  8099. exports.createScratchCanvas = createScratchCanvas;
  8100. }));
  8101. (function (root, factory) {
  8102. {
  8103. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  8104. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  8105. root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8106. }
  8107. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  8108. displayMetadata, displayDOMUtils, amdRequire) {
  8109. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8110. var MessageHandler = sharedUtil.MessageHandler;
  8111. var MissingPDFException = sharedUtil.MissingPDFException;
  8112. var PageViewport = sharedUtil.PageViewport;
  8113. var PasswordResponses = sharedUtil.PasswordResponses;
  8114. var PasswordException = sharedUtil.PasswordException;
  8115. var StatTimer = sharedUtil.StatTimer;
  8116. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8117. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8118. var Util = sharedUtil.Util;
  8119. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8120. var error = sharedUtil.error;
  8121. var deprecated = sharedUtil.deprecated;
  8122. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8123. var info = sharedUtil.info;
  8124. var isInt = sharedUtil.isInt;
  8125. var isArray = sharedUtil.isArray;
  8126. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8127. var isSameOrigin = sharedUtil.isSameOrigin;
  8128. var loadJpegStream = sharedUtil.loadJpegStream;
  8129. var stringToBytes = sharedUtil.stringToBytes;
  8130. var globalScope = sharedUtil.globalScope;
  8131. var warn = sharedUtil.warn;
  8132. var FontFaceObject = displayFontLoader.FontFaceObject;
  8133. var FontLoader = displayFontLoader.FontLoader;
  8134. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8135. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8136. var Metadata = displayMetadata.Metadata;
  8137. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8138. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  8139. var isWorkerDisabled = false;
  8140. var workerSrc;
  8141. var isPostMessageTransfersDisabled = false;
  8142. var useRequireEnsure = false;
  8143. if (typeof window === 'undefined') {
  8144. // node.js - disable worker and set require.ensure.
  8145. isWorkerDisabled = true;
  8146. if (typeof require.ensure === 'undefined') {
  8147. require.ensure = require('node-ensure');
  8148. }
  8149. useRequireEnsure = true;
  8150. }
  8151. if (typeof __webpack_require__ !== 'undefined') {
  8152. useRequireEnsure = true;
  8153. }
  8154. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8155. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8156. }
  8157. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8158. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  8159. require.ensure([], function () {
  8160. var worker = require('./pdf.worker.js');
  8161. callback(worker.WorkerMessageHandler);
  8162. });
  8163. }) : dynamicLoaderSupported ? (function (callback) {
  8164. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8165. callback(worker.WorkerMessageHandler);
  8166. });
  8167. }) : null;
  8168. /**
  8169. * Document initialization / loading parameters object.
  8170. *
  8171. * @typedef {Object} DocumentInitParameters
  8172. * @property {string} url - The URL of the PDF.
  8173. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8174. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8175. * use atob() to convert it to a binary string first.
  8176. * @property {Object} httpHeaders - Basic authentication headers.
  8177. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8178. * Access-Control requests should be made using credentials such as cookies
  8179. * or authorization headers. The default is false.
  8180. * @property {string} password - For decrypting password-protected PDFs.
  8181. * @property {TypedArray} initialData - A typed array with the first portion or
  8182. * all of the pdf data. Used by the extension since some data is already
  8183. * loaded before the switch to range requests.
  8184. * @property {number} length - The PDF file length. It's used for progress
  8185. * reports and range requests operations.
  8186. * @property {PDFDataRangeTransport} range
  8187. * @property {number} rangeChunkSize - Optional parameter to specify
  8188. * maximum number of bytes fetched per range request. The default value is
  8189. * 2^16 = 65536.
  8190. * @property {PDFWorker} worker - The worker that will be used for the loading
  8191. * and parsing of the PDF data.
  8192. */
  8193. /**
  8194. * @typedef {Object} PDFDocumentStats
  8195. * @property {Array} streamTypes - Used stream types in the document (an item
  8196. * is set to true if specific stream ID was used in the document).
  8197. * @property {Array} fontTypes - Used font type in the document (an item is set
  8198. * to true if specific font ID was used in the document).
  8199. */
  8200. /**
  8201. * This is the main entry point for loading a PDF and interacting with it.
  8202. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8203. * is used, which means it must follow the same origin rules that any XHR does
  8204. * e.g. No cross domain requests without CORS.
  8205. *
  8206. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8207. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8208. * already populated with data or parameter object.
  8209. *
  8210. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8211. * if you want to manually serve range requests for data in the PDF.
  8212. *
  8213. * @param {function} passwordCallback (deprecated) It is used to request a
  8214. * password if wrong or no password was provided. The callback receives two
  8215. * parameters: function that needs to be called with new password and reason
  8216. * (see {PasswordResponses}).
  8217. *
  8218. * @param {function} progressCallback (deprecated) It is used to be able to
  8219. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8220. * a loading bar). The callback receives an {Object} with the properties:
  8221. * {number} loaded and {number} total.
  8222. *
  8223. * @return {PDFDocumentLoadingTask}
  8224. */
  8225. function getDocument(src, pdfDataRangeTransport,
  8226. passwordCallback, progressCallback) {
  8227. var task = new PDFDocumentLoadingTask();
  8228. // Support of the obsolete arguments (for compatibility with API v1.0)
  8229. if (arguments.length > 1) {
  8230. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  8231. 'passwordCallback or progressCallback argument');
  8232. }
  8233. if (pdfDataRangeTransport) {
  8234. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8235. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8236. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8237. pdfDataRangeTransport.length = src.length;
  8238. pdfDataRangeTransport.initialData = src.initialData;
  8239. if (!pdfDataRangeTransport.abort) {
  8240. pdfDataRangeTransport.abort = function () {};
  8241. }
  8242. }
  8243. src = Object.create(src);
  8244. src.range = pdfDataRangeTransport;
  8245. }
  8246. task.onPassword = passwordCallback || null;
  8247. task.onProgress = progressCallback || null;
  8248. var source;
  8249. if (typeof src === 'string') {
  8250. source = { url: src };
  8251. } else if (isArrayBuffer(src)) {
  8252. source = { data: src };
  8253. } else if (src instanceof PDFDataRangeTransport) {
  8254. source = { range: src };
  8255. } else {
  8256. if (typeof src !== 'object') {
  8257. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  8258. 'string or a parameter object');
  8259. }
  8260. if (!src.url && !src.data && !src.range) {
  8261. error('Invalid parameter object: need either .data, .range or .url');
  8262. }
  8263. source = src;
  8264. }
  8265. var params = {};
  8266. var rangeTransport = null;
  8267. var worker = null;
  8268. for (var key in source) {
  8269. if (key === 'url' && typeof window !== 'undefined') {
  8270. // The full path is required in the 'url' field.
  8271. params[key] = new URL(source[key], window.location).href;
  8272. continue;
  8273. } else if (key === 'range') {
  8274. rangeTransport = source[key];
  8275. continue;
  8276. } else if (key === 'worker') {
  8277. worker = source[key];
  8278. continue;
  8279. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8280. // Converting string or array-like data to Uint8Array.
  8281. var pdfBytes = source[key];
  8282. if (typeof pdfBytes === 'string') {
  8283. params[key] = stringToBytes(pdfBytes);
  8284. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  8285. !isNaN(pdfBytes.length)) {
  8286. params[key] = new Uint8Array(pdfBytes);
  8287. } else if (isArrayBuffer(pdfBytes)) {
  8288. params[key] = new Uint8Array(pdfBytes);
  8289. } else {
  8290. error('Invalid PDF binary data: either typed array, string or ' +
  8291. 'array-like object is expected in the data property.');
  8292. }
  8293. continue;
  8294. }
  8295. params[key] = source[key];
  8296. }
  8297. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8298. if (!worker) {
  8299. // Worker was not provided -- creating and owning our own.
  8300. worker = new PDFWorker();
  8301. task._worker = worker;
  8302. }
  8303. var docId = task.docId;
  8304. worker.promise.then(function () {
  8305. if (task.destroyed) {
  8306. throw new Error('Loading aborted');
  8307. }
  8308. return _fetchDocument(worker, params, rangeTransport, docId).then(
  8309. function (workerId) {
  8310. if (task.destroyed) {
  8311. throw new Error('Loading aborted');
  8312. }
  8313. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8314. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8315. task._transport = transport;
  8316. messageHandler.send('Ready', null);
  8317. });
  8318. }).catch(task._capability.reject);
  8319. return task;
  8320. }
  8321. /**
  8322. * Starts fetching of specified PDF document/data.
  8323. * @param {PDFWorker} worker
  8324. * @param {Object} source
  8325. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8326. * @param {string} docId Unique document id, used as MessageHandler id.
  8327. * @returns {Promise} The promise, which is resolved when worker id of
  8328. * MessageHandler is known.
  8329. * @private
  8330. */
  8331. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8332. if (worker.destroyed) {
  8333. return Promise.reject(new Error('Worker was destroyed'));
  8334. }
  8335. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8336. source.disableStream = getDefaultSetting('disableStream');
  8337. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8338. if (pdfDataRangeTransport) {
  8339. source.length = pdfDataRangeTransport.length;
  8340. source.initialData = pdfDataRangeTransport.initialData;
  8341. }
  8342. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8343. docId: docId,
  8344. source: source,
  8345. disableRange: getDefaultSetting('disableRange'),
  8346. maxImageSize: getDefaultSetting('maxImageSize'),
  8347. cMapUrl: getDefaultSetting('cMapUrl'),
  8348. cMapPacked: getDefaultSetting('cMapPacked'),
  8349. disableFontFace: getDefaultSetting('disableFontFace'),
  8350. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8351. postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
  8352. !isPostMessageTransfersDisabled,
  8353. }).then(function (workerId) {
  8354. if (worker.destroyed) {
  8355. throw new Error('Worker was destroyed');
  8356. }
  8357. return workerId;
  8358. });
  8359. }
  8360. /**
  8361. * PDF document loading operation.
  8362. * @class
  8363. * @alias PDFDocumentLoadingTask
  8364. */
  8365. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  8366. var nextDocumentId = 0;
  8367. /** @constructs PDFDocumentLoadingTask */
  8368. function PDFDocumentLoadingTask() {
  8369. this._capability = createPromiseCapability();
  8370. this._transport = null;
  8371. this._worker = null;
  8372. /**
  8373. * Unique document loading task id -- used in MessageHandlers.
  8374. * @type {string}
  8375. */
  8376. this.docId = 'd' + (nextDocumentId++);
  8377. /**
  8378. * Shows if loading task is destroyed.
  8379. * @type {boolean}
  8380. */
  8381. this.destroyed = false;
  8382. /**
  8383. * Callback to request a password if wrong or no password was provided.
  8384. * The callback receives two parameters: function that needs to be called
  8385. * with new password and reason (see {PasswordResponses}).
  8386. */
  8387. this.onPassword = null;
  8388. /**
  8389. * Callback to be able to monitor the loading progress of the PDF file
  8390. * (necessary to implement e.g. a loading bar). The callback receives
  8391. * an {Object} with the properties: {number} loaded and {number} total.
  8392. */
  8393. this.onProgress = null;
  8394. /**
  8395. * Callback to when unsupported feature is used. The callback receives
  8396. * an {UNSUPPORTED_FEATURES} argument.
  8397. */
  8398. this.onUnsupportedFeature = null;
  8399. }
  8400. PDFDocumentLoadingTask.prototype =
  8401. /** @lends PDFDocumentLoadingTask.prototype */ {
  8402. /**
  8403. * @return {Promise}
  8404. */
  8405. get promise() {
  8406. return this._capability.promise;
  8407. },
  8408. /**
  8409. * Aborts all network requests and destroys worker.
  8410. * @return {Promise} A promise that is resolved after destruction activity
  8411. * is completed.
  8412. */
  8413. destroy: function () {
  8414. this.destroyed = true;
  8415. var transportDestroyed = !this._transport ? Promise.resolve() :
  8416. this._transport.destroy();
  8417. return transportDestroyed.then(function () {
  8418. this._transport = null;
  8419. if (this._worker) {
  8420. this._worker.destroy();
  8421. this._worker = null;
  8422. }
  8423. }.bind(this));
  8424. },
  8425. /**
  8426. * Registers callbacks to indicate the document loading completion.
  8427. *
  8428. * @param {function} onFulfilled The callback for the loading completion.
  8429. * @param {function} onRejected The callback for the loading failure.
  8430. * @return {Promise} A promise that is resolved after the onFulfilled or
  8431. * onRejected callback.
  8432. */
  8433. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8434. return this.promise.then.apply(this.promise, arguments);
  8435. }
  8436. };
  8437. return PDFDocumentLoadingTask;
  8438. })();
  8439. /**
  8440. * Abstract class to support range requests file loading.
  8441. * @class
  8442. * @alias PDFDataRangeTransport
  8443. * @param {number} length
  8444. * @param {Uint8Array} initialData
  8445. */
  8446. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  8447. function PDFDataRangeTransport(length, initialData) {
  8448. this.length = length;
  8449. this.initialData = initialData;
  8450. this._rangeListeners = [];
  8451. this._progressListeners = [];
  8452. this._progressiveReadListeners = [];
  8453. this._readyCapability = createPromiseCapability();
  8454. }
  8455. PDFDataRangeTransport.prototype =
  8456. /** @lends PDFDataRangeTransport.prototype */ {
  8457. addRangeListener:
  8458. function PDFDataRangeTransport_addRangeListener(listener) {
  8459. this._rangeListeners.push(listener);
  8460. },
  8461. addProgressListener:
  8462. function PDFDataRangeTransport_addProgressListener(listener) {
  8463. this._progressListeners.push(listener);
  8464. },
  8465. addProgressiveReadListener:
  8466. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8467. this._progressiveReadListeners.push(listener);
  8468. },
  8469. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8470. var listeners = this._rangeListeners;
  8471. for (var i = 0, n = listeners.length; i < n; ++i) {
  8472. listeners[i](begin, chunk);
  8473. }
  8474. },
  8475. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8476. this._readyCapability.promise.then(function () {
  8477. var listeners = this._progressListeners;
  8478. for (var i = 0, n = listeners.length; i < n; ++i) {
  8479. listeners[i](loaded);
  8480. }
  8481. }.bind(this));
  8482. },
  8483. onDataProgressiveRead:
  8484. function PDFDataRangeTransport_onDataProgress(chunk) {
  8485. this._readyCapability.promise.then(function () {
  8486. var listeners = this._progressiveReadListeners;
  8487. for (var i = 0, n = listeners.length; i < n; ++i) {
  8488. listeners[i](chunk);
  8489. }
  8490. }.bind(this));
  8491. },
  8492. transportReady: function PDFDataRangeTransport_transportReady() {
  8493. this._readyCapability.resolve();
  8494. },
  8495. requestDataRange:
  8496. function PDFDataRangeTransport_requestDataRange(begin, end) {
  8497. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8498. },
  8499. abort: function PDFDataRangeTransport_abort() {
  8500. }
  8501. };
  8502. return PDFDataRangeTransport;
  8503. })();
  8504. /**
  8505. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8506. * properties that can be read synchronously.
  8507. * @class
  8508. * @alias PDFDocumentProxy
  8509. */
  8510. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  8511. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8512. this.pdfInfo = pdfInfo;
  8513. this.transport = transport;
  8514. this.loadingTask = loadingTask;
  8515. }
  8516. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  8517. /**
  8518. * @return {number} Total number of pages the PDF contains.
  8519. */
  8520. get numPages() {
  8521. return this.pdfInfo.numPages;
  8522. },
  8523. /**
  8524. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8525. * unique.
  8526. */
  8527. get fingerprint() {
  8528. return this.pdfInfo.fingerprint;
  8529. },
  8530. /**
  8531. * @param {number} pageNumber The page number to get. The first page is 1.
  8532. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8533. * object.
  8534. */
  8535. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8536. return this.transport.getPage(pageNumber);
  8537. },
  8538. /**
  8539. * @param {{num: number, gen: number}} ref The page reference. Must have
  8540. * the 'num' and 'gen' properties.
  8541. * @return {Promise} A promise that is resolved with the page index that is
  8542. * associated with the reference.
  8543. */
  8544. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8545. return this.transport.getPageIndex(ref);
  8546. },
  8547. /**
  8548. * @return {Promise} A promise that is resolved with a lookup table for
  8549. * mapping named destinations to reference numbers.
  8550. *
  8551. * This can be slow for large documents: use getDestination instead
  8552. */
  8553. getDestinations: function PDFDocumentProxy_getDestinations() {
  8554. return this.transport.getDestinations();
  8555. },
  8556. /**
  8557. * @param {string} id The named destination to get.
  8558. * @return {Promise} A promise that is resolved with all information
  8559. * of the given named destination.
  8560. */
  8561. getDestination: function PDFDocumentProxy_getDestination(id) {
  8562. return this.transport.getDestination(id);
  8563. },
  8564. /**
  8565. * @return {Promise} A promise that is resolved with:
  8566. * an Array containing the pageLabels that correspond to the pageIndexes,
  8567. * or `null` when no pageLabels are present in the PDF file.
  8568. */
  8569. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8570. return this.transport.getPageLabels();
  8571. },
  8572. /**
  8573. * @return {Promise} A promise that is resolved with a lookup table for
  8574. * mapping named attachments to their content.
  8575. */
  8576. getAttachments: function PDFDocumentProxy_getAttachments() {
  8577. return this.transport.getAttachments();
  8578. },
  8579. /**
  8580. * @return {Promise} A promise that is resolved with an array of all the
  8581. * JavaScript strings in the name tree.
  8582. */
  8583. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8584. return this.transport.getJavaScript();
  8585. },
  8586. /**
  8587. * @return {Promise} A promise that is resolved with an {Array} that is a
  8588. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8589. * [
  8590. * {
  8591. * title: string,
  8592. * bold: boolean,
  8593. * italic: boolean,
  8594. * color: rgb Uint8Array,
  8595. * dest: dest obj,
  8596. * url: string,
  8597. * items: array of more items like this
  8598. * },
  8599. * ...
  8600. * ].
  8601. */
  8602. getOutline: function PDFDocumentProxy_getOutline() {
  8603. return this.transport.getOutline();
  8604. },
  8605. /**
  8606. * @return {Promise} A promise that is resolved with an {Object} that has
  8607. * info and metadata properties. Info is an {Object} filled with anything
  8608. * available in the information dictionary and similarly metadata is a
  8609. * {Metadata} object with information from the metadata section of the PDF.
  8610. */
  8611. getMetadata: function PDFDocumentProxy_getMetadata() {
  8612. return this.transport.getMetadata();
  8613. },
  8614. /**
  8615. * @return {Promise} A promise that is resolved with a TypedArray that has
  8616. * the raw data from the PDF.
  8617. */
  8618. getData: function PDFDocumentProxy_getData() {
  8619. return this.transport.getData();
  8620. },
  8621. /**
  8622. * @return {Promise} A promise that is resolved when the document's data
  8623. * is loaded. It is resolved with an {Object} that contains the length
  8624. * property that indicates size of the PDF data in bytes.
  8625. */
  8626. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8627. return this.transport.downloadInfoCapability.promise;
  8628. },
  8629. /**
  8630. * @return {Promise} A promise this is resolved with current stats about
  8631. * document structures (see {@link PDFDocumentStats}).
  8632. */
  8633. getStats: function PDFDocumentProxy_getStats() {
  8634. return this.transport.getStats();
  8635. },
  8636. /**
  8637. * Cleans up resources allocated by the document, e.g. created @font-face.
  8638. */
  8639. cleanup: function PDFDocumentProxy_cleanup() {
  8640. this.transport.startCleanup();
  8641. },
  8642. /**
  8643. * Destroys current document instance and terminates worker.
  8644. */
  8645. destroy: function PDFDocumentProxy_destroy() {
  8646. return this.loadingTask.destroy();
  8647. }
  8648. };
  8649. return PDFDocumentProxy;
  8650. })();
  8651. /**
  8652. * Page getTextContent parameters.
  8653. *
  8654. * @typedef {Object} getTextContentParameters
  8655. * @param {boolean} normalizeWhitespace - replaces all occurrences of
  8656. * whitespace with standard spaces (0x20). The default value is `false`.
  8657. * @param {boolean} disableCombineTextItems - do not attempt to combine
  8658. * same line {@link TextItem}'s. The default value is `false`.
  8659. */
  8660. /**
  8661. * Page text content.
  8662. *
  8663. * @typedef {Object} TextContent
  8664. * @property {array} items - array of {@link TextItem}
  8665. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  8666. * name.
  8667. */
  8668. /**
  8669. * Page text content part.
  8670. *
  8671. * @typedef {Object} TextItem
  8672. * @property {string} str - text content.
  8673. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8674. * @property {array} transform - transformation matrix.
  8675. * @property {number} width - width in device space.
  8676. * @property {number} height - height in device space.
  8677. * @property {string} fontName - font name used by pdf.js for converted font.
  8678. */
  8679. /**
  8680. * Text style.
  8681. *
  8682. * @typedef {Object} TextStyle
  8683. * @property {number} ascent - font ascent.
  8684. * @property {number} descent - font descent.
  8685. * @property {boolean} vertical - text is in vertical mode.
  8686. * @property {string} fontFamily - possible font family
  8687. */
  8688. /**
  8689. * Page annotation parameters.
  8690. *
  8691. * @typedef {Object} GetAnnotationsParameters
  8692. * @param {string} intent - Determines the annotations that will be fetched,
  8693. * can be either 'display' (viewable annotations) or 'print'
  8694. * (printable annotations).
  8695. * If the parameter is omitted, all annotations are fetched.
  8696. */
  8697. /**
  8698. * Page render parameters.
  8699. *
  8700. * @typedef {Object} RenderParameters
  8701. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  8702. * @property {PageViewport} viewport - Rendering viewport obtained by
  8703. * calling of PDFPage.getViewport method.
  8704. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  8705. * (default value is 'display').
  8706. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  8707. * interactive form elements are rendered in the display
  8708. * layer. If so, we do not render them on canvas as well.
  8709. * @property {Array} transform - (optional) Additional transform, applied
  8710. * just before viewport transform.
  8711. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  8712. * endLayout and appendImage functions.
  8713. * @property {function} continueCallback - (deprecated) A function that will be
  8714. * called each time the rendering is paused. To continue
  8715. * rendering call the function that is the first argument
  8716. * to the callback.
  8717. */
  8718. /**
  8719. * PDF page operator list.
  8720. *
  8721. * @typedef {Object} PDFOperatorList
  8722. * @property {Array} fnArray - Array containing the operator functions.
  8723. * @property {Array} argsArray - Array containing the arguments of the
  8724. * functions.
  8725. */
  8726. /**
  8727. * Proxy to a PDFPage in the worker thread.
  8728. * @class
  8729. * @alias PDFPageProxy
  8730. */
  8731. var PDFPageProxy = (function PDFPageProxyClosure() {
  8732. function PDFPageProxy(pageIndex, pageInfo, transport) {
  8733. this.pageIndex = pageIndex;
  8734. this.pageInfo = pageInfo;
  8735. this.transport = transport;
  8736. this.stats = new StatTimer();
  8737. this.stats.enabled = getDefaultSetting('enableStats');
  8738. this.commonObjs = transport.commonObjs;
  8739. this.objs = new PDFObjects();
  8740. this.cleanupAfterRender = false;
  8741. this.pendingCleanup = false;
  8742. this.intentStates = Object.create(null);
  8743. this.destroyed = false;
  8744. }
  8745. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  8746. /**
  8747. * @return {number} Page number of the page. First page is 1.
  8748. */
  8749. get pageNumber() {
  8750. return this.pageIndex + 1;
  8751. },
  8752. /**
  8753. * @return {number} The number of degrees the page is rotated clockwise.
  8754. */
  8755. get rotate() {
  8756. return this.pageInfo.rotate;
  8757. },
  8758. /**
  8759. * @return {Object} The reference that points to this page. It has 'num' and
  8760. * 'gen' properties.
  8761. */
  8762. get ref() {
  8763. return this.pageInfo.ref;
  8764. },
  8765. /**
  8766. * @return {Array} An array of the visible portion of the PDF page in the
  8767. * user space units - [x1, y1, x2, y2].
  8768. */
  8769. get view() {
  8770. return this.pageInfo.view;
  8771. },
  8772. /**
  8773. * @param {number} scale The desired scale of the viewport.
  8774. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  8775. * defaults to the page rotation.
  8776. * @return {PageViewport} Contains 'width' and 'height' properties
  8777. * along with transforms required for rendering.
  8778. */
  8779. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  8780. if (arguments.length < 2) {
  8781. rotate = this.rotate;
  8782. }
  8783. return new PageViewport(this.view, scale, rotate, 0, 0);
  8784. },
  8785. /**
  8786. * @param {GetAnnotationsParameters} params - Annotation parameters.
  8787. * @return {Promise} A promise that is resolved with an {Array} of the
  8788. * annotation objects.
  8789. */
  8790. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  8791. var intent = (params && params.intent) || null;
  8792. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  8793. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
  8794. intent);
  8795. this.annotationsIntent = intent;
  8796. }
  8797. return this.annotationsPromise;
  8798. },
  8799. /**
  8800. * Begins the process of rendering a page to the desired context.
  8801. * @param {RenderParameters} params Page render parameters.
  8802. * @return {RenderTask} An object that contains the promise, which
  8803. * is resolved when the page finishes rendering.
  8804. */
  8805. render: function PDFPageProxy_render(params) {
  8806. var stats = this.stats;
  8807. stats.time('Overall');
  8808. // If there was a pending destroy cancel it so no cleanup happens during
  8809. // this call to render.
  8810. this.pendingCleanup = false;
  8811. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  8812. var renderInteractiveForms = (params.renderInteractiveForms === true ?
  8813. true : /* Default */ false);
  8814. if (!this.intentStates[renderingIntent]) {
  8815. this.intentStates[renderingIntent] = Object.create(null);
  8816. }
  8817. var intentState = this.intentStates[renderingIntent];
  8818. // If there's no displayReadyCapability yet, then the operatorList
  8819. // was never requested before. Make the request and create the promise.
  8820. if (!intentState.displayReadyCapability) {
  8821. intentState.receivingOperatorList = true;
  8822. intentState.displayReadyCapability = createPromiseCapability();
  8823. intentState.operatorList = {
  8824. fnArray: [],
  8825. argsArray: [],
  8826. lastChunk: false
  8827. };
  8828. this.stats.time('Page Request');
  8829. this.transport.messageHandler.send('RenderPageRequest', {
  8830. pageIndex: this.pageNumber - 1,
  8831. intent: renderingIntent,
  8832. renderInteractiveForms: renderInteractiveForms,
  8833. });
  8834. }
  8835. var internalRenderTask = new InternalRenderTask(complete, params,
  8836. this.objs,
  8837. this.commonObjs,
  8838. intentState.operatorList,
  8839. this.pageNumber);
  8840. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  8841. if (!intentState.renderTasks) {
  8842. intentState.renderTasks = [];
  8843. }
  8844. intentState.renderTasks.push(internalRenderTask);
  8845. var renderTask = internalRenderTask.task;
  8846. // Obsolete parameter support
  8847. if (params.continueCallback) {
  8848. deprecated('render is used with continueCallback parameter');
  8849. renderTask.onContinue = params.continueCallback;
  8850. }
  8851. var self = this;
  8852. intentState.displayReadyCapability.promise.then(
  8853. function pageDisplayReadyPromise(transparency) {
  8854. if (self.pendingCleanup) {
  8855. complete();
  8856. return;
  8857. }
  8858. stats.time('Rendering');
  8859. internalRenderTask.initializeGraphics(transparency);
  8860. internalRenderTask.operatorListChanged();
  8861. },
  8862. function pageDisplayReadPromiseError(reason) {
  8863. complete(reason);
  8864. }
  8865. );
  8866. function complete(error) {
  8867. var i = intentState.renderTasks.indexOf(internalRenderTask);
  8868. if (i >= 0) {
  8869. intentState.renderTasks.splice(i, 1);
  8870. }
  8871. if (self.cleanupAfterRender) {
  8872. self.pendingCleanup = true;
  8873. }
  8874. self._tryCleanup();
  8875. if (error) {
  8876. internalRenderTask.capability.reject(error);
  8877. } else {
  8878. internalRenderTask.capability.resolve();
  8879. }
  8880. stats.timeEnd('Rendering');
  8881. stats.timeEnd('Overall');
  8882. }
  8883. return renderTask;
  8884. },
  8885. /**
  8886. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  8887. * object that represents page's operator list.
  8888. */
  8889. getOperatorList: function PDFPageProxy_getOperatorList() {
  8890. function operatorListChanged() {
  8891. if (intentState.operatorList.lastChunk) {
  8892. intentState.opListReadCapability.resolve(intentState.operatorList);
  8893. var i = intentState.renderTasks.indexOf(opListTask);
  8894. if (i >= 0) {
  8895. intentState.renderTasks.splice(i, 1);
  8896. }
  8897. }
  8898. }
  8899. var renderingIntent = 'oplist';
  8900. if (!this.intentStates[renderingIntent]) {
  8901. this.intentStates[renderingIntent] = Object.create(null);
  8902. }
  8903. var intentState = this.intentStates[renderingIntent];
  8904. var opListTask;
  8905. if (!intentState.opListReadCapability) {
  8906. opListTask = {};
  8907. opListTask.operatorListChanged = operatorListChanged;
  8908. intentState.receivingOperatorList = true;
  8909. intentState.opListReadCapability = createPromiseCapability();
  8910. intentState.renderTasks = [];
  8911. intentState.renderTasks.push(opListTask);
  8912. intentState.operatorList = {
  8913. fnArray: [],
  8914. argsArray: [],
  8915. lastChunk: false
  8916. };
  8917. this.transport.messageHandler.send('RenderPageRequest', {
  8918. pageIndex: this.pageIndex,
  8919. intent: renderingIntent
  8920. });
  8921. }
  8922. return intentState.opListReadCapability.promise;
  8923. },
  8924. /**
  8925. * @param {getTextContentParameters} params - getTextContent parameters.
  8926. * @return {Promise} That is resolved a {@link TextContent}
  8927. * object that represent the page text content.
  8928. */
  8929. getTextContent: function PDFPageProxy_getTextContent(params) {
  8930. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8931. pageIndex: this.pageNumber - 1,
  8932. normalizeWhitespace: (params && params.normalizeWhitespace === true ?
  8933. true : /* Default */ false),
  8934. combineTextItems: (params && params.disableCombineTextItems === true ?
  8935. false : /* Default */ true),
  8936. });
  8937. },
  8938. /**
  8939. * Destroys page object.
  8940. */
  8941. _destroy: function PDFPageProxy_destroy() {
  8942. this.destroyed = true;
  8943. this.transport.pageCache[this.pageIndex] = null;
  8944. var waitOn = [];
  8945. Object.keys(this.intentStates).forEach(function(intent) {
  8946. if (intent === 'oplist') {
  8947. // Avoid errors below, since the renderTasks are just stubs.
  8948. return;
  8949. }
  8950. var intentState = this.intentStates[intent];
  8951. intentState.renderTasks.forEach(function(renderTask) {
  8952. var renderCompleted = renderTask.capability.promise.
  8953. catch(function () {}); // ignoring failures
  8954. waitOn.push(renderCompleted);
  8955. renderTask.cancel();
  8956. });
  8957. }, this);
  8958. this.objs.clear();
  8959. this.annotationsPromise = null;
  8960. this.pendingCleanup = false;
  8961. return Promise.all(waitOn);
  8962. },
  8963. /**
  8964. * Cleans up resources allocated by the page. (deprecated)
  8965. */
  8966. destroy: function() {
  8967. deprecated('page destroy method, use cleanup() instead');
  8968. this.cleanup();
  8969. },
  8970. /**
  8971. * Cleans up resources allocated by the page.
  8972. */
  8973. cleanup: function PDFPageProxy_cleanup() {
  8974. this.pendingCleanup = true;
  8975. this._tryCleanup();
  8976. },
  8977. /**
  8978. * For internal use only. Attempts to clean up if rendering is in a state
  8979. * where that's possible.
  8980. * @ignore
  8981. */
  8982. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8983. if (!this.pendingCleanup ||
  8984. Object.keys(this.intentStates).some(function(intent) {
  8985. var intentState = this.intentStates[intent];
  8986. return (intentState.renderTasks.length !== 0 ||
  8987. intentState.receivingOperatorList);
  8988. }, this)) {
  8989. return;
  8990. }
  8991. Object.keys(this.intentStates).forEach(function(intent) {
  8992. delete this.intentStates[intent];
  8993. }, this);
  8994. this.objs.clear();
  8995. this.annotationsPromise = null;
  8996. this.pendingCleanup = false;
  8997. },
  8998. /**
  8999. * For internal use only.
  9000. * @ignore
  9001. */
  9002. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  9003. intent) {
  9004. var intentState = this.intentStates[intent];
  9005. // TODO Refactor RenderPageRequest to separate rendering
  9006. // and operator list logic
  9007. if (intentState.displayReadyCapability) {
  9008. intentState.displayReadyCapability.resolve(transparency);
  9009. }
  9010. },
  9011. /**
  9012. * For internal use only.
  9013. * @ignore
  9014. */
  9015. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  9016. intent) {
  9017. var intentState = this.intentStates[intent];
  9018. var i, ii;
  9019. // Add the new chunk to the current operator list.
  9020. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9021. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9022. intentState.operatorList.argsArray.push(
  9023. operatorListChunk.argsArray[i]);
  9024. }
  9025. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9026. // Notify all the rendering tasks there are more operators to be consumed.
  9027. for (i = 0; i < intentState.renderTasks.length; i++) {
  9028. intentState.renderTasks[i].operatorListChanged();
  9029. }
  9030. if (operatorListChunk.lastChunk) {
  9031. intentState.receivingOperatorList = false;
  9032. this._tryCleanup();
  9033. }
  9034. }
  9035. };
  9036. return PDFPageProxy;
  9037. })();
  9038. /**
  9039. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9040. * WorkerTransport for them. If creation of a web worker is not possible,
  9041. * a "fake" worker will be used instead.
  9042. * @class
  9043. */
  9044. var PDFWorker = (function PDFWorkerClosure() {
  9045. var nextFakeWorkerId = 0;
  9046. function getWorkerSrc() {
  9047. if (typeof workerSrc !== 'undefined') {
  9048. return workerSrc;
  9049. }
  9050. if (getDefaultSetting('workerSrc')) {
  9051. return getDefaultSetting('workerSrc');
  9052. }
  9053. if (pdfjsFilePath) {
  9054. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9055. }
  9056. error('No PDFJS.workerSrc specified');
  9057. }
  9058. var fakeWorkerFilesLoadedCapability;
  9059. // Loads worker code into main thread.
  9060. function setupFakeWorkerGlobal() {
  9061. var WorkerMessageHandler;
  9062. if (!fakeWorkerFilesLoadedCapability) {
  9063. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9064. // In the developer build load worker_loader which in turn loads all the
  9065. // other files and resolves the promise. In production only the
  9066. // pdf.worker.js file is needed.
  9067. var loader = fakeWorkerFilesLoader || function (callback) {
  9068. Util.loadScript(getWorkerSrc(), function () {
  9069. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9070. });
  9071. };
  9072. loader(fakeWorkerFilesLoadedCapability.resolve);
  9073. }
  9074. return fakeWorkerFilesLoadedCapability.promise;
  9075. }
  9076. function FakeWorkerPort(defer) {
  9077. this._listeners = [];
  9078. this._defer = defer;
  9079. this._deferred = Promise.resolve(undefined);
  9080. }
  9081. FakeWorkerPort.prototype = {
  9082. postMessage: function (obj, transfers) {
  9083. function cloneValue(value) {
  9084. // Trying to perform a structured clone close to the spec, including
  9085. // transfers.
  9086. if (typeof value !== 'object' || value === null) {
  9087. return value;
  9088. }
  9089. if (cloned.has(value)) { // already cloned the object
  9090. return cloned.get(value);
  9091. }
  9092. var result;
  9093. var buffer;
  9094. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9095. // We found object with ArrayBuffer (typed array).
  9096. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9097. if (value === buffer) {
  9098. // Special case when we are faking typed arrays in compatibility.js.
  9099. result = value;
  9100. } else if (transferable) {
  9101. result = new value.constructor(buffer, value.byteOffset,
  9102. value.byteLength);
  9103. } else {
  9104. result = new value.constructor(value);
  9105. }
  9106. cloned.set(value, result);
  9107. return result;
  9108. }
  9109. result = isArray(value) ? [] : {};
  9110. cloned.set(value, result); // adding to cache now for cyclic references
  9111. // Cloning all value and object properties, however ignoring properties
  9112. // defined via getter.
  9113. for (var i in value) {
  9114. var desc, p = value;
  9115. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9116. p = Object.getPrototypeOf(p);
  9117. }
  9118. if (typeof desc.value === 'undefined' ||
  9119. typeof desc.value === 'function') {
  9120. continue;
  9121. }
  9122. result[i] = cloneValue(desc.value);
  9123. }
  9124. return result;
  9125. }
  9126. if (!this._defer) {
  9127. this._listeners.forEach(function (listener) {
  9128. listener.call(this, {data: obj});
  9129. }, this);
  9130. return;
  9131. }
  9132. var cloned = new WeakMap();
  9133. var e = {data: cloneValue(obj)};
  9134. this._deferred.then(function () {
  9135. this._listeners.forEach(function (listener) {
  9136. listener.call(this, e);
  9137. }, this);
  9138. }.bind(this));
  9139. },
  9140. addEventListener: function (name, listener) {
  9141. this._listeners.push(listener);
  9142. },
  9143. removeEventListener: function (name, listener) {
  9144. var i = this._listeners.indexOf(listener);
  9145. this._listeners.splice(i, 1);
  9146. },
  9147. terminate: function () {
  9148. this._listeners = [];
  9149. }
  9150. };
  9151. function createCDNWrapper(url) {
  9152. // We will rely on blob URL's property to specify origin.
  9153. // We want this function to fail in case if createObjectURL or Blob do not
  9154. // exist or fail for some reason -- our Worker creation will fail anyway.
  9155. var wrapper = 'importScripts(\'' + url + '\');';
  9156. return URL.createObjectURL(new Blob([wrapper]));
  9157. }
  9158. function PDFWorker(name) {
  9159. this.name = name;
  9160. this.destroyed = false;
  9161. this._readyCapability = createPromiseCapability();
  9162. this._port = null;
  9163. this._webWorker = null;
  9164. this._messageHandler = null;
  9165. this._initialize();
  9166. }
  9167. PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
  9168. get promise() {
  9169. return this._readyCapability.promise;
  9170. },
  9171. get port() {
  9172. return this._port;
  9173. },
  9174. get messageHandler() {
  9175. return this._messageHandler;
  9176. },
  9177. _initialize: function PDFWorker_initialize() {
  9178. // If worker support isn't disabled explicit and the browser has worker
  9179. // support, create a new web worker and test if it/the browser fulfills
  9180. // all requirements to run parts of pdf.js in a web worker.
  9181. // Right now, the requirement is, that an Uint8Array is still an
  9182. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9183. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') &&
  9184. typeof Worker !== 'undefined') {
  9185. var workerSrc = getWorkerSrc();
  9186. try {
  9187. // Wraps workerSrc path into blob URL, if the former does not belong
  9188. // to the same origin.
  9189. if (!isSameOrigin(window.location.href, workerSrc)) {
  9190. workerSrc = createCDNWrapper(
  9191. new URL(workerSrc, window.location).href);
  9192. }
  9193. // Some versions of FF can't create a worker on localhost, see:
  9194. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9195. var worker = new Worker(workerSrc);
  9196. var messageHandler = new MessageHandler('main', 'worker', worker);
  9197. var terminateEarly = function() {
  9198. worker.removeEventListener('error', onWorkerError);
  9199. messageHandler.destroy();
  9200. worker.terminate();
  9201. if (this.destroyed) {
  9202. this._readyCapability.reject(new Error('Worker was destroyed'));
  9203. } else {
  9204. // Fall back to fake worker if the termination is caused by an
  9205. // error (e.g. NetworkError / SecurityError).
  9206. this._setupFakeWorker();
  9207. }
  9208. }.bind(this);
  9209. var onWorkerError = function(event) {
  9210. if (!this._webWorker) {
  9211. // Worker failed to initialize due to an error. Clean up and fall
  9212. // back to the fake worker.
  9213. terminateEarly();
  9214. }
  9215. }.bind(this);
  9216. worker.addEventListener('error', onWorkerError);
  9217. messageHandler.on('test', function PDFWorker_test(data) {
  9218. worker.removeEventListener('error', onWorkerError);
  9219. if (this.destroyed) {
  9220. terminateEarly();
  9221. return; // worker was destroyed
  9222. }
  9223. var supportTypedArray = data && data.supportTypedArray;
  9224. if (supportTypedArray) {
  9225. this._messageHandler = messageHandler;
  9226. this._port = worker;
  9227. this._webWorker = worker;
  9228. if (!data.supportTransfers) {
  9229. isPostMessageTransfersDisabled = true;
  9230. }
  9231. this._readyCapability.resolve();
  9232. // Send global setting, e.g. verbosity level.
  9233. messageHandler.send('configure', {
  9234. verbosity: getVerbosityLevel()
  9235. });
  9236. } else {
  9237. this._setupFakeWorker();
  9238. messageHandler.destroy();
  9239. worker.terminate();
  9240. }
  9241. }.bind(this));
  9242. messageHandler.on('console_log', function (data) {
  9243. console.log.apply(console, data);
  9244. });
  9245. messageHandler.on('console_error', function (data) {
  9246. console.error.apply(console, data);
  9247. });
  9248. messageHandler.on('ready', function (data) {
  9249. worker.removeEventListener('error', onWorkerError);
  9250. if (this.destroyed) {
  9251. terminateEarly();
  9252. return; // worker was destroyed
  9253. }
  9254. try {
  9255. sendTest();
  9256. } catch (e) {
  9257. // We need fallback to a faked worker.
  9258. this._setupFakeWorker();
  9259. }
  9260. }.bind(this));
  9261. var sendTest = function () {
  9262. var postMessageTransfers =
  9263. getDefaultSetting('postMessageTransfers') &&
  9264. !isPostMessageTransfersDisabled;
  9265. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9266. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9267. // typed array. Also, checking if we can use transfers.
  9268. try {
  9269. messageHandler.send('test', testObj, [testObj.buffer]);
  9270. } catch (ex) {
  9271. info('Cannot use postMessage transfers');
  9272. testObj[0] = 0;
  9273. messageHandler.send('test', testObj);
  9274. }
  9275. };
  9276. // It might take time for worker to initialize (especially when AMD
  9277. // loader is used). We will try to send test immediately, and then
  9278. // when 'ready' message will arrive. The worker shall process only
  9279. // first received 'test'.
  9280. sendTest();
  9281. return;
  9282. } catch (e) {
  9283. info('The worker has been disabled.');
  9284. }
  9285. }
  9286. // Either workers are disabled, not supported or have thrown an exception.
  9287. // Thus, we fallback to a faked worker.
  9288. this._setupFakeWorker();
  9289. },
  9290. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9291. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9292. warn('Setting up fake worker.');
  9293. isWorkerDisabled = true;
  9294. }
  9295. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9296. if (this.destroyed) {
  9297. this._readyCapability.reject(new Error('Worker was destroyed'));
  9298. return;
  9299. }
  9300. // We cannot turn on proper fake port simulation (this includes
  9301. // structured cloning) when typed arrays are not supported. Relying
  9302. // on a chance that messages will be sent in proper order.
  9303. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9304. var port = new FakeWorkerPort(isTypedArraysPresent);
  9305. this._port = port;
  9306. // All fake workers use the same port, making id unique.
  9307. var id = 'fake' + (nextFakeWorkerId++);
  9308. // If the main thread is our worker, setup the handling for the
  9309. // messages -- the main thread sends to it self.
  9310. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9311. WorkerMessageHandler.setup(workerHandler, port);
  9312. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9313. this._messageHandler = messageHandler;
  9314. this._readyCapability.resolve();
  9315. }.bind(this));
  9316. },
  9317. /**
  9318. * Destroys the worker instance.
  9319. */
  9320. destroy: function PDFWorker_destroy() {
  9321. this.destroyed = true;
  9322. if (this._webWorker) {
  9323. // We need to terminate only web worker created resource.
  9324. this._webWorker.terminate();
  9325. this._webWorker = null;
  9326. }
  9327. this._port = null;
  9328. if (this._messageHandler) {
  9329. this._messageHandler.destroy();
  9330. this._messageHandler = null;
  9331. }
  9332. }
  9333. };
  9334. return PDFWorker;
  9335. })();
  9336. /**
  9337. * For internal use only.
  9338. * @ignore
  9339. */
  9340. var WorkerTransport = (function WorkerTransportClosure() {
  9341. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9342. this.messageHandler = messageHandler;
  9343. this.loadingTask = loadingTask;
  9344. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9345. this.commonObjs = new PDFObjects();
  9346. this.fontLoader = new FontLoader(loadingTask.docId);
  9347. this.destroyed = false;
  9348. this.destroyCapability = null;
  9349. this.pageCache = [];
  9350. this.pagePromises = [];
  9351. this.downloadInfoCapability = createPromiseCapability();
  9352. this.setupMessageHandler();
  9353. }
  9354. WorkerTransport.prototype = {
  9355. destroy: function WorkerTransport_destroy() {
  9356. if (this.destroyCapability) {
  9357. return this.destroyCapability.promise;
  9358. }
  9359. this.destroyed = true;
  9360. this.destroyCapability = createPromiseCapability();
  9361. var waitOn = [];
  9362. // We need to wait for all renderings to be completed, e.g.
  9363. // timeout/rAF can take a long time.
  9364. this.pageCache.forEach(function (page) {
  9365. if (page) {
  9366. waitOn.push(page._destroy());
  9367. }
  9368. });
  9369. this.pageCache = [];
  9370. this.pagePromises = [];
  9371. var self = this;
  9372. // We also need to wait for the worker to finish its long running tasks.
  9373. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9374. waitOn.push(terminated);
  9375. Promise.all(waitOn).then(function () {
  9376. self.fontLoader.clear();
  9377. if (self.pdfDataRangeTransport) {
  9378. self.pdfDataRangeTransport.abort();
  9379. self.pdfDataRangeTransport = null;
  9380. }
  9381. if (self.messageHandler) {
  9382. self.messageHandler.destroy();
  9383. self.messageHandler = null;
  9384. }
  9385. self.destroyCapability.resolve();
  9386. }, this.destroyCapability.reject);
  9387. return this.destroyCapability.promise;
  9388. },
  9389. setupMessageHandler:
  9390. function WorkerTransport_setupMessageHandler() {
  9391. var messageHandler = this.messageHandler;
  9392. function updatePassword(password) {
  9393. messageHandler.send('UpdatePassword', password);
  9394. }
  9395. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9396. if (pdfDataRangeTransport) {
  9397. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  9398. messageHandler.send('OnDataRange', {
  9399. begin: begin,
  9400. chunk: chunk
  9401. });
  9402. });
  9403. pdfDataRangeTransport.addProgressListener(function(loaded) {
  9404. messageHandler.send('OnDataProgress', {
  9405. loaded: loaded
  9406. });
  9407. });
  9408. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  9409. messageHandler.send('OnDataRange', {
  9410. chunk: chunk
  9411. });
  9412. });
  9413. messageHandler.on('RequestDataRange',
  9414. function transportDataRange(data) {
  9415. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9416. }, this);
  9417. }
  9418. messageHandler.on('GetDoc', function transportDoc(data) {
  9419. var pdfInfo = data.pdfInfo;
  9420. this.numPages = data.pdfInfo.numPages;
  9421. var loadingTask = this.loadingTask;
  9422. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9423. this.pdfDocument = pdfDocument;
  9424. loadingTask._capability.resolve(pdfDocument);
  9425. }, this);
  9426. messageHandler.on('NeedPassword',
  9427. function transportNeedPassword(exception) {
  9428. var loadingTask = this.loadingTask;
  9429. if (loadingTask.onPassword) {
  9430. return loadingTask.onPassword(updatePassword,
  9431. PasswordResponses.NEED_PASSWORD);
  9432. }
  9433. loadingTask._capability.reject(
  9434. new PasswordException(exception.message, exception.code));
  9435. }, this);
  9436. messageHandler.on('IncorrectPassword',
  9437. function transportIncorrectPassword(exception) {
  9438. var loadingTask = this.loadingTask;
  9439. if (loadingTask.onPassword) {
  9440. return loadingTask.onPassword(updatePassword,
  9441. PasswordResponses.INCORRECT_PASSWORD);
  9442. }
  9443. loadingTask._capability.reject(
  9444. new PasswordException(exception.message, exception.code));
  9445. }, this);
  9446. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9447. this.loadingTask._capability.reject(
  9448. new InvalidPDFException(exception.message));
  9449. }, this);
  9450. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9451. this.loadingTask._capability.reject(
  9452. new MissingPDFException(exception.message));
  9453. }, this);
  9454. messageHandler.on('UnexpectedResponse',
  9455. function transportUnexpectedResponse(exception) {
  9456. this.loadingTask._capability.reject(
  9457. new UnexpectedResponseException(exception.message, exception.status));
  9458. }, this);
  9459. messageHandler.on('UnknownError',
  9460. function transportUnknownError(exception) {
  9461. this.loadingTask._capability.reject(
  9462. new UnknownErrorException(exception.message, exception.details));
  9463. }, this);
  9464. messageHandler.on('DataLoaded', function transportPage(data) {
  9465. this.downloadInfoCapability.resolve(data);
  9466. }, this);
  9467. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9468. if (this.pdfDataRangeTransport) {
  9469. this.pdfDataRangeTransport.transportReady();
  9470. }
  9471. }, this);
  9472. messageHandler.on('StartRenderPage', function transportRender(data) {
  9473. if (this.destroyed) {
  9474. return; // Ignore any pending requests if the worker was terminated.
  9475. }
  9476. var page = this.pageCache[data.pageIndex];
  9477. page.stats.timeEnd('Page Request');
  9478. page._startRenderPage(data.transparency, data.intent);
  9479. }, this);
  9480. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9481. if (this.destroyed) {
  9482. return; // Ignore any pending requests if the worker was terminated.
  9483. }
  9484. var page = this.pageCache[data.pageIndex];
  9485. page._renderPageChunk(data.operatorList, data.intent);
  9486. }, this);
  9487. messageHandler.on('commonobj', function transportObj(data) {
  9488. if (this.destroyed) {
  9489. return; // Ignore any pending requests if the worker was terminated.
  9490. }
  9491. var id = data[0];
  9492. var type = data[1];
  9493. if (this.commonObjs.hasData(id)) {
  9494. return;
  9495. }
  9496. switch (type) {
  9497. case 'Font':
  9498. var exportedData = data[2];
  9499. if ('error' in exportedData) {
  9500. var exportedError = exportedData.error;
  9501. warn('Error during font loading: ' + exportedError);
  9502. this.commonObjs.resolve(id, exportedError);
  9503. break;
  9504. }
  9505. var fontRegistry = null;
  9506. if (getDefaultSetting('pdfBug') && globalScope.FontInspector &&
  9507. globalScope['FontInspector'].enabled) {
  9508. fontRegistry = {
  9509. registerFont: function (font, url) {
  9510. globalScope['FontInspector'].fontAdded(font, url);
  9511. }
  9512. };
  9513. }
  9514. var font = new FontFaceObject(exportedData, {
  9515. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9516. disableFontFace: getDefaultSetting('disableFontFace'),
  9517. fontRegistry: fontRegistry
  9518. });
  9519. this.fontLoader.bind(
  9520. [font],
  9521. function fontReady(fontObjs) {
  9522. this.commonObjs.resolve(id, font);
  9523. }.bind(this)
  9524. );
  9525. break;
  9526. case 'FontPath':
  9527. this.commonObjs.resolve(id, data[2]);
  9528. break;
  9529. default:
  9530. error('Got unknown common object type ' + type);
  9531. }
  9532. }, this);
  9533. messageHandler.on('obj', function transportObj(data) {
  9534. if (this.destroyed) {
  9535. return; // Ignore any pending requests if the worker was terminated.
  9536. }
  9537. var id = data[0];
  9538. var pageIndex = data[1];
  9539. var type = data[2];
  9540. var pageProxy = this.pageCache[pageIndex];
  9541. var imageData;
  9542. if (pageProxy.objs.hasData(id)) {
  9543. return;
  9544. }
  9545. switch (type) {
  9546. case 'JpegStream':
  9547. imageData = data[3];
  9548. loadJpegStream(id, imageData, pageProxy.objs);
  9549. break;
  9550. case 'Image':
  9551. imageData = data[3];
  9552. pageProxy.objs.resolve(id, imageData);
  9553. // heuristics that will allow not to store large data
  9554. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9555. if (imageData && 'data' in imageData &&
  9556. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9557. pageProxy.cleanupAfterRender = true;
  9558. }
  9559. break;
  9560. default:
  9561. error('Got unknown object type ' + type);
  9562. }
  9563. }, this);
  9564. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9565. if (this.destroyed) {
  9566. return; // Ignore any pending requests if the worker was terminated.
  9567. }
  9568. var loadingTask = this.loadingTask;
  9569. if (loadingTask.onProgress) {
  9570. loadingTask.onProgress({
  9571. loaded: data.loaded,
  9572. total: data.total
  9573. });
  9574. }
  9575. }, this);
  9576. messageHandler.on('PageError', function transportError(data) {
  9577. if (this.destroyed) {
  9578. return; // Ignore any pending requests if the worker was terminated.
  9579. }
  9580. var page = this.pageCache[data.pageNum - 1];
  9581. var intentState = page.intentStates[data.intent];
  9582. if (intentState.displayReadyCapability) {
  9583. intentState.displayReadyCapability.reject(data.error);
  9584. } else {
  9585. error(data.error);
  9586. }
  9587. if (intentState.operatorList) {
  9588. // Mark operator list as complete.
  9589. intentState.operatorList.lastChunk = true;
  9590. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9591. intentState.renderTasks[i].operatorListChanged();
  9592. }
  9593. }
  9594. }, this);
  9595. messageHandler.on('UnsupportedFeature',
  9596. function transportUnsupportedFeature(data) {
  9597. if (this.destroyed) {
  9598. return; // Ignore any pending requests if the worker was terminated.
  9599. }
  9600. var featureId = data.featureId;
  9601. var loadingTask = this.loadingTask;
  9602. if (loadingTask.onUnsupportedFeature) {
  9603. loadingTask.onUnsupportedFeature(featureId);
  9604. }
  9605. _UnsupportedManager.notify(featureId);
  9606. }, this);
  9607. messageHandler.on('JpegDecode', function(data) {
  9608. if (this.destroyed) {
  9609. return Promise.reject(new Error('Worker was destroyed'));
  9610. }
  9611. var imageUrl = data[0];
  9612. var components = data[1];
  9613. if (components !== 3 && components !== 1) {
  9614. return Promise.reject(
  9615. new Error('Only 3 components or 1 component can be returned'));
  9616. }
  9617. return new Promise(function (resolve, reject) {
  9618. var img = new Image();
  9619. img.onload = function () {
  9620. var width = img.width;
  9621. var height = img.height;
  9622. var size = width * height;
  9623. var rgbaLength = size * 4;
  9624. var buf = new Uint8Array(size * components);
  9625. var tmpCanvas = createScratchCanvas(width, height);
  9626. var tmpCtx = tmpCanvas.getContext('2d');
  9627. tmpCtx.drawImage(img, 0, 0);
  9628. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9629. var i, j;
  9630. if (components === 3) {
  9631. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9632. buf[j] = data[i];
  9633. buf[j + 1] = data[i + 1];
  9634. buf[j + 2] = data[i + 2];
  9635. }
  9636. } else if (components === 1) {
  9637. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9638. buf[j] = data[i];
  9639. }
  9640. }
  9641. resolve({ data: buf, width: width, height: height});
  9642. };
  9643. img.onerror = function () {
  9644. reject(new Error('JpegDecode failed to load image'));
  9645. };
  9646. img.src = imageUrl;
  9647. });
  9648. }, this);
  9649. },
  9650. getData: function WorkerTransport_getData() {
  9651. return this.messageHandler.sendWithPromise('GetData', null);
  9652. },
  9653. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9654. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9655. return Promise.reject(new Error('Invalid page request'));
  9656. }
  9657. var pageIndex = pageNumber - 1;
  9658. if (pageIndex in this.pagePromises) {
  9659. return this.pagePromises[pageIndex];
  9660. }
  9661. var promise = this.messageHandler.sendWithPromise('GetPage', {
  9662. pageIndex: pageIndex
  9663. }).then(function (pageInfo) {
  9664. if (this.destroyed) {
  9665. throw new Error('Transport destroyed');
  9666. }
  9667. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9668. this.pageCache[pageIndex] = page;
  9669. return page;
  9670. }.bind(this));
  9671. this.pagePromises[pageIndex] = promise;
  9672. return promise;
  9673. },
  9674. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9675. return this.messageHandler.sendWithPromise('GetPageIndex', {
  9676. ref: ref,
  9677. }).catch(function (reason) {
  9678. return Promise.reject(new Error(reason));
  9679. });
  9680. },
  9681. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9682. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9683. pageIndex: pageIndex,
  9684. intent: intent,
  9685. });
  9686. },
  9687. getDestinations: function WorkerTransport_getDestinations() {
  9688. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9689. },
  9690. getDestination: function WorkerTransport_getDestination(id) {
  9691. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9692. },
  9693. getPageLabels: function WorkerTransport_getPageLabels() {
  9694. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9695. },
  9696. getAttachments: function WorkerTransport_getAttachments() {
  9697. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9698. },
  9699. getJavaScript: function WorkerTransport_getJavaScript() {
  9700. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9701. },
  9702. getOutline: function WorkerTransport_getOutline() {
  9703. return this.messageHandler.sendWithPromise('GetOutline', null);
  9704. },
  9705. getMetadata: function WorkerTransport_getMetadata() {
  9706. return this.messageHandler.sendWithPromise('GetMetadata', null).
  9707. then(function transportMetadata(results) {
  9708. return {
  9709. info: results[0],
  9710. metadata: (results[1] ? new Metadata(results[1]) : null)
  9711. };
  9712. });
  9713. },
  9714. getStats: function WorkerTransport_getStats() {
  9715. return this.messageHandler.sendWithPromise('GetStats', null);
  9716. },
  9717. startCleanup: function WorkerTransport_startCleanup() {
  9718. this.messageHandler.sendWithPromise('Cleanup', null).
  9719. then(function endCleanup() {
  9720. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  9721. var page = this.pageCache[i];
  9722. if (page) {
  9723. page.cleanup();
  9724. }
  9725. }
  9726. this.commonObjs.clear();
  9727. this.fontLoader.clear();
  9728. }.bind(this));
  9729. }
  9730. };
  9731. return WorkerTransport;
  9732. })();
  9733. /**
  9734. * A PDF document and page is built of many objects. E.g. there are objects
  9735. * for fonts, images, rendering code and such. These objects might get processed
  9736. * inside of a worker. The `PDFObjects` implements some basic functions to
  9737. * manage these objects.
  9738. * @ignore
  9739. */
  9740. var PDFObjects = (function PDFObjectsClosure() {
  9741. function PDFObjects() {
  9742. this.objs = Object.create(null);
  9743. }
  9744. PDFObjects.prototype = {
  9745. /**
  9746. * Internal function.
  9747. * Ensures there is an object defined for `objId`.
  9748. */
  9749. ensureObj: function PDFObjects_ensureObj(objId) {
  9750. if (this.objs[objId]) {
  9751. return this.objs[objId];
  9752. }
  9753. var obj = {
  9754. capability: createPromiseCapability(),
  9755. data: null,
  9756. resolved: false
  9757. };
  9758. this.objs[objId] = obj;
  9759. return obj;
  9760. },
  9761. /**
  9762. * If called *without* callback, this returns the data of `objId` but the
  9763. * object needs to be resolved. If it isn't, this function throws.
  9764. *
  9765. * If called *with* a callback, the callback is called with the data of the
  9766. * object once the object is resolved. That means, if you call this
  9767. * function and the object is already resolved, the callback gets called
  9768. * right away.
  9769. */
  9770. get: function PDFObjects_get(objId, callback) {
  9771. // If there is a callback, then the get can be async and the object is
  9772. // not required to be resolved right now
  9773. if (callback) {
  9774. this.ensureObj(objId).capability.promise.then(callback);
  9775. return null;
  9776. }
  9777. // If there isn't a callback, the user expects to get the resolved data
  9778. // directly.
  9779. var obj = this.objs[objId];
  9780. // If there isn't an object yet or the object isn't resolved, then the
  9781. // data isn't ready yet!
  9782. if (!obj || !obj.resolved) {
  9783. error('Requesting object that isn\'t resolved yet ' + objId);
  9784. }
  9785. return obj.data;
  9786. },
  9787. /**
  9788. * Resolves the object `objId` with optional `data`.
  9789. */
  9790. resolve: function PDFObjects_resolve(objId, data) {
  9791. var obj = this.ensureObj(objId);
  9792. obj.resolved = true;
  9793. obj.data = data;
  9794. obj.capability.resolve(data);
  9795. },
  9796. isResolved: function PDFObjects_isResolved(objId) {
  9797. var objs = this.objs;
  9798. if (!objs[objId]) {
  9799. return false;
  9800. } else {
  9801. return objs[objId].resolved;
  9802. }
  9803. },
  9804. hasData: function PDFObjects_hasData(objId) {
  9805. return this.isResolved(objId);
  9806. },
  9807. /**
  9808. * Returns the data of `objId` if object exists, null otherwise.
  9809. */
  9810. getData: function PDFObjects_getData(objId) {
  9811. var objs = this.objs;
  9812. if (!objs[objId] || !objs[objId].resolved) {
  9813. return null;
  9814. } else {
  9815. return objs[objId].data;
  9816. }
  9817. },
  9818. clear: function PDFObjects_clear() {
  9819. this.objs = Object.create(null);
  9820. }
  9821. };
  9822. return PDFObjects;
  9823. })();
  9824. /**
  9825. * Allows controlling of the rendering tasks.
  9826. * @class
  9827. * @alias RenderTask
  9828. */
  9829. var RenderTask = (function RenderTaskClosure() {
  9830. function RenderTask(internalRenderTask) {
  9831. this._internalRenderTask = internalRenderTask;
  9832. /**
  9833. * Callback for incremental rendering -- a function that will be called
  9834. * each time the rendering is paused. To continue rendering call the
  9835. * function that is the first argument to the callback.
  9836. * @type {function}
  9837. */
  9838. this.onContinue = null;
  9839. }
  9840. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  9841. /**
  9842. * Promise for rendering task completion.
  9843. * @return {Promise}
  9844. */
  9845. get promise() {
  9846. return this._internalRenderTask.capability.promise;
  9847. },
  9848. /**
  9849. * Cancels the rendering task. If the task is currently rendering it will
  9850. * not be cancelled until graphics pauses with a timeout. The promise that
  9851. * this object extends will resolved when cancelled.
  9852. */
  9853. cancel: function RenderTask_cancel() {
  9854. this._internalRenderTask.cancel();
  9855. },
  9856. /**
  9857. * Registers callbacks to indicate the rendering task completion.
  9858. *
  9859. * @param {function} onFulfilled The callback for the rendering completion.
  9860. * @param {function} onRejected The callback for the rendering failure.
  9861. * @return {Promise} A promise that is resolved after the onFulfilled or
  9862. * onRejected callback.
  9863. */
  9864. then: function RenderTask_then(onFulfilled, onRejected) {
  9865. return this.promise.then.apply(this.promise, arguments);
  9866. }
  9867. };
  9868. return RenderTask;
  9869. })();
  9870. /**
  9871. * For internal use only.
  9872. * @ignore
  9873. */
  9874. var InternalRenderTask = (function InternalRenderTaskClosure() {
  9875. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  9876. pageNumber) {
  9877. this.callback = callback;
  9878. this.params = params;
  9879. this.objs = objs;
  9880. this.commonObjs = commonObjs;
  9881. this.operatorListIdx = null;
  9882. this.operatorList = operatorList;
  9883. this.pageNumber = pageNumber;
  9884. this.running = false;
  9885. this.graphicsReadyCallback = null;
  9886. this.graphicsReady = false;
  9887. this.useRequestAnimationFrame = false;
  9888. this.cancelled = false;
  9889. this.capability = createPromiseCapability();
  9890. this.task = new RenderTask(this);
  9891. // caching this-bound methods
  9892. this._continueBound = this._continue.bind(this);
  9893. this._scheduleNextBound = this._scheduleNext.bind(this);
  9894. this._nextBound = this._next.bind(this);
  9895. }
  9896. InternalRenderTask.prototype = {
  9897. initializeGraphics:
  9898. function InternalRenderTask_initializeGraphics(transparency) {
  9899. if (this.cancelled) {
  9900. return;
  9901. }
  9902. if (getDefaultSetting('pdfBug') && globalScope.StepperManager &&
  9903. globalScope.StepperManager.enabled) {
  9904. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  9905. this.stepper.init(this.operatorList);
  9906. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  9907. }
  9908. var params = this.params;
  9909. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  9910. this.objs, params.imageLayer);
  9911. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  9912. this.operatorListIdx = 0;
  9913. this.graphicsReady = true;
  9914. if (this.graphicsReadyCallback) {
  9915. this.graphicsReadyCallback();
  9916. }
  9917. },
  9918. cancel: function InternalRenderTask_cancel() {
  9919. this.running = false;
  9920. this.cancelled = true;
  9921. this.callback('cancelled');
  9922. },
  9923. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  9924. if (!this.graphicsReady) {
  9925. if (!this.graphicsReadyCallback) {
  9926. this.graphicsReadyCallback = this._continueBound;
  9927. }
  9928. return;
  9929. }
  9930. if (this.stepper) {
  9931. this.stepper.updateOperatorList(this.operatorList);
  9932. }
  9933. if (this.running) {
  9934. return;
  9935. }
  9936. this._continue();
  9937. },
  9938. _continue: function InternalRenderTask__continue() {
  9939. this.running = true;
  9940. if (this.cancelled) {
  9941. return;
  9942. }
  9943. if (this.task.onContinue) {
  9944. this.task.onContinue.call(this.task, this._scheduleNextBound);
  9945. } else {
  9946. this._scheduleNext();
  9947. }
  9948. },
  9949. _scheduleNext: function InternalRenderTask__scheduleNext() {
  9950. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  9951. window.requestAnimationFrame(this._nextBound);
  9952. } else {
  9953. Promise.resolve(undefined).then(this._nextBound);
  9954. }
  9955. },
  9956. _next: function InternalRenderTask__next() {
  9957. if (this.cancelled) {
  9958. return;
  9959. }
  9960. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  9961. this.operatorListIdx,
  9962. this._continueBound,
  9963. this.stepper);
  9964. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  9965. this.running = false;
  9966. if (this.operatorList.lastChunk) {
  9967. this.gfx.endDrawing();
  9968. this.callback();
  9969. }
  9970. }
  9971. }
  9972. };
  9973. return InternalRenderTask;
  9974. })();
  9975. /**
  9976. * (Deprecated) Global observer of unsupported feature usages. Use
  9977. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  9978. */
  9979. var _UnsupportedManager = (function UnsupportedManagerClosure() {
  9980. var listeners = [];
  9981. return {
  9982. listen: function (cb) {
  9983. deprecated('Global UnsupportedManager.listen is used: ' +
  9984. ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  9985. listeners.push(cb);
  9986. },
  9987. notify: function (featureId) {
  9988. for (var i = 0, ii = listeners.length; i < ii; i++) {
  9989. listeners[i](featureId);
  9990. }
  9991. }
  9992. };
  9993. })();
  9994. if (typeof pdfjsVersion !== 'undefined') {
  9995. exports.version = pdfjsVersion;
  9996. }
  9997. if (typeof pdfjsBuild !== 'undefined') {
  9998. exports.build = pdfjsBuild;
  9999. }
  10000. exports.getDocument = getDocument;
  10001. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10002. exports.PDFWorker = PDFWorker;
  10003. exports.PDFDocumentProxy = PDFDocumentProxy;
  10004. exports.PDFPageProxy = PDFPageProxy;
  10005. exports._UnsupportedManager = _UnsupportedManager;
  10006. }));
  10007. (function (root, factory) {
  10008. {
  10009. factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil,
  10010. root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI,
  10011. root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer,
  10012. root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10013. }
  10014. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI,
  10015. displayAnnotationLayer, displayTextLayer, displayMetadata,
  10016. displaySVG) {
  10017. var globalScope = sharedUtil.globalScope;
  10018. var deprecated = sharedUtil.deprecated;
  10019. var warn = sharedUtil.warn;
  10020. var LinkTarget = displayDOMUtils.LinkTarget;
  10021. var isWorker = (typeof window === 'undefined');
  10022. // The global PDFJS object is now deprecated and will not be supported in
  10023. // the future. The members below are maintained for backward compatibility
  10024. // and shall not be extended or modified. If the global.js is included as
  10025. // a module, we will create a global PDFJS object instance or use existing.
  10026. if (!globalScope.PDFJS) {
  10027. globalScope.PDFJS = {};
  10028. }
  10029. var PDFJS = globalScope.PDFJS;
  10030. if (typeof pdfjsVersion !== 'undefined') {
  10031. PDFJS.version = pdfjsVersion;
  10032. }
  10033. if (typeof pdfjsBuild !== 'undefined') {
  10034. PDFJS.build = pdfjsBuild;
  10035. }
  10036. PDFJS.pdfBug = false;
  10037. if (PDFJS.verbosity !== undefined) {
  10038. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10039. }
  10040. delete PDFJS.verbosity;
  10041. Object.defineProperty(PDFJS, 'verbosity', {
  10042. get: function () { return sharedUtil.getVerbosityLevel(); },
  10043. set: function (level) { sharedUtil.setVerbosityLevel(level); },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10048. PDFJS.OPS = sharedUtil.OPS;
  10049. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10050. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10051. PDFJS.shadow = sharedUtil.shadow;
  10052. PDFJS.createBlob = sharedUtil.createBlob;
  10053. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10054. return sharedUtil.createObjectURL(data, contentType,
  10055. PDFJS.disableCreateObjectURL);
  10056. };
  10057. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10058. configurable: true,
  10059. get: function PDFJS_isLittleEndian() {
  10060. var value = sharedUtil.isLittleEndian();
  10061. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10062. }
  10063. });
  10064. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10065. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10066. PDFJS.PasswordException = sharedUtil.PasswordException;
  10067. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10068. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10069. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10070. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10071. PDFJS.Util = sharedUtil.Util;
  10072. PDFJS.PageViewport = sharedUtil.PageViewport;
  10073. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10074. /**
  10075. * The maximum allowed image size in total pixels e.g. width * height. Images
  10076. * above this value will not be drawn. Use -1 for no limit.
  10077. * @var {number}
  10078. */
  10079. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  10080. -1 : PDFJS.maxImageSize);
  10081. /**
  10082. * The url of where the predefined Adobe CMaps are located. Include trailing
  10083. * slash.
  10084. * @var {string}
  10085. */
  10086. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  10087. /**
  10088. * Specifies if CMaps are binary packed.
  10089. * @var {boolean}
  10090. */
  10091. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10092. /**
  10093. * By default fonts are converted to OpenType fonts and loaded via font face
  10094. * rules. If disabled, the font will be rendered using a built in font
  10095. * renderer that constructs the glyphs with primitive path commands.
  10096. * @var {boolean}
  10097. */
  10098. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  10099. false : PDFJS.disableFontFace);
  10100. /**
  10101. * Path for image resources, mainly for annotation icons. Include trailing
  10102. * slash.
  10103. * @var {string}
  10104. */
  10105. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  10106. '' : PDFJS.imageResourcesPath);
  10107. /**
  10108. * Disable the web worker and run all code on the main thread. This will
  10109. * happen automatically if the browser doesn't support workers or sending
  10110. * typed arrays to workers.
  10111. * @var {boolean}
  10112. */
  10113. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  10114. false : PDFJS.disableWorker);
  10115. /**
  10116. * Path and filename of the worker file. Required when the worker is enabled
  10117. * in development mode. If unspecified in the production build, the worker
  10118. * will be loaded based on the location of the pdf.js file. It is recommended
  10119. * that the workerSrc is set in a custom application to prevent issues caused
  10120. * by third-party frameworks and libraries.
  10121. * @var {string}
  10122. */
  10123. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  10124. /**
  10125. * Disable range request loading of PDF files. When enabled and if the server
  10126. * supports partial content requests then the PDF will be fetched in chunks.
  10127. * Enabled (false) by default.
  10128. * @var {boolean}
  10129. */
  10130. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  10131. false : PDFJS.disableRange);
  10132. /**
  10133. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10134. * in chunks. This default behavior can be disabled.
  10135. * @var {boolean}
  10136. */
  10137. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  10138. false : PDFJS.disableStream);
  10139. /**
  10140. * Disable pre-fetching of PDF file data. When range requests are enabled
  10141. * PDF.js will automatically keep fetching more data even if it isn't needed
  10142. * to display the current page. This default behavior can be disabled.
  10143. *
  10144. * NOTE: It is also necessary to disable streaming, see above,
  10145. * in order for disabling of pre-fetching to work correctly.
  10146. * @var {boolean}
  10147. */
  10148. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  10149. false : PDFJS.disableAutoFetch);
  10150. /**
  10151. * Enables special hooks for debugging PDF.js.
  10152. * @var {boolean}
  10153. */
  10154. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  10155. /**
  10156. * Enables transfer usage in postMessage for ArrayBuffers.
  10157. * @var {boolean}
  10158. */
  10159. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  10160. true : PDFJS.postMessageTransfers);
  10161. /**
  10162. * Disables URL.createObjectURL usage.
  10163. * @var {boolean}
  10164. */
  10165. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  10166. false : PDFJS.disableCreateObjectURL);
  10167. /**
  10168. * Disables WebGL usage.
  10169. * @var {boolean}
  10170. */
  10171. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  10172. true : PDFJS.disableWebGL);
  10173. /**
  10174. * Specifies the |target| attribute for external links.
  10175. * The constants from PDFJS.LinkTarget should be used:
  10176. * - NONE [default]
  10177. * - SELF
  10178. * - BLANK
  10179. * - PARENT
  10180. * - TOP
  10181. * @var {number}
  10182. */
  10183. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  10184. LinkTarget.NONE : PDFJS.externalLinkTarget);
  10185. /**
  10186. * Specifies the |rel| attribute for external links. Defaults to stripping
  10187. * the referrer.
  10188. * @var {string}
  10189. */
  10190. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  10191. 'noreferrer' : PDFJS.externalLinkRel);
  10192. /**
  10193. * Determines if we can eval strings as JS. Primarily used to improve
  10194. * performance for font rendering.
  10195. * @var {boolean}
  10196. */
  10197. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  10198. true : PDFJS.isEvalSupported);
  10199. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10200. delete PDFJS.openExternalLinksInNewWindow;
  10201. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10202. get: function () {
  10203. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10204. },
  10205. set: function (value) {
  10206. if (value) {
  10207. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
  10208. '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10209. }
  10210. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10211. warn('PDFJS.externalLinkTarget is already initialized');
  10212. return;
  10213. }
  10214. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10215. },
  10216. enumerable: true,
  10217. configurable: true
  10218. });
  10219. if (savedOpenExternalLinksInNewWindow) {
  10220. /**
  10221. * (Deprecated) Opens external links in a new window if enabled.
  10222. * The default behavior opens external links in the PDF.js window.
  10223. *
  10224. * NOTE: This property has been deprecated, please use
  10225. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10226. * @var {boolean}
  10227. */
  10228. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10229. }
  10230. PDFJS.getDocument = displayAPI.getDocument;
  10231. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10232. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10233. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10234. configurable: true,
  10235. get: function PDFJS_hasCanvasTypedArrays() {
  10236. var value = displayDOMUtils.hasCanvasTypedArrays();
  10237. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10238. }
  10239. });
  10240. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10241. PDFJS.LinkTarget = LinkTarget;
  10242. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10243. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10244. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10245. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10246. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10247. PDFJS.Metadata = displayMetadata.Metadata;
  10248. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10249. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10250. exports.globalScope = globalScope;
  10251. exports.isWorker = isWorker;
  10252. exports.PDFJS = globalScope.PDFJS;
  10253. }));
  10254. }).call(pdfjsLibs);
  10255. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10256. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10257. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10258. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10259. exports.PDFDataRangeTransport =
  10260. pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10261. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10262. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10263. exports.AnnotationLayer =
  10264. pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10265. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10266. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10267. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10268. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10269. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10270. exports.UnexpectedResponseException =
  10271. pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10272. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10273. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10274. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10275. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10276. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10277. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10278. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10279. exports.getFilenameFromUrl =
  10280. pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10281. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10282. }));