pdf.js 294 KB

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