pdf.js 296 KB

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