pdf.js 305 KB

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