pdf.js 301 KB

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