pdf.js 326 KB

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