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.4.20';
  30. var pdfjsBuild = 'b15f335';
  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. try {
  1616. if (typeof URL === 'function' &&
  1617. typeof URL.prototype === 'object' &&
  1618. ('origin' in URL.prototype)) {
  1619. var u = new URL('b', 'http://a');
  1620. u.pathname = 'c%20d';
  1621. hasWorkingUrl = u.href === 'http://a/c%20d';
  1622. }
  1623. } catch(e) { }
  1624. if (hasWorkingUrl)
  1625. return;
  1626. var relative = Object.create(null);
  1627. relative['ftp'] = 21;
  1628. relative['file'] = 0;
  1629. relative['gopher'] = 70;
  1630. relative['http'] = 80;
  1631. relative['https'] = 443;
  1632. relative['ws'] = 80;
  1633. relative['wss'] = 443;
  1634. var relativePathDotMapping = Object.create(null);
  1635. relativePathDotMapping['%2e'] = '.';
  1636. relativePathDotMapping['.%2e'] = '..';
  1637. relativePathDotMapping['%2e.'] = '..';
  1638. relativePathDotMapping['%2e%2e'] = '..';
  1639. function isRelativeScheme(scheme) {
  1640. return relative[scheme] !== undefined;
  1641. }
  1642. function invalid() {
  1643. clear.call(this);
  1644. this._isInvalid = true;
  1645. }
  1646. function IDNAToASCII(h) {
  1647. if ('' == h) {
  1648. invalid.call(this)
  1649. }
  1650. // XXX
  1651. return h.toLowerCase()
  1652. }
  1653. function percentEscape(c) {
  1654. var unicode = c.charCodeAt(0);
  1655. if (unicode > 0x20 &&
  1656. unicode < 0x7F &&
  1657. // " # < > ? `
  1658. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
  1659. ) {
  1660. return c;
  1661. }
  1662. return encodeURIComponent(c);
  1663. }
  1664. function percentEscapeQuery(c) {
  1665. // XXX This actually needs to encode c using encoding and then
  1666. // convert the bytes one-by-one.
  1667. var unicode = c.charCodeAt(0);
  1668. if (unicode > 0x20 &&
  1669. unicode < 0x7F &&
  1670. // " # < > ` (do not escape '?')
  1671. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1
  1672. ) {
  1673. return c;
  1674. }
  1675. return encodeURIComponent(c);
  1676. }
  1677. var EOF = undefined,
  1678. ALPHA = /[a-zA-Z]/,
  1679. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1680. function parse(input, stateOverride, base) {
  1681. function err(message) {
  1682. errors.push(message)
  1683. }
  1684. var state = stateOverride || 'scheme start',
  1685. cursor = 0,
  1686. buffer = '',
  1687. seenAt = false,
  1688. seenBracket = false,
  1689. errors = [];
  1690. loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
  1691. var c = input[cursor];
  1692. switch (state) {
  1693. case 'scheme start':
  1694. if (c && ALPHA.test(c)) {
  1695. buffer += c.toLowerCase(); // ASCII-safe
  1696. state = 'scheme';
  1697. } else if (!stateOverride) {
  1698. buffer = '';
  1699. state = 'no scheme';
  1700. continue;
  1701. } else {
  1702. err('Invalid scheme.');
  1703. break loop;
  1704. }
  1705. break;
  1706. case 'scheme':
  1707. if (c && ALPHANUMERIC.test(c)) {
  1708. buffer += c.toLowerCase(); // ASCII-safe
  1709. } else if (':' == c) {
  1710. this._scheme = buffer;
  1711. buffer = '';
  1712. if (stateOverride) {
  1713. break loop;
  1714. }
  1715. if (isRelativeScheme(this._scheme)) {
  1716. this._isRelative = true;
  1717. }
  1718. if ('file' == this._scheme) {
  1719. state = 'relative';
  1720. } else if (this._isRelative && base && base._scheme == this._scheme) {
  1721. state = 'relative or authority';
  1722. } else if (this._isRelative) {
  1723. state = 'authority first slash';
  1724. } else {
  1725. state = 'scheme data';
  1726. }
  1727. } else if (!stateOverride) {
  1728. buffer = '';
  1729. cursor = 0;
  1730. state = 'no scheme';
  1731. continue;
  1732. } else if (EOF == c) {
  1733. break loop;
  1734. } else {
  1735. err('Code point not allowed in scheme: ' + c)
  1736. break loop;
  1737. }
  1738. break;
  1739. case 'scheme data':
  1740. if ('?' == c) {
  1741. this._query = '?';
  1742. state = 'query';
  1743. } else if ('#' == c) {
  1744. this._fragment = '#';
  1745. state = 'fragment';
  1746. } else {
  1747. // XXX error handling
  1748. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  1749. this._schemeData += percentEscape(c);
  1750. }
  1751. }
  1752. break;
  1753. case 'no scheme':
  1754. if (!base || !(isRelativeScheme(base._scheme))) {
  1755. err('Missing scheme.');
  1756. invalid.call(this);
  1757. } else {
  1758. state = 'relative';
  1759. continue;
  1760. }
  1761. break;
  1762. case 'relative or authority':
  1763. if ('/' == c && '/' == input[cursor+1]) {
  1764. state = 'authority ignore slashes';
  1765. } else {
  1766. err('Expected /, got: ' + c);
  1767. state = 'relative';
  1768. continue
  1769. }
  1770. break;
  1771. case 'relative':
  1772. this._isRelative = true;
  1773. if ('file' != this._scheme)
  1774. this._scheme = base._scheme;
  1775. if (EOF == c) {
  1776. this._host = base._host;
  1777. this._port = base._port;
  1778. this._path = base._path.slice();
  1779. this._query = base._query;
  1780. this._username = base._username;
  1781. this._password = base._password;
  1782. break loop;
  1783. } else if ('/' == c || '\\' == c) {
  1784. if ('\\' == c)
  1785. err('\\ is an invalid code point.');
  1786. state = 'relative slash';
  1787. } else if ('?' == c) {
  1788. this._host = base._host;
  1789. this._port = base._port;
  1790. this._path = base._path.slice();
  1791. this._query = '?';
  1792. this._username = base._username;
  1793. this._password = base._password;
  1794. state = 'query';
  1795. } else if ('#' == c) {
  1796. this._host = base._host;
  1797. this._port = base._port;
  1798. this._path = base._path.slice();
  1799. this._query = base._query;
  1800. this._fragment = '#';
  1801. this._username = base._username;
  1802. this._password = base._password;
  1803. state = 'fragment';
  1804. } else {
  1805. var nextC = input[cursor+1]
  1806. var nextNextC = input[cursor+2]
  1807. if (
  1808. 'file' != this._scheme || !ALPHA.test(c) ||
  1809. (nextC != ':' && nextC != '|') ||
  1810. (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) {
  1811. this._host = base._host;
  1812. this._port = base._port;
  1813. this._username = base._username;
  1814. this._password = base._password;
  1815. this._path = base._path.slice();
  1816. this._path.pop();
  1817. }
  1818. state = 'relative path';
  1819. continue;
  1820. }
  1821. break;
  1822. case 'relative slash':
  1823. if ('/' == c || '\\' == c) {
  1824. if ('\\' == c) {
  1825. err('\\ is an invalid code point.');
  1826. }
  1827. if ('file' == this._scheme) {
  1828. state = 'file host';
  1829. } else {
  1830. state = 'authority ignore slashes';
  1831. }
  1832. } else {
  1833. if ('file' != this._scheme) {
  1834. this._host = base._host;
  1835. this._port = base._port;
  1836. this._username = base._username;
  1837. this._password = base._password;
  1838. }
  1839. state = 'relative path';
  1840. continue;
  1841. }
  1842. break;
  1843. case 'authority first slash':
  1844. if ('/' == c) {
  1845. state = 'authority second slash';
  1846. } else {
  1847. err("Expected '/', got: " + c);
  1848. state = 'authority ignore slashes';
  1849. continue;
  1850. }
  1851. break;
  1852. case 'authority second slash':
  1853. state = 'authority ignore slashes';
  1854. if ('/' != c) {
  1855. err("Expected '/', got: " + c);
  1856. continue;
  1857. }
  1858. break;
  1859. case 'authority ignore slashes':
  1860. if ('/' != c && '\\' != c) {
  1861. state = 'authority';
  1862. continue;
  1863. } else {
  1864. err('Expected authority, got: ' + c);
  1865. }
  1866. break;
  1867. case 'authority':
  1868. if ('@' == c) {
  1869. if (seenAt) {
  1870. err('@ already seen.');
  1871. buffer += '%40';
  1872. }
  1873. seenAt = true;
  1874. for (var i = 0; i < buffer.length; i++) {
  1875. var cp = buffer[i];
  1876. if ('\t' == cp || '\n' == cp || '\r' == cp) {
  1877. err('Invalid whitespace in authority.');
  1878. continue;
  1879. }
  1880. // XXX check URL code points
  1881. if (':' == cp && null === this._password) {
  1882. this._password = '';
  1883. continue;
  1884. }
  1885. var tempC = percentEscape(cp);
  1886. (null !== this._password) ? this._password += tempC : this._username += tempC;
  1887. }
  1888. buffer = '';
  1889. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1890. cursor -= buffer.length;
  1891. buffer = '';
  1892. state = 'host';
  1893. continue;
  1894. } else {
  1895. buffer += c;
  1896. }
  1897. break;
  1898. case 'file host':
  1899. if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1900. if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
  1901. state = 'relative path';
  1902. } else if (buffer.length == 0) {
  1903. state = 'relative path start';
  1904. } else {
  1905. this._host = IDNAToASCII.call(this, buffer);
  1906. buffer = '';
  1907. state = 'relative path start';
  1908. }
  1909. continue;
  1910. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1911. err('Invalid whitespace in file host.');
  1912. } else {
  1913. buffer += c;
  1914. }
  1915. break;
  1916. case 'host':
  1917. case 'hostname':
  1918. if (':' == c && !seenBracket) {
  1919. // XXX host parsing
  1920. this._host = IDNAToASCII.call(this, buffer);
  1921. buffer = '';
  1922. state = 'port';
  1923. if ('hostname' == stateOverride) {
  1924. break loop;
  1925. }
  1926. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  1927. this._host = IDNAToASCII.call(this, buffer);
  1928. buffer = '';
  1929. state = 'relative path start';
  1930. if (stateOverride) {
  1931. break loop;
  1932. }
  1933. continue;
  1934. } else if ('\t' != c && '\n' != c && '\r' != c) {
  1935. if ('[' == c) {
  1936. seenBracket = true;
  1937. } else if (']' == c) {
  1938. seenBracket = false;
  1939. }
  1940. buffer += c;
  1941. } else {
  1942. err('Invalid code point in host/hostname: ' + c);
  1943. }
  1944. break;
  1945. case 'port':
  1946. if (/[0-9]/.test(c)) {
  1947. buffer += c;
  1948. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
  1949. if ('' != buffer) {
  1950. var temp = parseInt(buffer, 10);
  1951. if (temp != relative[this._scheme]) {
  1952. this._port = temp + '';
  1953. }
  1954. buffer = '';
  1955. }
  1956. if (stateOverride) {
  1957. break loop;
  1958. }
  1959. state = 'relative path start';
  1960. continue;
  1961. } else if ('\t' == c || '\n' == c || '\r' == c) {
  1962. err('Invalid code point in port: ' + c);
  1963. } else {
  1964. invalid.call(this);
  1965. }
  1966. break;
  1967. case 'relative path start':
  1968. if ('\\' == c)
  1969. err("'\\' not allowed in path.");
  1970. state = 'relative path';
  1971. if ('/' != c && '\\' != c) {
  1972. continue;
  1973. }
  1974. break;
  1975. case 'relative path':
  1976. if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) {
  1977. if ('\\' == c) {
  1978. err('\\ not allowed in relative path.');
  1979. }
  1980. var tmp;
  1981. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1982. buffer = tmp;
  1983. }
  1984. if ('..' == buffer) {
  1985. this._path.pop();
  1986. if ('/' != c && '\\' != c) {
  1987. this._path.push('');
  1988. }
  1989. } else if ('.' == buffer && '/' != c && '\\' != c) {
  1990. this._path.push('');
  1991. } else if ('.' != buffer) {
  1992. if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
  1993. buffer = buffer[0] + ':';
  1994. }
  1995. this._path.push(buffer);
  1996. }
  1997. buffer = '';
  1998. if ('?' == c) {
  1999. this._query = '?';
  2000. state = 'query';
  2001. } else if ('#' == c) {
  2002. this._fragment = '#';
  2003. state = 'fragment';
  2004. }
  2005. } else if ('\t' != c && '\n' != c && '\r' != c) {
  2006. buffer += percentEscape(c);
  2007. }
  2008. break;
  2009. case 'query':
  2010. if (!stateOverride && '#' == c) {
  2011. this._fragment = '#';
  2012. state = 'fragment';
  2013. } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  2014. this._query += percentEscapeQuery(c);
  2015. }
  2016. break;
  2017. case 'fragment':
  2018. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  2019. this._fragment += c;
  2020. }
  2021. break;
  2022. }
  2023. cursor++;
  2024. }
  2025. }
  2026. function clear() {
  2027. this._scheme = '';
  2028. this._schemeData = '';
  2029. this._username = '';
  2030. this._password = null;
  2031. this._host = '';
  2032. this._port = '';
  2033. this._path = [];
  2034. this._query = '';
  2035. this._fragment = '';
  2036. this._isInvalid = false;
  2037. this._isRelative = false;
  2038. }
  2039. // Does not process domain names or IP addresses.
  2040. // Does not handle encoding for the query parameter.
  2041. function jURL(url, base /* , encoding */) {
  2042. if (base !== undefined && !(base instanceof jURL))
  2043. base = new jURL(String(base));
  2044. this._url = url;
  2045. clear.call(this);
  2046. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2047. // encoding = encoding || 'utf-8'
  2048. parse.call(this, input, null, base);
  2049. }
  2050. jURL.prototype = {
  2051. toString: function() {
  2052. return this.href;
  2053. },
  2054. get href() {
  2055. if (this._isInvalid)
  2056. return this._url;
  2057. var authority = '';
  2058. if ('' != this._username || null != this._password) {
  2059. authority = this._username +
  2060. (null != this._password ? ':' + this._password : '') + '@';
  2061. }
  2062. return this.protocol +
  2063. (this._isRelative ? '//' + authority + this.host : '') +
  2064. this.pathname + this._query + this._fragment;
  2065. },
  2066. set href(href) {
  2067. clear.call(this);
  2068. parse.call(this, href);
  2069. },
  2070. get protocol() {
  2071. return this._scheme + ':';
  2072. },
  2073. set protocol(protocol) {
  2074. if (this._isInvalid)
  2075. return;
  2076. parse.call(this, protocol + ':', 'scheme start');
  2077. },
  2078. get host() {
  2079. return this._isInvalid ? '' : this._port ?
  2080. this._host + ':' + this._port : this._host;
  2081. },
  2082. set host(host) {
  2083. if (this._isInvalid || !this._isRelative)
  2084. return;
  2085. parse.call(this, host, 'host');
  2086. },
  2087. get hostname() {
  2088. return this._host;
  2089. },
  2090. set hostname(hostname) {
  2091. if (this._isInvalid || !this._isRelative)
  2092. return;
  2093. parse.call(this, hostname, 'hostname');
  2094. },
  2095. get port() {
  2096. return this._port;
  2097. },
  2098. set port(port) {
  2099. if (this._isInvalid || !this._isRelative)
  2100. return;
  2101. parse.call(this, port, 'port');
  2102. },
  2103. get pathname() {
  2104. return this._isInvalid ? '' : this._isRelative ?
  2105. '/' + this._path.join('/') : this._schemeData;
  2106. },
  2107. set pathname(pathname) {
  2108. if (this._isInvalid || !this._isRelative)
  2109. return;
  2110. this._path = [];
  2111. parse.call(this, pathname, 'relative path start');
  2112. },
  2113. get search() {
  2114. return this._isInvalid || !this._query || '?' == this._query ?
  2115. '' : this._query;
  2116. },
  2117. set search(search) {
  2118. if (this._isInvalid || !this._isRelative)
  2119. return;
  2120. this._query = '?';
  2121. if ('?' == search[0])
  2122. search = search.slice(1);
  2123. parse.call(this, search, 'query');
  2124. },
  2125. get hash() {
  2126. return this._isInvalid || !this._fragment || '#' == this._fragment ?
  2127. '' : this._fragment;
  2128. },
  2129. set hash(hash) {
  2130. if (this._isInvalid)
  2131. return;
  2132. this._fragment = '#';
  2133. if ('#' == hash[0])
  2134. hash = hash.slice(1);
  2135. parse.call(this, hash, 'fragment');
  2136. },
  2137. get origin() {
  2138. var host;
  2139. if (this._isInvalid || !this._scheme) {
  2140. return '';
  2141. }
  2142. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2143. // Gecko throws error for "data://"
  2144. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2145. // Gecko returns String("") for file: mailto:
  2146. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2147. switch (this._scheme) {
  2148. case 'data':
  2149. case 'file':
  2150. case 'javascript':
  2151. case 'mailto':
  2152. return 'null';
  2153. }
  2154. host = this.host;
  2155. if (!host) {
  2156. return '';
  2157. }
  2158. return this._scheme + '://' + host;
  2159. }
  2160. };
  2161. // Copy over the static methods
  2162. var OriginalURL = scope.URL;
  2163. if (OriginalURL) {
  2164. jURL.createObjectURL = function(blob) {
  2165. // IE extension allows a second optional options argument.
  2166. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2167. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2168. };
  2169. jURL.revokeObjectURL = function(url) {
  2170. OriginalURL.revokeObjectURL(url);
  2171. };
  2172. }
  2173. scope.URL = jURL;
  2174. /* jshint ignore:end */
  2175. })(globalScope);
  2176. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2177. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2178. exports.OPS = OPS;
  2179. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2180. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2181. exports.AnnotationFlag = AnnotationFlag;
  2182. exports.AnnotationType = AnnotationType;
  2183. exports.FontType = FontType;
  2184. exports.ImageKind = ImageKind;
  2185. exports.InvalidPDFException = InvalidPDFException;
  2186. exports.LinkTarget = LinkTarget;
  2187. exports.LinkTargetStringMap = LinkTargetStringMap;
  2188. exports.MessageHandler = MessageHandler;
  2189. exports.MissingDataException = MissingDataException;
  2190. exports.MissingPDFException = MissingPDFException;
  2191. exports.NotImplementedException = NotImplementedException;
  2192. exports.PasswordException = PasswordException;
  2193. exports.PasswordResponses = PasswordResponses;
  2194. exports.StatTimer = StatTimer;
  2195. exports.StreamType = StreamType;
  2196. exports.TextRenderingMode = TextRenderingMode;
  2197. exports.UnexpectedResponseException = UnexpectedResponseException;
  2198. exports.UnknownErrorException = UnknownErrorException;
  2199. exports.Util = Util;
  2200. exports.XRefParseException = XRefParseException;
  2201. exports.assert = assert;
  2202. exports.bytesToString = bytesToString;
  2203. exports.combineUrl = combineUrl;
  2204. exports.createPromiseCapability = createPromiseCapability;
  2205. exports.deprecated = deprecated;
  2206. exports.error = error;
  2207. exports.info = info;
  2208. exports.isArray = isArray;
  2209. exports.isArrayBuffer = isArrayBuffer;
  2210. exports.isBool = isBool;
  2211. exports.isEmptyObj = isEmptyObj;
  2212. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2213. exports.isInt = isInt;
  2214. exports.isNum = isNum;
  2215. exports.isString = isString;
  2216. exports.isValidUrl = isValidUrl;
  2217. exports.addLinkAttributes = addLinkAttributes;
  2218. exports.loadJpegStream = loadJpegStream;
  2219. exports.log2 = log2;
  2220. exports.readInt8 = readInt8;
  2221. exports.readUint16 = readUint16;
  2222. exports.readUint32 = readUint32;
  2223. exports.removeNullCharacters = removeNullCharacters;
  2224. exports.shadow = shadow;
  2225. exports.string32 = string32;
  2226. exports.stringToBytes = stringToBytes;
  2227. exports.stringToPDFString = stringToPDFString;
  2228. exports.stringToUTF8String = stringToUTF8String;
  2229. exports.utf8StringToString = utf8StringToString;
  2230. exports.warn = warn;
  2231. }));
  2232. (function (root, factory) {
  2233. {
  2234. factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
  2235. root.pdfjsDisplayDOMUtils);
  2236. }
  2237. }(this, function (exports, sharedUtil, displayDOMUtils) {
  2238. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  2239. var AnnotationType = sharedUtil.AnnotationType;
  2240. var Util = sharedUtil.Util;
  2241. var addLinkAttributes = sharedUtil.addLinkAttributes;
  2242. var warn = sharedUtil.warn;
  2243. var CustomStyle = displayDOMUtils.CustomStyle;
  2244. /**
  2245. * @typedef {Object} AnnotationElementParameters
  2246. * @property {Object} data
  2247. * @property {HTMLDivElement} layer
  2248. * @property {PDFPage} page
  2249. * @property {PageViewport} viewport
  2250. * @property {IPDFLinkService} linkService
  2251. */
  2252. /**
  2253. * @class
  2254. * @alias AnnotationElementFactory
  2255. */
  2256. function AnnotationElementFactory() {}
  2257. AnnotationElementFactory.prototype =
  2258. /** @lends AnnotationElementFactory.prototype */ {
  2259. /**
  2260. * @param {AnnotationElementParameters} parameters
  2261. * @returns {AnnotationElement}
  2262. */
  2263. create: function AnnotationElementFactory_create(parameters) {
  2264. var subtype = parameters.data.annotationType;
  2265. switch (subtype) {
  2266. case AnnotationType.LINK:
  2267. return new LinkAnnotationElement(parameters);
  2268. case AnnotationType.TEXT:
  2269. return new TextAnnotationElement(parameters);
  2270. case AnnotationType.WIDGET:
  2271. return new WidgetAnnotationElement(parameters);
  2272. case AnnotationType.POPUP:
  2273. return new PopupAnnotationElement(parameters);
  2274. case AnnotationType.HIGHLIGHT:
  2275. return new HighlightAnnotationElement(parameters);
  2276. case AnnotationType.UNDERLINE:
  2277. return new UnderlineAnnotationElement(parameters);
  2278. case AnnotationType.SQUIGGLY:
  2279. return new SquigglyAnnotationElement(parameters);
  2280. case AnnotationType.STRIKEOUT:
  2281. return new StrikeOutAnnotationElement(parameters);
  2282. default:
  2283. throw new Error('Unimplemented annotation type "' + subtype + '"');
  2284. }
  2285. }
  2286. };
  2287. /**
  2288. * @class
  2289. * @alias AnnotationElement
  2290. */
  2291. var AnnotationElement = (function AnnotationElementClosure() {
  2292. function AnnotationElement(parameters) {
  2293. this.data = parameters.data;
  2294. this.layer = parameters.layer;
  2295. this.page = parameters.page;
  2296. this.viewport = parameters.viewport;
  2297. this.linkService = parameters.linkService;
  2298. this.container = this._createContainer();
  2299. }
  2300. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
  2301. /**
  2302. * Create an empty container for the annotation's HTML element.
  2303. *
  2304. * @private
  2305. * @memberof AnnotationElement
  2306. * @returns {HTMLSectionElement}
  2307. */
  2308. _createContainer: function AnnotationElement_createContainer() {
  2309. var data = this.data, page = this.page, viewport = this.viewport;
  2310. var container = document.createElement('section');
  2311. var width = data.rect[2] - data.rect[0];
  2312. var height = data.rect[3] - data.rect[1];
  2313. container.setAttribute('data-annotation-id', data.id);
  2314. // Do *not* modify `data.rect`, since that will corrupt the annotation
  2315. // position on subsequent calls to `_createContainer` (see issue 6804).
  2316. var rect = Util.normalizeRect([
  2317. data.rect[0],
  2318. page.view[3] - data.rect[1] + page.view[1],
  2319. data.rect[2],
  2320. page.view[3] - data.rect[3] + page.view[1]
  2321. ]);
  2322. CustomStyle.setProp('transform', container,
  2323. 'matrix(' + viewport.transform.join(',') + ')');
  2324. CustomStyle.setProp('transformOrigin', container,
  2325. -rect[0] + 'px ' + -rect[1] + 'px');
  2326. if (data.borderStyle.width > 0) {
  2327. container.style.borderWidth = data.borderStyle.width + 'px';
  2328. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  2329. // Underline styles only have a bottom border, so we do not need
  2330. // to adjust for all borders. This yields a similar result as
  2331. // Adobe Acrobat/Reader.
  2332. width = width - 2 * data.borderStyle.width;
  2333. height = height - 2 * data.borderStyle.width;
  2334. }
  2335. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  2336. var verticalRadius = data.borderStyle.verticalCornerRadius;
  2337. if (horizontalRadius > 0 || verticalRadius > 0) {
  2338. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  2339. CustomStyle.setProp('borderRadius', container, radius);
  2340. }
  2341. switch (data.borderStyle.style) {
  2342. case AnnotationBorderStyleType.SOLID:
  2343. container.style.borderStyle = 'solid';
  2344. break;
  2345. case AnnotationBorderStyleType.DASHED:
  2346. container.style.borderStyle = 'dashed';
  2347. break;
  2348. case AnnotationBorderStyleType.BEVELED:
  2349. warn('Unimplemented border style: beveled');
  2350. break;
  2351. case AnnotationBorderStyleType.INSET:
  2352. warn('Unimplemented border style: inset');
  2353. break;
  2354. case AnnotationBorderStyleType.UNDERLINE:
  2355. container.style.borderBottomStyle = 'solid';
  2356. break;
  2357. default:
  2358. break;
  2359. }
  2360. if (data.color) {
  2361. container.style.borderColor =
  2362. Util.makeCssRgb(data.color[0] | 0,
  2363. data.color[1] | 0,
  2364. data.color[2] | 0);
  2365. } else {
  2366. // Transparent (invisible) border, so do not draw it at all.
  2367. container.style.borderWidth = 0;
  2368. }
  2369. }
  2370. container.style.left = rect[0] + 'px';
  2371. container.style.top = rect[1] + 'px';
  2372. container.style.width = width + 'px';
  2373. container.style.height = height + 'px';
  2374. return container;
  2375. },
  2376. /**
  2377. * Render the annotation's HTML element in the empty container.
  2378. *
  2379. * @public
  2380. * @memberof AnnotationElement
  2381. */
  2382. render: function AnnotationElement_render() {
  2383. throw new Error('Abstract method AnnotationElement.render called');
  2384. }
  2385. };
  2386. return AnnotationElement;
  2387. })();
  2388. /**
  2389. * @class
  2390. * @alias LinkAnnotationElement
  2391. */
  2392. var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
  2393. function LinkAnnotationElement(parameters) {
  2394. AnnotationElement.call(this, parameters);
  2395. }
  2396. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  2397. /**
  2398. * Render the link annotation's HTML element in the empty container.
  2399. *
  2400. * @public
  2401. * @memberof LinkAnnotationElement
  2402. * @returns {HTMLSectionElement}
  2403. */
  2404. render: function LinkAnnotationElement_render() {
  2405. this.container.className = 'linkAnnotation';
  2406. var link = document.createElement('a');
  2407. addLinkAttributes(link, { url: this.data.url });
  2408. if (!this.data.url) {
  2409. if (this.data.action) {
  2410. this._bindNamedAction(link, this.data.action);
  2411. } else {
  2412. this._bindLink(link, ('dest' in this.data) ? this.data.dest : null);
  2413. }
  2414. }
  2415. this.container.appendChild(link);
  2416. return this.container;
  2417. },
  2418. /**
  2419. * Bind internal links to the link element.
  2420. *
  2421. * @private
  2422. * @param {Object} link
  2423. * @param {Object} destination
  2424. * @memberof LinkAnnotationElement
  2425. */
  2426. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  2427. var self = this;
  2428. link.href = this.linkService.getDestinationHash(destination);
  2429. link.onclick = function() {
  2430. if (destination) {
  2431. self.linkService.navigateTo(destination);
  2432. }
  2433. return false;
  2434. };
  2435. if (destination) {
  2436. link.className = 'internalLink';
  2437. }
  2438. },
  2439. /**
  2440. * Bind named actions to the link element.
  2441. *
  2442. * @private
  2443. * @param {Object} link
  2444. * @param {Object} action
  2445. * @memberof LinkAnnotationElement
  2446. */
  2447. _bindNamedAction:
  2448. function LinkAnnotationElement_bindNamedAction(link, action) {
  2449. var self = this;
  2450. link.href = this.linkService.getAnchorUrl('');
  2451. link.onclick = function() {
  2452. self.linkService.executeNamedAction(action);
  2453. return false;
  2454. };
  2455. link.className = 'internalLink';
  2456. }
  2457. });
  2458. return LinkAnnotationElement;
  2459. })();
  2460. /**
  2461. * @class
  2462. * @alias TextAnnotationElement
  2463. */
  2464. var TextAnnotationElement = (function TextAnnotationElementClosure() {
  2465. function TextAnnotationElement(parameters) {
  2466. AnnotationElement.call(this, parameters);
  2467. }
  2468. Util.inherit(TextAnnotationElement, AnnotationElement, {
  2469. /**
  2470. * Render the text annotation's HTML element in the empty container.
  2471. *
  2472. * @public
  2473. * @memberof TextAnnotationElement
  2474. * @returns {HTMLSectionElement}
  2475. */
  2476. render: function TextAnnotationElement_render() {
  2477. this.container.className = 'textAnnotation';
  2478. var image = document.createElement('img');
  2479. image.style.height = this.container.style.height;
  2480. image.style.width = this.container.style.width;
  2481. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  2482. this.data.name.toLowerCase() + '.svg';
  2483. image.alt = '[{{type}} Annotation]';
  2484. image.dataset.l10nId = 'text_annotation_type';
  2485. image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
  2486. if (!this.data.hasPopup) {
  2487. var popupElement = new PopupElement({
  2488. container: this.container,
  2489. trigger: image,
  2490. color: this.data.color,
  2491. title: this.data.title,
  2492. contents: this.data.contents,
  2493. hideWrapper: true
  2494. });
  2495. var popup = popupElement.render();
  2496. // Position the popup next to the Text annotation's container.
  2497. popup.style.left = image.style.width;
  2498. this.container.appendChild(popup);
  2499. }
  2500. this.container.appendChild(image);
  2501. return this.container;
  2502. }
  2503. });
  2504. return TextAnnotationElement;
  2505. })();
  2506. /**
  2507. * @class
  2508. * @alias WidgetAnnotationElement
  2509. */
  2510. var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
  2511. function WidgetAnnotationElement(parameters) {
  2512. AnnotationElement.call(this, parameters);
  2513. }
  2514. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  2515. /**
  2516. * Render the widget annotation's HTML element in the empty container.
  2517. *
  2518. * @public
  2519. * @memberof WidgetAnnotationElement
  2520. * @returns {HTMLSectionElement}
  2521. */
  2522. render: function WidgetAnnotationElement_render() {
  2523. var content = document.createElement('div');
  2524. content.textContent = this.data.fieldValue;
  2525. var textAlignment = this.data.textAlignment;
  2526. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  2527. content.style.verticalAlign = 'middle';
  2528. content.style.display = 'table-cell';
  2529. var font = (this.data.fontRefName ?
  2530. this.page.commonObjs.getData(this.data.fontRefName) : null);
  2531. this._setTextStyle(content, font);
  2532. this.container.appendChild(content);
  2533. return this.container;
  2534. },
  2535. /**
  2536. * Apply text styles to the text in the element.
  2537. *
  2538. * @private
  2539. * @param {HTMLDivElement} element
  2540. * @param {Object} font
  2541. * @memberof WidgetAnnotationElement
  2542. */
  2543. _setTextStyle:
  2544. function WidgetAnnotationElement_setTextStyle(element, font) {
  2545. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  2546. var style = element.style;
  2547. style.fontSize = this.data.fontSize + 'px';
  2548. style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
  2549. if (!font) {
  2550. return;
  2551. }
  2552. style.fontWeight = (font.black ?
  2553. (font.bold ? '900' : 'bold') :
  2554. (font.bold ? 'bold' : 'normal'));
  2555. style.fontStyle = (font.italic ? 'italic' : 'normal');
  2556. // Use a reasonable default font if the font doesn't specify a fallback.
  2557. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  2558. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  2559. style.fontFamily = fontFamily + fallbackName;
  2560. }
  2561. });
  2562. return WidgetAnnotationElement;
  2563. })();
  2564. /**
  2565. * @class
  2566. * @alias PopupAnnotationElement
  2567. */
  2568. var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
  2569. function PopupAnnotationElement(parameters) {
  2570. AnnotationElement.call(this, parameters);
  2571. }
  2572. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  2573. /**
  2574. * Render the popup annotation's HTML element in the empty container.
  2575. *
  2576. * @public
  2577. * @memberof PopupAnnotationElement
  2578. * @returns {HTMLSectionElement}
  2579. */
  2580. render: function PopupAnnotationElement_render() {
  2581. this.container.className = 'popupAnnotation';
  2582. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  2583. var parentElement = this.layer.querySelector(selector);
  2584. if (!parentElement) {
  2585. return this.container;
  2586. }
  2587. var popup = new PopupElement({
  2588. container: this.container,
  2589. trigger: parentElement,
  2590. color: this.data.color,
  2591. title: this.data.title,
  2592. contents: this.data.contents
  2593. });
  2594. // Position the popup next to the parent annotation's container.
  2595. // PDF viewers ignore a popup annotation's rectangle.
  2596. var parentLeft = parseFloat(parentElement.style.left);
  2597. var parentWidth = parseFloat(parentElement.style.width);
  2598. CustomStyle.setProp('transformOrigin', this.container,
  2599. -(parentLeft + parentWidth) + 'px -' +
  2600. parentElement.style.top);
  2601. this.container.style.left = (parentLeft + parentWidth) + 'px';
  2602. this.container.appendChild(popup.render());
  2603. return this.container;
  2604. }
  2605. });
  2606. return PopupAnnotationElement;
  2607. })();
  2608. /**
  2609. * @class
  2610. * @alias PopupElement
  2611. */
  2612. var PopupElement = (function PopupElementClosure() {
  2613. var BACKGROUND_ENLIGHT = 0.7;
  2614. function PopupElement(parameters) {
  2615. this.container = parameters.container;
  2616. this.trigger = parameters.trigger;
  2617. this.color = parameters.color;
  2618. this.title = parameters.title;
  2619. this.contents = parameters.contents;
  2620. this.hideWrapper = parameters.hideWrapper || false;
  2621. this.pinned = false;
  2622. }
  2623. PopupElement.prototype = /** @lends PopupElement.prototype */ {
  2624. /**
  2625. * Render the popup's HTML element.
  2626. *
  2627. * @public
  2628. * @memberof PopupElement
  2629. * @returns {HTMLSectionElement}
  2630. */
  2631. render: function PopupElement_render() {
  2632. var wrapper = document.createElement('div');
  2633. wrapper.className = 'popupWrapper';
  2634. // For Popup annotations we hide the entire section because it contains
  2635. // only the popup. However, for Text annotations without a separate Popup
  2636. // annotation, we cannot hide the entire container as the image would
  2637. // disappear too. In that special case, hiding the wrapper suffices.
  2638. this.hideElement = (this.hideWrapper ? wrapper : this.container);
  2639. this.hideElement.setAttribute('hidden', true);
  2640. var popup = document.createElement('div');
  2641. popup.className = 'popup';
  2642. var color = this.color;
  2643. if (color) {
  2644. // Enlighten the color.
  2645. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  2646. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  2647. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  2648. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  2649. }
  2650. var contents = this._formatContents(this.contents);
  2651. var title = document.createElement('h1');
  2652. title.textContent = this.title;
  2653. // Attach the event listeners to the trigger element.
  2654. this.trigger.addEventListener('click', this._toggle.bind(this));
  2655. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  2656. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  2657. popup.addEventListener('click', this._hide.bind(this, true));
  2658. popup.appendChild(title);
  2659. popup.appendChild(contents);
  2660. wrapper.appendChild(popup);
  2661. return wrapper;
  2662. },
  2663. /**
  2664. * Format the contents of the popup by adding newlines where necessary.
  2665. *
  2666. * @private
  2667. * @param {string} contents
  2668. * @memberof PopupElement
  2669. * @returns {HTMLParagraphElement}
  2670. */
  2671. _formatContents: function PopupElement_formatContents(contents) {
  2672. var p = document.createElement('p');
  2673. var lines = contents.split(/(?:\r\n?|\n)/);
  2674. for (var i = 0, ii = lines.length; i < ii; ++i) {
  2675. var line = lines[i];
  2676. p.appendChild(document.createTextNode(line));
  2677. if (i < (ii - 1)) {
  2678. p.appendChild(document.createElement('br'));
  2679. }
  2680. }
  2681. return p;
  2682. },
  2683. /**
  2684. * Toggle the visibility of the popup.
  2685. *
  2686. * @private
  2687. * @memberof PopupElement
  2688. */
  2689. _toggle: function PopupElement_toggle() {
  2690. if (this.pinned) {
  2691. this._hide(true);
  2692. } else {
  2693. this._show(true);
  2694. }
  2695. },
  2696. /**
  2697. * Show the popup.
  2698. *
  2699. * @private
  2700. * @param {boolean} pin
  2701. * @memberof PopupElement
  2702. */
  2703. _show: function PopupElement_show(pin) {
  2704. if (pin) {
  2705. this.pinned = true;
  2706. }
  2707. if (this.hideElement.hasAttribute('hidden')) {
  2708. this.hideElement.removeAttribute('hidden');
  2709. this.container.style.zIndex += 1;
  2710. }
  2711. },
  2712. /**
  2713. * Hide the popup.
  2714. *
  2715. * @private
  2716. * @param {boolean} unpin
  2717. * @memberof PopupElement
  2718. */
  2719. _hide: function PopupElement_hide(unpin) {
  2720. if (unpin) {
  2721. this.pinned = false;
  2722. }
  2723. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  2724. this.hideElement.setAttribute('hidden', true);
  2725. this.container.style.zIndex -= 1;
  2726. }
  2727. }
  2728. };
  2729. return PopupElement;
  2730. })();
  2731. /**
  2732. * @class
  2733. * @alias HighlightAnnotationElement
  2734. */
  2735. var HighlightAnnotationElement = (
  2736. function HighlightAnnotationElementClosure() {
  2737. function HighlightAnnotationElement(parameters) {
  2738. AnnotationElement.call(this, parameters);
  2739. }
  2740. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  2741. /**
  2742. * Render the highlight annotation's HTML element in the empty container.
  2743. *
  2744. * @public
  2745. * @memberof HighlightAnnotationElement
  2746. * @returns {HTMLSectionElement}
  2747. */
  2748. render: function HighlightAnnotationElement_render() {
  2749. this.container.className = 'highlightAnnotation';
  2750. return this.container;
  2751. }
  2752. });
  2753. return HighlightAnnotationElement;
  2754. })();
  2755. /**
  2756. * @class
  2757. * @alias UnderlineAnnotationElement
  2758. */
  2759. var UnderlineAnnotationElement = (
  2760. function UnderlineAnnotationElementClosure() {
  2761. function UnderlineAnnotationElement(parameters) {
  2762. AnnotationElement.call(this, parameters);
  2763. }
  2764. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  2765. /**
  2766. * Render the underline annotation's HTML element in the empty container.
  2767. *
  2768. * @public
  2769. * @memberof UnderlineAnnotationElement
  2770. * @returns {HTMLSectionElement}
  2771. */
  2772. render: function UnderlineAnnotationElement_render() {
  2773. this.container.className = 'underlineAnnotation';
  2774. return this.container;
  2775. }
  2776. });
  2777. return UnderlineAnnotationElement;
  2778. })();
  2779. /**
  2780. * @class
  2781. * @alias SquigglyAnnotationElement
  2782. */
  2783. var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
  2784. function SquigglyAnnotationElement(parameters) {
  2785. AnnotationElement.call(this, parameters);
  2786. }
  2787. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  2788. /**
  2789. * Render the squiggly annotation's HTML element in the empty container.
  2790. *
  2791. * @public
  2792. * @memberof SquigglyAnnotationElement
  2793. * @returns {HTMLSectionElement}
  2794. */
  2795. render: function SquigglyAnnotationElement_render() {
  2796. this.container.className = 'squigglyAnnotation';
  2797. return this.container;
  2798. }
  2799. });
  2800. return SquigglyAnnotationElement;
  2801. })();
  2802. /**
  2803. * @class
  2804. * @alias StrikeOutAnnotationElement
  2805. */
  2806. var StrikeOutAnnotationElement = (
  2807. function StrikeOutAnnotationElementClosure() {
  2808. function StrikeOutAnnotationElement(parameters) {
  2809. AnnotationElement.call(this, parameters);
  2810. }
  2811. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  2812. /**
  2813. * Render the strikeout annotation's HTML element in the empty container.
  2814. *
  2815. * @public
  2816. * @memberof StrikeOutAnnotationElement
  2817. * @returns {HTMLSectionElement}
  2818. */
  2819. render: function StrikeOutAnnotationElement_render() {
  2820. this.container.className = 'strikeoutAnnotation';
  2821. return this.container;
  2822. }
  2823. });
  2824. return StrikeOutAnnotationElement;
  2825. })();
  2826. /**
  2827. * @typedef {Object} AnnotationLayerParameters
  2828. * @property {PageViewport} viewport
  2829. * @property {HTMLDivElement} div
  2830. * @property {Array} annotations
  2831. * @property {PDFPage} page
  2832. * @property {IPDFLinkService} linkService
  2833. */
  2834. /**
  2835. * @class
  2836. * @alias AnnotationLayer
  2837. */
  2838. var AnnotationLayer = (function AnnotationLayerClosure() {
  2839. return {
  2840. /**
  2841. * Render a new annotation layer with all annotation elements.
  2842. *
  2843. * @public
  2844. * @param {AnnotationLayerParameters} parameters
  2845. * @memberof AnnotationLayer
  2846. */
  2847. render: function AnnotationLayer_render(parameters) {
  2848. var annotationElementFactory = new AnnotationElementFactory();
  2849. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  2850. var data = parameters.annotations[i];
  2851. if (!data || !data.hasHtml) {
  2852. continue;
  2853. }
  2854. var properties = {
  2855. data: data,
  2856. layer: parameters.div,
  2857. page: parameters.page,
  2858. viewport: parameters.viewport,
  2859. linkService: parameters.linkService
  2860. };
  2861. var element = annotationElementFactory.create(properties);
  2862. parameters.div.appendChild(element.render());
  2863. }
  2864. },
  2865. /**
  2866. * Update the annotation elements on existing annotation layer.
  2867. *
  2868. * @public
  2869. * @param {AnnotationLayerParameters} parameters
  2870. * @memberof AnnotationLayer
  2871. */
  2872. update: function AnnotationLayer_update(parameters) {
  2873. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  2874. var data = parameters.annotations[i];
  2875. var element = parameters.div.querySelector(
  2876. '[data-annotation-id="' + data.id + '"]');
  2877. if (element) {
  2878. CustomStyle.setProp('transform', element,
  2879. 'matrix(' + parameters.viewport.transform.join(',') + ')');
  2880. }
  2881. }
  2882. parameters.div.removeAttribute('hidden');
  2883. }
  2884. };
  2885. })();
  2886. PDFJS.AnnotationLayer = AnnotationLayer;
  2887. exports.AnnotationLayer = AnnotationLayer;
  2888. }));
  2889. (function (root, factory) {
  2890. {
  2891. factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil,
  2892. root.pdfjsSharedGlobal);
  2893. }
  2894. }(this, function (exports, sharedUtil, sharedGlobal) {
  2895. var assert = sharedUtil.assert;
  2896. var bytesToString = sharedUtil.bytesToString;
  2897. var string32 = sharedUtil.string32;
  2898. var shadow = sharedUtil.shadow;
  2899. var warn = sharedUtil.warn;
  2900. var PDFJS = sharedGlobal.PDFJS;
  2901. var globalScope = sharedGlobal.globalScope;
  2902. var isWorker = sharedGlobal.isWorker;
  2903. function FontLoader(docId) {
  2904. this.docId = docId;
  2905. this.styleElement = null;
  2906. this.nativeFontFaces = [];
  2907. this.loadTestFontId = 0;
  2908. this.loadingContext = {
  2909. requests: [],
  2910. nextRequestId: 0
  2911. };
  2912. }
  2913. FontLoader.prototype = {
  2914. insertRule: function fontLoaderInsertRule(rule) {
  2915. var styleElement = this.styleElement;
  2916. if (!styleElement) {
  2917. styleElement = this.styleElement = document.createElement('style');
  2918. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2919. document.documentElement.getElementsByTagName('head')[0].appendChild(
  2920. styleElement);
  2921. }
  2922. var styleSheet = styleElement.sheet;
  2923. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2924. },
  2925. clear: function fontLoaderClear() {
  2926. var styleElement = this.styleElement;
  2927. if (styleElement) {
  2928. styleElement.parentNode.removeChild(styleElement);
  2929. styleElement = this.styleElement = null;
  2930. }
  2931. this.nativeFontFaces.forEach(function(nativeFontFace) {
  2932. document.fonts.delete(nativeFontFace);
  2933. });
  2934. this.nativeFontFaces.length = 0;
  2935. },
  2936. get loadTestFont() {
  2937. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2938. // height.
  2939. return shadow(this, 'loadTestFont', atob(
  2940. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  2941. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  2942. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  2943. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  2944. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  2945. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  2946. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  2947. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  2948. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  2949. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  2950. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  2951. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  2952. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  2953. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2954. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2955. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  2956. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  2957. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  2958. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  2959. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  2960. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  2961. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  2962. ));
  2963. },
  2964. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  2965. this.nativeFontFaces.push(nativeFontFace);
  2966. document.fonts.add(nativeFontFace);
  2967. },
  2968. bind: function fontLoaderBind(fonts, callback) {
  2969. assert(!isWorker, 'bind() shall be called from main thread');
  2970. var rules = [];
  2971. var fontsToLoad = [];
  2972. var fontLoadPromises = [];
  2973. var getNativeFontPromise = function(nativeFontFace) {
  2974. // Return a promise that is always fulfilled, even when the font fails to
  2975. // load.
  2976. return nativeFontFace.loaded.catch(function(e) {
  2977. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2978. });
  2979. };
  2980. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2981. var font = fonts[i];
  2982. // Add the font to the DOM only once or skip if the font
  2983. // is already loaded.
  2984. if (font.attached || font.loading === false) {
  2985. continue;
  2986. }
  2987. font.attached = true;
  2988. if (FontLoader.isFontLoadingAPISupported) {
  2989. var nativeFontFace = font.createNativeFontFace();
  2990. if (nativeFontFace) {
  2991. this.addNativeFontFace(nativeFontFace);
  2992. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2993. }
  2994. } else {
  2995. var rule = font.createFontFaceRule();
  2996. if (rule) {
  2997. this.insertRule(rule);
  2998. rules.push(rule);
  2999. fontsToLoad.push(font);
  3000. }
  3001. }
  3002. }
  3003. var request = this.queueLoadingCallback(callback);
  3004. if (FontLoader.isFontLoadingAPISupported) {
  3005. Promise.all(fontLoadPromises).then(function() {
  3006. request.complete();
  3007. });
  3008. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  3009. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  3010. } else {
  3011. request.complete();
  3012. }
  3013. },
  3014. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  3015. function LoadLoader_completeRequest() {
  3016. assert(!request.end, 'completeRequest() cannot be called twice');
  3017. request.end = Date.now();
  3018. // sending all completed requests in order how they were queued
  3019. while (context.requests.length > 0 && context.requests[0].end) {
  3020. var otherRequest = context.requests.shift();
  3021. setTimeout(otherRequest.callback, 0);
  3022. }
  3023. }
  3024. var context = this.loadingContext;
  3025. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  3026. var request = {
  3027. id: requestId,
  3028. complete: LoadLoader_completeRequest,
  3029. callback: callback,
  3030. started: Date.now()
  3031. };
  3032. context.requests.push(request);
  3033. return request;
  3034. },
  3035. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  3036. fonts,
  3037. request) {
  3038. /** Hack begin */
  3039. // There's currently no event when a font has finished downloading so the
  3040. // following code is a dirty hack to 'guess' when a font is
  3041. // ready. It's assumed fonts are loaded in order, so add a known test
  3042. // font after the desired fonts and then test for the loading of that
  3043. // test font.
  3044. function int32(data, offset) {
  3045. return (data.charCodeAt(offset) << 24) |
  3046. (data.charCodeAt(offset + 1) << 16) |
  3047. (data.charCodeAt(offset + 2) << 8) |
  3048. (data.charCodeAt(offset + 3) & 0xff);
  3049. }
  3050. function spliceString(s, offset, remove, insert) {
  3051. var chunk1 = s.substr(0, offset);
  3052. var chunk2 = s.substr(offset + remove);
  3053. return chunk1 + insert + chunk2;
  3054. }
  3055. var i, ii;
  3056. var canvas = document.createElement('canvas');
  3057. canvas.width = 1;
  3058. canvas.height = 1;
  3059. var ctx = canvas.getContext('2d');
  3060. var called = 0;
  3061. function isFontReady(name, callback) {
  3062. called++;
  3063. // With setTimeout clamping this gives the font ~100ms to load.
  3064. if(called > 30) {
  3065. warn('Load test font never loaded.');
  3066. callback();
  3067. return;
  3068. }
  3069. ctx.font = '30px ' + name;
  3070. ctx.fillText('.', 0, 20);
  3071. var imageData = ctx.getImageData(0, 0, 1, 1);
  3072. if (imageData.data[3] > 0) {
  3073. callback();
  3074. return;
  3075. }
  3076. setTimeout(isFontReady.bind(null, name, callback));
  3077. }
  3078. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  3079. // Chromium seems to cache fonts based on a hash of the actual font data,
  3080. // so the font must be modified for each load test else it will appear to
  3081. // be loaded already.
  3082. // TODO: This could maybe be made faster by avoiding the btoa of the full
  3083. // font by splitting it in chunks before hand and padding the font id.
  3084. var data = this.loadTestFont;
  3085. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  3086. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  3087. loadTestFontId);
  3088. // CFF checksum is important for IE, adjusting it
  3089. var CFF_CHECKSUM_OFFSET = 16;
  3090. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  3091. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  3092. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  3093. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  3094. }
  3095. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  3096. checksum = (checksum - XXXX_VALUE +
  3097. int32(loadTestFontId + 'XXX', i)) | 0;
  3098. }
  3099. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  3100. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  3101. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  3102. url + '}';
  3103. this.insertRule(rule);
  3104. var names = [];
  3105. for (i = 0, ii = fonts.length; i < ii; i++) {
  3106. names.push(fonts[i].loadedName);
  3107. }
  3108. names.push(loadTestFontId);
  3109. var div = document.createElement('div');
  3110. div.setAttribute('style',
  3111. 'visibility: hidden;' +
  3112. 'width: 10px; height: 10px;' +
  3113. 'position: absolute; top: 0px; left: 0px;');
  3114. for (i = 0, ii = names.length; i < ii; ++i) {
  3115. var span = document.createElement('span');
  3116. span.textContent = 'Hi';
  3117. span.style.fontFamily = names[i];
  3118. div.appendChild(span);
  3119. }
  3120. document.body.appendChild(div);
  3121. isFontReady(loadTestFontId, function() {
  3122. document.body.removeChild(div);
  3123. request.complete();
  3124. });
  3125. /** Hack end */
  3126. }
  3127. };
  3128. FontLoader.isFontLoadingAPISupported = (!isWorker &&
  3129. typeof document !== 'undefined' && !!document.fonts);
  3130. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  3131. get: function () {
  3132. var supported = false;
  3133. // User agent string sniffing is bad, but there is no reliable way to tell
  3134. // if font is fully loaded and ready to be used with canvas.
  3135. var userAgent = window.navigator.userAgent;
  3136. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  3137. if (m && m[1] >= 14) {
  3138. supported = true;
  3139. }
  3140. // TODO other browsers
  3141. if (userAgent === 'node') {
  3142. supported = true;
  3143. }
  3144. return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
  3145. },
  3146. enumerable: true,
  3147. configurable: true
  3148. });
  3149. var FontFaceObject = (function FontFaceObjectClosure() {
  3150. function FontFaceObject(translatedData) {
  3151. this.compiledGlyphs = {};
  3152. // importing translated data
  3153. for (var i in translatedData) {
  3154. this[i] = translatedData[i];
  3155. }
  3156. }
  3157. Object.defineProperty(FontFaceObject, 'isEvalSupported', {
  3158. get: function () {
  3159. var evalSupport = false;
  3160. if (PDFJS.isEvalSupported) {
  3161. try {
  3162. /* jshint evil: true */
  3163. new Function('');
  3164. evalSupport = true;
  3165. } catch (e) {}
  3166. }
  3167. return shadow(this, 'isEvalSupported', evalSupport);
  3168. },
  3169. enumerable: true,
  3170. configurable: true
  3171. });
  3172. FontFaceObject.prototype = {
  3173. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  3174. if (!this.data) {
  3175. return null;
  3176. }
  3177. if (PDFJS.disableFontFace) {
  3178. this.disableFontFace = true;
  3179. return null;
  3180. }
  3181. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  3182. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  3183. globalScope['FontInspector'].enabled) {
  3184. globalScope['FontInspector'].fontAdded(this);
  3185. }
  3186. return nativeFontFace;
  3187. },
  3188. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  3189. if (!this.data) {
  3190. return null;
  3191. }
  3192. if (PDFJS.disableFontFace) {
  3193. this.disableFontFace = true;
  3194. return null;
  3195. }
  3196. var data = bytesToString(new Uint8Array(this.data));
  3197. var fontName = this.loadedName;
  3198. // Add the font-face rule to the document
  3199. var url = ('url(data:' + this.mimetype + ';base64,' +
  3200. window.btoa(data) + ');');
  3201. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  3202. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  3203. globalScope['FontInspector'].enabled) {
  3204. globalScope['FontInspector'].fontAdded(this, url);
  3205. }
  3206. return rule;
  3207. },
  3208. getPathGenerator:
  3209. function FontFaceObject_getPathGenerator(objs, character) {
  3210. if (!(character in this.compiledGlyphs)) {
  3211. var cmds = objs.get(this.loadedName + '_path_' + character);
  3212. var current, i, len;
  3213. // If we can, compile cmds into JS for MAXIMUM SPEED
  3214. if (FontFaceObject.isEvalSupported) {
  3215. var args, js = '';
  3216. for (i = 0, len = cmds.length; i < len; i++) {
  3217. current = cmds[i];
  3218. if (current.args !== undefined) {
  3219. args = current.args.join(',');
  3220. } else {
  3221. args = '';
  3222. }
  3223. js += 'c.' + current.cmd + '(' + args + ');\n';
  3224. }
  3225. /* jshint -W054 */
  3226. this.compiledGlyphs[character] = new Function('c', 'size', js);
  3227. } else {
  3228. // But fall back on using Function.prototype.apply() if we're
  3229. // blocked from using eval() for whatever reason (like CSP policies)
  3230. this.compiledGlyphs[character] = function(c, size) {
  3231. for (i = 0, len = cmds.length; i < len; i++) {
  3232. current = cmds[i];
  3233. if (current.cmd === 'scale') {
  3234. current.args = [size, -size];
  3235. }
  3236. c[current.cmd].apply(c, current.args);
  3237. }
  3238. };
  3239. }
  3240. }
  3241. return this.compiledGlyphs[character];
  3242. }
  3243. };
  3244. return FontFaceObject;
  3245. })();
  3246. exports.FontFaceObject = FontFaceObject;
  3247. exports.FontLoader = FontLoader;
  3248. }));
  3249. (function (root, factory) {
  3250. {
  3251. factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
  3252. }
  3253. }(this, function (exports, sharedUtil) {
  3254. var error = sharedUtil.error;
  3255. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  3256. function fixMetadata(meta) {
  3257. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  3258. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  3259. function(code, d1, d2, d3) {
  3260. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  3261. });
  3262. var chars = '';
  3263. for (var i = 0; i < bytes.length; i += 2) {
  3264. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  3265. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  3266. code !== 38 && false ? String.fromCharCode(code) :
  3267. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  3268. }
  3269. return '>' + chars;
  3270. });
  3271. }
  3272. function Metadata(meta) {
  3273. if (typeof meta === 'string') {
  3274. // Ghostscript produces invalid metadata
  3275. meta = fixMetadata(meta);
  3276. var parser = new DOMParser();
  3277. meta = parser.parseFromString(meta, 'application/xml');
  3278. } else if (!(meta instanceof Document)) {
  3279. error('Metadata: Invalid metadata object');
  3280. }
  3281. this.metaDocument = meta;
  3282. this.metadata = {};
  3283. this.parse();
  3284. }
  3285. Metadata.prototype = {
  3286. parse: function Metadata_parse() {
  3287. var doc = this.metaDocument;
  3288. var rdf = doc.documentElement;
  3289. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  3290. rdf = rdf.firstChild;
  3291. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3292. rdf = rdf.nextSibling;
  3293. }
  3294. }
  3295. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  3296. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3297. return;
  3298. }
  3299. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3300. for (i = 0, length = children.length; i < length; i++) {
  3301. desc = children[i];
  3302. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3303. continue;
  3304. }
  3305. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3306. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3307. entry = desc.childNodes[ii];
  3308. name = entry.nodeName.toLowerCase();
  3309. this.metadata[name] = entry.textContent.trim();
  3310. }
  3311. }
  3312. }
  3313. },
  3314. get: function Metadata_get(name) {
  3315. return this.metadata[name] || null;
  3316. },
  3317. has: function Metadata_has(name) {
  3318. return typeof this.metadata[name] !== 'undefined';
  3319. }
  3320. };
  3321. return Metadata;
  3322. })();
  3323. exports.Metadata = Metadata;
  3324. }));
  3325. (function (root, factory) {
  3326. {
  3327. factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
  3328. }
  3329. }(this, function (exports, sharedUtil) {
  3330. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3331. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3332. var ImageKind = sharedUtil.ImageKind;
  3333. var OPS = sharedUtil.OPS;
  3334. var Util = sharedUtil.Util;
  3335. var isNum = sharedUtil.isNum;
  3336. var isArray = sharedUtil.isArray;
  3337. var warn = sharedUtil.warn;
  3338. var SVG_DEFAULTS = {
  3339. fontStyle: 'normal',
  3340. fontWeight: 'normal',
  3341. fillColor: '#000000'
  3342. };
  3343. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  3344. var PNG_HEADER =
  3345. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  3346. var CHUNK_WRAPPER_SIZE = 12;
  3347. var crcTable = new Int32Array(256);
  3348. for (var i = 0; i < 256; i++) {
  3349. var c = i;
  3350. for (var h = 0; h < 8; h++) {
  3351. if (c & 1) {
  3352. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  3353. } else {
  3354. c = (c >> 1) & 0x7fffffff;
  3355. }
  3356. }
  3357. crcTable[i] = c;
  3358. }
  3359. function crc32(data, start, end) {
  3360. var crc = -1;
  3361. for (var i = start; i < end; i++) {
  3362. var a = (crc ^ data[i]) & 0xff;
  3363. var b = crcTable[a];
  3364. crc = (crc >>> 8) ^ b;
  3365. }
  3366. return crc ^ -1;
  3367. }
  3368. function writePngChunk(type, body, data, offset) {
  3369. var p = offset;
  3370. var len = body.length;
  3371. data[p] = len >> 24 & 0xff;
  3372. data[p + 1] = len >> 16 & 0xff;
  3373. data[p + 2] = len >> 8 & 0xff;
  3374. data[p + 3] = len & 0xff;
  3375. p += 4;
  3376. data[p] = type.charCodeAt(0) & 0xff;
  3377. data[p + 1] = type.charCodeAt(1) & 0xff;
  3378. data[p + 2] = type.charCodeAt(2) & 0xff;
  3379. data[p + 3] = type.charCodeAt(3) & 0xff;
  3380. p += 4;
  3381. data.set(body, p);
  3382. p += body.length;
  3383. var crc = crc32(data, offset + 4, p);
  3384. data[p] = crc >> 24 & 0xff;
  3385. data[p + 1] = crc >> 16 & 0xff;
  3386. data[p + 2] = crc >> 8 & 0xff;
  3387. data[p + 3] = crc & 0xff;
  3388. }
  3389. function adler32(data, start, end) {
  3390. var a = 1;
  3391. var b = 0;
  3392. for (var i = start; i < end; ++i) {
  3393. a = (a + (data[i] & 0xff)) % 65521;
  3394. b = (b + a) % 65521;
  3395. }
  3396. return (b << 16) | a;
  3397. }
  3398. function encode(imgData, kind) {
  3399. var width = imgData.width;
  3400. var height = imgData.height;
  3401. var bitDepth, colorType, lineSize;
  3402. var bytes = imgData.data;
  3403. switch (kind) {
  3404. case ImageKind.GRAYSCALE_1BPP:
  3405. colorType = 0;
  3406. bitDepth = 1;
  3407. lineSize = (width + 7) >> 3;
  3408. break;
  3409. case ImageKind.RGB_24BPP:
  3410. colorType = 2;
  3411. bitDepth = 8;
  3412. lineSize = width * 3;
  3413. break;
  3414. case ImageKind.RGBA_32BPP:
  3415. colorType = 6;
  3416. bitDepth = 8;
  3417. lineSize = width * 4;
  3418. break;
  3419. default:
  3420. throw new Error('invalid format');
  3421. }
  3422. // prefix every row with predictor 0
  3423. var literals = new Uint8Array((1 + lineSize) * height);
  3424. var offsetLiterals = 0, offsetBytes = 0;
  3425. var y, i;
  3426. for (y = 0; y < height; ++y) {
  3427. literals[offsetLiterals++] = 0; // no prediction
  3428. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  3429. offsetLiterals);
  3430. offsetBytes += lineSize;
  3431. offsetLiterals += lineSize;
  3432. }
  3433. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3434. // inverting for B/W
  3435. offsetLiterals = 0;
  3436. for (y = 0; y < height; y++) {
  3437. offsetLiterals++; // skipping predictor
  3438. for (i = 0; i < lineSize; i++) {
  3439. literals[offsetLiterals++] ^= 0xFF;
  3440. }
  3441. }
  3442. }
  3443. var ihdr = new Uint8Array([
  3444. width >> 24 & 0xff,
  3445. width >> 16 & 0xff,
  3446. width >> 8 & 0xff,
  3447. width & 0xff,
  3448. height >> 24 & 0xff,
  3449. height >> 16 & 0xff,
  3450. height >> 8 & 0xff,
  3451. height & 0xff,
  3452. bitDepth, // bit depth
  3453. colorType, // color type
  3454. 0x00, // compression method
  3455. 0x00, // filter method
  3456. 0x00 // interlace method
  3457. ]);
  3458. var len = literals.length;
  3459. var maxBlockLength = 0xFFFF;
  3460. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3461. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3462. var pi = 0;
  3463. idat[pi++] = 0x78; // compression method and flags
  3464. idat[pi++] = 0x9c; // flags
  3465. var pos = 0;
  3466. while (len > maxBlockLength) {
  3467. // writing non-final DEFLATE blocks type 0 and length of 65535
  3468. idat[pi++] = 0x00;
  3469. idat[pi++] = 0xff;
  3470. idat[pi++] = 0xff;
  3471. idat[pi++] = 0x00;
  3472. idat[pi++] = 0x00;
  3473. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3474. pi += maxBlockLength;
  3475. pos += maxBlockLength;
  3476. len -= maxBlockLength;
  3477. }
  3478. // writing non-final DEFLATE blocks type 0
  3479. idat[pi++] = 0x01;
  3480. idat[pi++] = len & 0xff;
  3481. idat[pi++] = len >> 8 & 0xff;
  3482. idat[pi++] = (~len & 0xffff) & 0xff;
  3483. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3484. idat.set(literals.subarray(pos), pi);
  3485. pi += literals.length - pos;
  3486. var adler = adler32(literals, 0, literals.length); // checksum
  3487. idat[pi++] = adler >> 24 & 0xff;
  3488. idat[pi++] = adler >> 16 & 0xff;
  3489. idat[pi++] = adler >> 8 & 0xff;
  3490. idat[pi++] = adler & 0xff;
  3491. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3492. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  3493. ihdr.length + idat.length;
  3494. var data = new Uint8Array(pngLength);
  3495. var offset = 0;
  3496. data.set(PNG_HEADER, offset);
  3497. offset += PNG_HEADER.length;
  3498. writePngChunk('IHDR', ihdr, data, offset);
  3499. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3500. writePngChunk('IDATA', idat, data, offset);
  3501. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3502. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3503. return PDFJS.createObjectURL(data, 'image/png');
  3504. }
  3505. return function convertImgDataToPng(imgData) {
  3506. var kind = (imgData.kind === undefined ?
  3507. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  3508. return encode(imgData, kind);
  3509. };
  3510. })();
  3511. var SVGExtraState = (function SVGExtraStateClosure() {
  3512. function SVGExtraState() {
  3513. this.fontSizeScale = 1;
  3514. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3515. this.fontSize = 0;
  3516. this.textMatrix = IDENTITY_MATRIX;
  3517. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3518. this.leading = 0;
  3519. // Current point (in user coordinates)
  3520. this.x = 0;
  3521. this.y = 0;
  3522. // Start of text line (in text coordinates)
  3523. this.lineX = 0;
  3524. this.lineY = 0;
  3525. // Character and word spacing
  3526. this.charSpacing = 0;
  3527. this.wordSpacing = 0;
  3528. this.textHScale = 1;
  3529. this.textRise = 0;
  3530. // Default foreground and background colors
  3531. this.fillColor = SVG_DEFAULTS.fillColor;
  3532. this.strokeColor = '#000000';
  3533. this.fillAlpha = 1;
  3534. this.strokeAlpha = 1;
  3535. this.lineWidth = 1;
  3536. this.lineJoin = '';
  3537. this.lineCap = '';
  3538. this.miterLimit = 0;
  3539. this.dashArray = [];
  3540. this.dashPhase = 0;
  3541. this.dependencies = [];
  3542. // Clipping
  3543. this.clipId = '';
  3544. this.pendingClip = false;
  3545. this.maskId = '';
  3546. }
  3547. SVGExtraState.prototype = {
  3548. clone: function SVGExtraState_clone() {
  3549. return Object.create(this);
  3550. },
  3551. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3552. this.x = x;
  3553. this.y = y;
  3554. }
  3555. };
  3556. return SVGExtraState;
  3557. })();
  3558. var SVGGraphics = (function SVGGraphicsClosure() {
  3559. function createScratchSVG(width, height) {
  3560. var NS = 'http://www.w3.org/2000/svg';
  3561. var svg = document.createElementNS(NS, 'svg:svg');
  3562. svg.setAttributeNS(null, 'version', '1.1');
  3563. svg.setAttributeNS(null, 'width', width + 'px');
  3564. svg.setAttributeNS(null, 'height', height + 'px');
  3565. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3566. return svg;
  3567. }
  3568. function opListToTree(opList) {
  3569. var opTree = [];
  3570. var tmp = [];
  3571. var opListLen = opList.length;
  3572. for (var x = 0; x < opListLen; x++) {
  3573. if (opList[x].fn === 'save') {
  3574. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  3575. tmp.push(opTree);
  3576. opTree = opTree[opTree.length - 1].items;
  3577. continue;
  3578. }
  3579. if(opList[x].fn === 'restore') {
  3580. opTree = tmp.pop();
  3581. } else {
  3582. opTree.push(opList[x]);
  3583. }
  3584. }
  3585. return opTree;
  3586. }
  3587. /**
  3588. * Formats float number.
  3589. * @param value {number} number to format.
  3590. * @returns {string}
  3591. */
  3592. function pf(value) {
  3593. if (value === (value | 0)) { // integer number
  3594. return value.toString();
  3595. }
  3596. var s = value.toFixed(10);
  3597. var i = s.length - 1;
  3598. if (s[i] !== '0') {
  3599. return s;
  3600. }
  3601. // removing trailing zeros
  3602. do {
  3603. i--;
  3604. } while (s[i] === '0');
  3605. return s.substr(0, s[i] === '.' ? i : i + 1);
  3606. }
  3607. /**
  3608. * Formats transform matrix. The standard rotation, scale and translate
  3609. * matrices are replaced by their shorter forms, and for identity matrix
  3610. * returns empty string to save the memory.
  3611. * @param m {Array} matrix to format.
  3612. * @returns {string}
  3613. */
  3614. function pm(m) {
  3615. if (m[4] === 0 && m[5] === 0) {
  3616. if (m[1] === 0 && m[2] === 0) {
  3617. if (m[0] === 1 && m[3] === 1) {
  3618. return '';
  3619. }
  3620. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3621. }
  3622. if (m[0] === m[3] && m[1] === -m[2]) {
  3623. var a = Math.acos(m[0]) * 180 / Math.PI;
  3624. return 'rotate(' + pf(a) + ')';
  3625. }
  3626. } else {
  3627. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3628. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3629. }
  3630. }
  3631. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  3632. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3633. }
  3634. function SVGGraphics(commonObjs, objs) {
  3635. this.current = new SVGExtraState();
  3636. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  3637. this.transformStack = [];
  3638. this.extraStack = [];
  3639. this.commonObjs = commonObjs;
  3640. this.objs = objs;
  3641. this.pendingEOFill = false;
  3642. this.embedFonts = false;
  3643. this.embeddedFonts = {};
  3644. this.cssStyle = null;
  3645. }
  3646. var NS = 'http://www.w3.org/2000/svg';
  3647. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3648. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3649. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3650. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3651. var clipCount = 0;
  3652. var maskCount = 0;
  3653. SVGGraphics.prototype = {
  3654. save: function SVGGraphics_save() {
  3655. this.transformStack.push(this.transformMatrix);
  3656. var old = this.current;
  3657. this.extraStack.push(old);
  3658. this.current = old.clone();
  3659. },
  3660. restore: function SVGGraphics_restore() {
  3661. this.transformMatrix = this.transformStack.pop();
  3662. this.current = this.extraStack.pop();
  3663. this.tgrp = document.createElementNS(NS, 'svg:g');
  3664. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3665. this.pgrp.appendChild(this.tgrp);
  3666. },
  3667. group: function SVGGraphics_group(items) {
  3668. this.save();
  3669. this.executeOpTree(items);
  3670. this.restore();
  3671. },
  3672. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3673. var fnArray = operatorList.fnArray;
  3674. var fnArrayLen = fnArray.length;
  3675. var argsArray = operatorList.argsArray;
  3676. var self = this;
  3677. for (var i = 0; i < fnArrayLen; i++) {
  3678. if (OPS.dependency === fnArray[i]) {
  3679. var deps = argsArray[i];
  3680. for (var n = 0, nn = deps.length; n < nn; n++) {
  3681. var obj = deps[n];
  3682. var common = obj.substring(0, 2) === 'g_';
  3683. var promise;
  3684. if (common) {
  3685. promise = new Promise(function(resolve) {
  3686. self.commonObjs.get(obj, resolve);
  3687. });
  3688. } else {
  3689. promise = new Promise(function(resolve) {
  3690. self.objs.get(obj, resolve);
  3691. });
  3692. }
  3693. this.current.dependencies.push(promise);
  3694. }
  3695. }
  3696. }
  3697. return Promise.all(this.current.dependencies);
  3698. },
  3699. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3700. var transformMatrix = [a, b, c, d, e, f];
  3701. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  3702. transformMatrix);
  3703. this.tgrp = document.createElementNS(NS, 'svg:g');
  3704. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3705. },
  3706. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3707. this.svg = createScratchSVG(viewport.width, viewport.height);
  3708. this.viewport = viewport;
  3709. return this.loadDependencies(operatorList).then(function () {
  3710. this.transformMatrix = IDENTITY_MATRIX;
  3711. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  3712. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3713. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  3714. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3715. this.defs = document.createElementNS(NS, 'svg:defs');
  3716. this.pgrp.appendChild(this.defs);
  3717. this.pgrp.appendChild(this.tgrp);
  3718. this.svg.appendChild(this.pgrp);
  3719. var opTree = this.convertOpList(operatorList);
  3720. this.executeOpTree(opTree);
  3721. return this.svg;
  3722. }.bind(this));
  3723. },
  3724. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3725. var argsArray = operatorList.argsArray;
  3726. var fnArray = operatorList.fnArray;
  3727. var fnArrayLen = fnArray.length;
  3728. var REVOPS = [];
  3729. var opList = [];
  3730. for (var op in OPS) {
  3731. REVOPS[OPS[op]] = op;
  3732. }
  3733. for (var x = 0; x < fnArrayLen; x++) {
  3734. var fnId = fnArray[x];
  3735. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  3736. }
  3737. return opListToTree(opList);
  3738. },
  3739. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3740. var opTreeLen = opTree.length;
  3741. for(var x = 0; x < opTreeLen; x++) {
  3742. var fn = opTree[x].fn;
  3743. var fnId = opTree[x].fnId;
  3744. var args = opTree[x].args;
  3745. switch (fnId | 0) {
  3746. case OPS.beginText:
  3747. this.beginText();
  3748. break;
  3749. case OPS.setLeading:
  3750. this.setLeading(args);
  3751. break;
  3752. case OPS.setLeadingMoveText:
  3753. this.setLeadingMoveText(args[0], args[1]);
  3754. break;
  3755. case OPS.setFont:
  3756. this.setFont(args);
  3757. break;
  3758. case OPS.showText:
  3759. this.showText(args[0]);
  3760. break;
  3761. case OPS.showSpacedText:
  3762. this.showText(args[0]);
  3763. break;
  3764. case OPS.endText:
  3765. this.endText();
  3766. break;
  3767. case OPS.moveText:
  3768. this.moveText(args[0], args[1]);
  3769. break;
  3770. case OPS.setCharSpacing:
  3771. this.setCharSpacing(args[0]);
  3772. break;
  3773. case OPS.setWordSpacing:
  3774. this.setWordSpacing(args[0]);
  3775. break;
  3776. case OPS.setHScale:
  3777. this.setHScale(args[0]);
  3778. break;
  3779. case OPS.setTextMatrix:
  3780. this.setTextMatrix(args[0], args[1], args[2],
  3781. args[3], args[4], args[5]);
  3782. break;
  3783. case OPS.setLineWidth:
  3784. this.setLineWidth(args[0]);
  3785. break;
  3786. case OPS.setLineJoin:
  3787. this.setLineJoin(args[0]);
  3788. break;
  3789. case OPS.setLineCap:
  3790. this.setLineCap(args[0]);
  3791. break;
  3792. case OPS.setMiterLimit:
  3793. this.setMiterLimit(args[0]);
  3794. break;
  3795. case OPS.setFillRGBColor:
  3796. this.setFillRGBColor(args[0], args[1], args[2]);
  3797. break;
  3798. case OPS.setStrokeRGBColor:
  3799. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3800. break;
  3801. case OPS.setDash:
  3802. this.setDash(args[0], args[1]);
  3803. break;
  3804. case OPS.setGState:
  3805. this.setGState(args[0]);
  3806. break;
  3807. case OPS.fill:
  3808. this.fill();
  3809. break;
  3810. case OPS.eoFill:
  3811. this.eoFill();
  3812. break;
  3813. case OPS.stroke:
  3814. this.stroke();
  3815. break;
  3816. case OPS.fillStroke:
  3817. this.fillStroke();
  3818. break;
  3819. case OPS.eoFillStroke:
  3820. this.eoFillStroke();
  3821. break;
  3822. case OPS.clip:
  3823. this.clip('nonzero');
  3824. break;
  3825. case OPS.eoClip:
  3826. this.clip('evenodd');
  3827. break;
  3828. case OPS.paintSolidColorImageMask:
  3829. this.paintSolidColorImageMask();
  3830. break;
  3831. case OPS.paintJpegXObject:
  3832. this.paintJpegXObject(args[0], args[1], args[2]);
  3833. break;
  3834. case OPS.paintImageXObject:
  3835. this.paintImageXObject(args[0]);
  3836. break;
  3837. case OPS.paintInlineImageXObject:
  3838. this.paintInlineImageXObject(args[0]);
  3839. break;
  3840. case OPS.paintImageMaskXObject:
  3841. this.paintImageMaskXObject(args[0]);
  3842. break;
  3843. case OPS.paintFormXObjectBegin:
  3844. this.paintFormXObjectBegin(args[0], args[1]);
  3845. break;
  3846. case OPS.paintFormXObjectEnd:
  3847. this.paintFormXObjectEnd();
  3848. break;
  3849. case OPS.closePath:
  3850. this.closePath();
  3851. break;
  3852. case OPS.closeStroke:
  3853. this.closeStroke();
  3854. break;
  3855. case OPS.closeFillStroke:
  3856. this.closeFillStroke();
  3857. break;
  3858. case OPS.nextLine:
  3859. this.nextLine();
  3860. break;
  3861. case OPS.transform:
  3862. this.transform(args[0], args[1], args[2], args[3],
  3863. args[4], args[5]);
  3864. break;
  3865. case OPS.constructPath:
  3866. this.constructPath(args[0], args[1]);
  3867. break;
  3868. case OPS.endPath:
  3869. this.endPath();
  3870. break;
  3871. case 92:
  3872. this.group(opTree[x].items);
  3873. break;
  3874. default:
  3875. warn('Unimplemented method '+ fn);
  3876. break;
  3877. }
  3878. }
  3879. },
  3880. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3881. this.current.wordSpacing = wordSpacing;
  3882. },
  3883. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3884. this.current.charSpacing = charSpacing;
  3885. },
  3886. nextLine: function SVGGraphics_nextLine() {
  3887. this.moveText(0, this.current.leading);
  3888. },
  3889. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3890. var current = this.current;
  3891. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  3892. this.current.x = this.current.lineX = 0;
  3893. this.current.y = this.current.lineY = 0;
  3894. current.xcoords = [];
  3895. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3896. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3897. current.tspan.setAttributeNS(null, 'font-size',
  3898. pf(current.fontSize) + 'px');
  3899. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3900. current.txtElement = document.createElementNS(NS, 'svg:text');
  3901. current.txtElement.appendChild(current.tspan);
  3902. },
  3903. beginText: function SVGGraphics_beginText() {
  3904. this.current.x = this.current.lineX = 0;
  3905. this.current.y = this.current.lineY = 0;
  3906. this.current.textMatrix = IDENTITY_MATRIX;
  3907. this.current.lineMatrix = IDENTITY_MATRIX;
  3908. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3909. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3910. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3911. this.current.xcoords = [];
  3912. },
  3913. moveText: function SVGGraphics_moveText(x, y) {
  3914. var current = this.current;
  3915. this.current.x = this.current.lineX += x;
  3916. this.current.y = this.current.lineY += y;
  3917. current.xcoords = [];
  3918. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3919. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3920. current.tspan.setAttributeNS(null, 'font-size',
  3921. pf(current.fontSize) + 'px');
  3922. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3923. },
  3924. showText: function SVGGraphics_showText(glyphs) {
  3925. var current = this.current;
  3926. var font = current.font;
  3927. var fontSize = current.fontSize;
  3928. if (fontSize === 0) {
  3929. return;
  3930. }
  3931. var charSpacing = current.charSpacing;
  3932. var wordSpacing = current.wordSpacing;
  3933. var fontDirection = current.fontDirection;
  3934. var textHScale = current.textHScale * fontDirection;
  3935. var glyphsLength = glyphs.length;
  3936. var vertical = font.vertical;
  3937. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3938. var x = 0, i;
  3939. for (i = 0; i < glyphsLength; ++i) {
  3940. var glyph = glyphs[i];
  3941. if (glyph === null) {
  3942. // word break
  3943. x += fontDirection * wordSpacing;
  3944. continue;
  3945. } else if (isNum(glyph)) {
  3946. x += -glyph * fontSize * 0.001;
  3947. continue;
  3948. }
  3949. current.xcoords.push(current.x + x * textHScale);
  3950. var width = glyph.width;
  3951. var character = glyph.fontChar;
  3952. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3953. x += charWidth;
  3954. current.tspan.textContent += character;
  3955. }
  3956. if (vertical) {
  3957. current.y -= x * textHScale;
  3958. } else {
  3959. current.x += x * textHScale;
  3960. }
  3961. current.tspan.setAttributeNS(null, 'x',
  3962. current.xcoords.map(pf).join(' '));
  3963. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3964. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3965. current.tspan.setAttributeNS(null, 'font-size',
  3966. pf(current.fontSize) + 'px');
  3967. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3968. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3969. }
  3970. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3971. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3972. }
  3973. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3974. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3975. }
  3976. current.txtElement.setAttributeNS(null, 'transform',
  3977. pm(current.textMatrix) +
  3978. ' scale(1, -1)' );
  3979. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3980. current.txtElement.appendChild(current.tspan);
  3981. current.txtgrp.appendChild(current.txtElement);
  3982. this.tgrp.appendChild(current.txtElement);
  3983. },
  3984. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3985. this.setLeading(-y);
  3986. this.moveText(x, y);
  3987. },
  3988. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3989. if (!this.cssStyle) {
  3990. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3991. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3992. this.defs.appendChild(this.cssStyle);
  3993. }
  3994. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  3995. this.cssStyle.textContent +=
  3996. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  3997. ' src: url(' + url + '); }\n';
  3998. },
  3999. setFont: function SVGGraphics_setFont(details) {
  4000. var current = this.current;
  4001. var fontObj = this.commonObjs.get(details[0]);
  4002. var size = details[1];
  4003. this.current.font = fontObj;
  4004. if (this.embedFonts && fontObj.data &&
  4005. !this.embeddedFonts[fontObj.loadedName]) {
  4006. this.addFontStyle(fontObj);
  4007. this.embeddedFonts[fontObj.loadedName] = fontObj;
  4008. }
  4009. current.fontMatrix = (fontObj.fontMatrix ?
  4010. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4011. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  4012. (fontObj.bold ? 'bold' : 'normal');
  4013. var italic = fontObj.italic ? 'italic' : 'normal';
  4014. if (size < 0) {
  4015. size = -size;
  4016. current.fontDirection = -1;
  4017. } else {
  4018. current.fontDirection = 1;
  4019. }
  4020. current.fontSize = size;
  4021. current.fontFamily = fontObj.loadedName;
  4022. current.fontWeight = bold;
  4023. current.fontStyle = italic;
  4024. current.tspan = document.createElementNS(NS, 'svg:tspan');
  4025. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  4026. current.xcoords = [];
  4027. },
  4028. endText: function SVGGraphics_endText() {
  4029. if (this.current.pendingClip) {
  4030. this.cgrp.appendChild(this.tgrp);
  4031. this.pgrp.appendChild(this.cgrp);
  4032. } else {
  4033. this.pgrp.appendChild(this.tgrp);
  4034. }
  4035. this.tgrp = document.createElementNS(NS, 'svg:g');
  4036. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4037. },
  4038. // Path properties
  4039. setLineWidth: function SVGGraphics_setLineWidth(width) {
  4040. this.current.lineWidth = width;
  4041. },
  4042. setLineCap: function SVGGraphics_setLineCap(style) {
  4043. this.current.lineCap = LINE_CAP_STYLES[style];
  4044. },
  4045. setLineJoin: function SVGGraphics_setLineJoin(style) {
  4046. this.current.lineJoin = LINE_JOIN_STYLES[style];
  4047. },
  4048. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  4049. this.current.miterLimit = limit;
  4050. },
  4051. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  4052. var color = Util.makeCssRgb(r, g, b);
  4053. this.current.strokeColor = color;
  4054. },
  4055. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  4056. var color = Util.makeCssRgb(r, g, b);
  4057. this.current.fillColor = color;
  4058. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  4059. this.current.xcoords = [];
  4060. },
  4061. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  4062. this.current.dashArray = dashArray;
  4063. this.current.dashPhase = dashPhase;
  4064. },
  4065. constructPath: function SVGGraphics_constructPath(ops, args) {
  4066. var current = this.current;
  4067. var x = current.x, y = current.y;
  4068. current.path = document.createElementNS(NS, 'svg:path');
  4069. var d = [];
  4070. var opLength = ops.length;
  4071. for (var i = 0, j = 0; i < opLength; i++) {
  4072. switch (ops[i] | 0) {
  4073. case OPS.rectangle:
  4074. x = args[j++];
  4075. y = args[j++];
  4076. var width = args[j++];
  4077. var height = args[j++];
  4078. var xw = x + width;
  4079. var yh = y + height;
  4080. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  4081. 'L', pf(x), pf(yh), 'Z');
  4082. break;
  4083. case OPS.moveTo:
  4084. x = args[j++];
  4085. y = args[j++];
  4086. d.push('M', pf(x), pf(y));
  4087. break;
  4088. case OPS.lineTo:
  4089. x = args[j++];
  4090. y = args[j++];
  4091. d.push('L', pf(x) , pf(y));
  4092. break;
  4093. case OPS.curveTo:
  4094. x = args[j + 4];
  4095. y = args[j + 5];
  4096. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  4097. pf(args[j + 3]), pf(x), pf(y));
  4098. j += 6;
  4099. break;
  4100. case OPS.curveTo2:
  4101. x = args[j + 2];
  4102. y = args[j + 3];
  4103. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  4104. pf(args[j + 2]), pf(args[j + 3]));
  4105. j += 4;
  4106. break;
  4107. case OPS.curveTo3:
  4108. x = args[j + 2];
  4109. y = args[j + 3];
  4110. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  4111. pf(x), pf(y));
  4112. j += 4;
  4113. break;
  4114. case OPS.closePath:
  4115. d.push('Z');
  4116. break;
  4117. }
  4118. }
  4119. current.path.setAttributeNS(null, 'd', d.join(' '));
  4120. current.path.setAttributeNS(null, 'stroke-miterlimit',
  4121. pf(current.miterLimit));
  4122. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  4123. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  4124. current.path.setAttributeNS(null, 'stroke-width',
  4125. pf(current.lineWidth) + 'px');
  4126. current.path.setAttributeNS(null, 'stroke-dasharray',
  4127. current.dashArray.map(pf).join(' '));
  4128. current.path.setAttributeNS(null, 'stroke-dashoffset',
  4129. pf(current.dashPhase) + 'px');
  4130. current.path.setAttributeNS(null, 'fill', 'none');
  4131. this.tgrp.appendChild(current.path);
  4132. if (current.pendingClip) {
  4133. this.cgrp.appendChild(this.tgrp);
  4134. this.pgrp.appendChild(this.cgrp);
  4135. } else {
  4136. this.pgrp.appendChild(this.tgrp);
  4137. }
  4138. // Saving a reference in current.element so that it can be addressed
  4139. // in 'fill' and 'stroke'
  4140. current.element = current.path;
  4141. current.setCurrentPoint(x, y);
  4142. },
  4143. endPath: function SVGGraphics_endPath() {
  4144. var current = this.current;
  4145. if (current.pendingClip) {
  4146. this.cgrp.appendChild(this.tgrp);
  4147. this.pgrp.appendChild(this.cgrp);
  4148. } else {
  4149. this.pgrp.appendChild(this.tgrp);
  4150. }
  4151. this.tgrp = document.createElementNS(NS, 'svg:g');
  4152. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4153. },
  4154. clip: function SVGGraphics_clip(type) {
  4155. var current = this.current;
  4156. // Add current path to clipping path
  4157. current.clipId = 'clippath' + clipCount;
  4158. clipCount++;
  4159. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  4160. this.clippath.setAttributeNS(null, 'id', current.clipId);
  4161. var clipElement = current.element.cloneNode();
  4162. if (type === 'evenodd') {
  4163. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  4164. } else {
  4165. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  4166. }
  4167. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4168. this.clippath.appendChild(clipElement);
  4169. this.defs.appendChild(this.clippath);
  4170. // Create a new group with that attribute
  4171. current.pendingClip = true;
  4172. this.cgrp = document.createElementNS(NS, 'svg:g');
  4173. this.cgrp.setAttributeNS(null, 'clip-path',
  4174. 'url(#' + current.clipId + ')');
  4175. this.pgrp.appendChild(this.cgrp);
  4176. },
  4177. closePath: function SVGGraphics_closePath() {
  4178. var current = this.current;
  4179. var d = current.path.getAttributeNS(null, 'd');
  4180. d += 'Z';
  4181. current.path.setAttributeNS(null, 'd', d);
  4182. },
  4183. setLeading: function SVGGraphics_setLeading(leading) {
  4184. this.current.leading = -leading;
  4185. },
  4186. setTextRise: function SVGGraphics_setTextRise(textRise) {
  4187. this.current.textRise = textRise;
  4188. },
  4189. setHScale: function SVGGraphics_setHScale(scale) {
  4190. this.current.textHScale = scale / 100;
  4191. },
  4192. setGState: function SVGGraphics_setGState(states) {
  4193. for (var i = 0, ii = states.length; i < ii; i++) {
  4194. var state = states[i];
  4195. var key = state[0];
  4196. var value = state[1];
  4197. switch (key) {
  4198. case 'LW':
  4199. this.setLineWidth(value);
  4200. break;
  4201. case 'LC':
  4202. this.setLineCap(value);
  4203. break;
  4204. case 'LJ':
  4205. this.setLineJoin(value);
  4206. break;
  4207. case 'ML':
  4208. this.setMiterLimit(value);
  4209. break;
  4210. case 'D':
  4211. this.setDash(value[0], value[1]);
  4212. break;
  4213. case 'RI':
  4214. break;
  4215. case 'FL':
  4216. break;
  4217. case 'Font':
  4218. this.setFont(value);
  4219. break;
  4220. case 'CA':
  4221. break;
  4222. case 'ca':
  4223. break;
  4224. case 'BM':
  4225. break;
  4226. case 'SMask':
  4227. break;
  4228. }
  4229. }
  4230. },
  4231. fill: function SVGGraphics_fill() {
  4232. var current = this.current;
  4233. current.element.setAttributeNS(null, 'fill', current.fillColor);
  4234. },
  4235. stroke: function SVGGraphics_stroke() {
  4236. var current = this.current;
  4237. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  4238. current.element.setAttributeNS(null, 'fill', 'none');
  4239. },
  4240. eoFill: function SVGGraphics_eoFill() {
  4241. var current = this.current;
  4242. current.element.setAttributeNS(null, 'fill', current.fillColor);
  4243. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4244. },
  4245. fillStroke: function SVGGraphics_fillStroke() {
  4246. // Order is important since stroke wants fill to be none.
  4247. // First stroke, then if fill needed, it will be overwritten.
  4248. this.stroke();
  4249. this.fill();
  4250. },
  4251. eoFillStroke: function SVGGraphics_eoFillStroke() {
  4252. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4253. this.fillStroke();
  4254. },
  4255. closeStroke: function SVGGraphics_closeStroke() {
  4256. this.closePath();
  4257. this.stroke();
  4258. },
  4259. closeFillStroke: function SVGGraphics_closeFillStroke() {
  4260. this.closePath();
  4261. this.fillStroke();
  4262. },
  4263. paintSolidColorImageMask:
  4264. function SVGGraphics_paintSolidColorImageMask() {
  4265. var current = this.current;
  4266. var rect = document.createElementNS(NS, 'svg:rect');
  4267. rect.setAttributeNS(null, 'x', '0');
  4268. rect.setAttributeNS(null, 'y', '0');
  4269. rect.setAttributeNS(null, 'width', '1px');
  4270. rect.setAttributeNS(null, 'height', '1px');
  4271. rect.setAttributeNS(null, 'fill', current.fillColor);
  4272. this.tgrp.appendChild(rect);
  4273. },
  4274. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  4275. var current = this.current;
  4276. var imgObj = this.objs.get(objId);
  4277. var imgEl = document.createElementNS(NS, 'svg:image');
  4278. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  4279. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  4280. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  4281. imgEl.setAttributeNS(null, 'x', '0');
  4282. imgEl.setAttributeNS(null, 'y', pf(-h));
  4283. imgEl.setAttributeNS(null, 'transform',
  4284. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  4285. this.tgrp.appendChild(imgEl);
  4286. if (current.pendingClip) {
  4287. this.cgrp.appendChild(this.tgrp);
  4288. this.pgrp.appendChild(this.cgrp);
  4289. } else {
  4290. this.pgrp.appendChild(this.tgrp);
  4291. }
  4292. },
  4293. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  4294. var imgData = this.objs.get(objId);
  4295. if (!imgData) {
  4296. warn('Dependent image isn\'t ready yet');
  4297. return;
  4298. }
  4299. this.paintInlineImageXObject(imgData);
  4300. },
  4301. paintInlineImageXObject:
  4302. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  4303. var current = this.current;
  4304. var width = imgData.width;
  4305. var height = imgData.height;
  4306. var imgSrc = convertImgDataToPng(imgData);
  4307. var cliprect = document.createElementNS(NS, 'svg:rect');
  4308. cliprect.setAttributeNS(null, 'x', '0');
  4309. cliprect.setAttributeNS(null, 'y', '0');
  4310. cliprect.setAttributeNS(null, 'width', pf(width));
  4311. cliprect.setAttributeNS(null, 'height', pf(height));
  4312. current.element = cliprect;
  4313. this.clip('nonzero');
  4314. var imgEl = document.createElementNS(NS, 'svg:image');
  4315. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4316. imgEl.setAttributeNS(null, 'x', '0');
  4317. imgEl.setAttributeNS(null, 'y', pf(-height));
  4318. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4319. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4320. imgEl.setAttributeNS(null, 'transform',
  4321. 'scale(' + pf(1 / width) + ' ' +
  4322. pf(-1 / height) + ')');
  4323. if (mask) {
  4324. mask.appendChild(imgEl);
  4325. } else {
  4326. this.tgrp.appendChild(imgEl);
  4327. }
  4328. if (current.pendingClip) {
  4329. this.cgrp.appendChild(this.tgrp);
  4330. this.pgrp.appendChild(this.cgrp);
  4331. } else {
  4332. this.pgrp.appendChild(this.tgrp);
  4333. }
  4334. },
  4335. paintImageMaskXObject:
  4336. function SVGGraphics_paintImageMaskXObject(imgData) {
  4337. var current = this.current;
  4338. var width = imgData.width;
  4339. var height = imgData.height;
  4340. var fillColor = current.fillColor;
  4341. current.maskId = 'mask' + maskCount++;
  4342. var mask = document.createElementNS(NS, 'svg:mask');
  4343. mask.setAttributeNS(null, 'id', current.maskId);
  4344. var rect = document.createElementNS(NS, 'svg:rect');
  4345. rect.setAttributeNS(null, 'x', '0');
  4346. rect.setAttributeNS(null, 'y', '0');
  4347. rect.setAttributeNS(null, 'width', pf(width));
  4348. rect.setAttributeNS(null, 'height', pf(height));
  4349. rect.setAttributeNS(null, 'fill', fillColor);
  4350. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  4351. this.defs.appendChild(mask);
  4352. this.tgrp.appendChild(rect);
  4353. this.paintInlineImageXObject(imgData, mask);
  4354. },
  4355. paintFormXObjectBegin:
  4356. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4357. this.save();
  4358. if (isArray(matrix) && matrix.length === 6) {
  4359. this.transform(matrix[0], matrix[1], matrix[2],
  4360. matrix[3], matrix[4], matrix[5]);
  4361. }
  4362. if (isArray(bbox) && bbox.length === 4) {
  4363. var width = bbox[2] - bbox[0];
  4364. var height = bbox[3] - bbox[1];
  4365. var cliprect = document.createElementNS(NS, 'svg:rect');
  4366. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4367. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4368. cliprect.setAttributeNS(null, 'width', pf(width));
  4369. cliprect.setAttributeNS(null, 'height', pf(height));
  4370. this.current.element = cliprect;
  4371. this.clip('nonzero');
  4372. this.endPath();
  4373. }
  4374. },
  4375. paintFormXObjectEnd:
  4376. function SVGGraphics_paintFormXObjectEnd() {
  4377. this.restore();
  4378. }
  4379. };
  4380. return SVGGraphics;
  4381. })();
  4382. PDFJS.SVGGraphics = SVGGraphics;
  4383. exports.SVGGraphics = SVGGraphics;
  4384. }));
  4385. (function (root, factory) {
  4386. {
  4387. factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
  4388. root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal);
  4389. }
  4390. }(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) {
  4391. var Util = sharedUtil.Util;
  4392. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4393. var CustomStyle = displayDOMUtils.CustomStyle;
  4394. var PDFJS = sharedGlobal.PDFJS;
  4395. /**
  4396. * Text layer render parameters.
  4397. *
  4398. * @typedef {Object} TextLayerRenderParameters
  4399. * @property {TextContent} textContent - Text content to render (the object is
  4400. * returned by the page's getTextContent() method).
  4401. * @property {HTMLElement} container - HTML element that will contain text runs.
  4402. * @property {PDFJS.PageViewport} viewport - The target viewport to properly
  4403. * layout the text runs.
  4404. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4405. * the text items of the textContent input. This is output and shall be
  4406. * initially be set to empty array.
  4407. * @property {number} timeout - (optional) Delay in milliseconds before
  4408. * rendering of the text runs occurs.
  4409. */
  4410. var renderTextLayer = (function renderTextLayerClosure() {
  4411. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4412. var NonWhitespaceRegexp = /\S/;
  4413. function isAllWhitespace(str) {
  4414. return !NonWhitespaceRegexp.test(str);
  4415. }
  4416. function appendText(textDivs, viewport, geom, styles) {
  4417. var style = styles[geom.fontName];
  4418. var textDiv = document.createElement('div');
  4419. textDivs.push(textDiv);
  4420. if (isAllWhitespace(geom.str)) {
  4421. textDiv.dataset.isWhitespace = true;
  4422. return;
  4423. }
  4424. var tx = Util.transform(viewport.transform, geom.transform);
  4425. var angle = Math.atan2(tx[1], tx[0]);
  4426. if (style.vertical) {
  4427. angle += Math.PI / 2;
  4428. }
  4429. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  4430. var fontAscent = fontHeight;
  4431. if (style.ascent) {
  4432. fontAscent = style.ascent * fontAscent;
  4433. } else if (style.descent) {
  4434. fontAscent = (1 + style.descent) * fontAscent;
  4435. }
  4436. var left;
  4437. var top;
  4438. if (angle === 0) {
  4439. left = tx[4];
  4440. top = tx[5] - fontAscent;
  4441. } else {
  4442. left = tx[4] + (fontAscent * Math.sin(angle));
  4443. top = tx[5] - (fontAscent * Math.cos(angle));
  4444. }
  4445. textDiv.style.left = left + 'px';
  4446. textDiv.style.top = top + 'px';
  4447. textDiv.style.fontSize = fontHeight + 'px';
  4448. textDiv.style.fontFamily = style.fontFamily;
  4449. textDiv.textContent = geom.str;
  4450. // |fontName| is only used by the Font Inspector. This test will succeed
  4451. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  4452. // not worth the effort to do a more accurate test.
  4453. if (PDFJS.pdfBug) {
  4454. textDiv.dataset.fontName = geom.fontName;
  4455. }
  4456. // Storing into dataset will convert number into string.
  4457. if (angle !== 0) {
  4458. textDiv.dataset.angle = angle * (180 / Math.PI);
  4459. }
  4460. // We don't bother scaling single-char text divs, because it has very
  4461. // little effect on text highlighting. This makes scrolling on docs with
  4462. // lots of such divs a lot faster.
  4463. if (geom.str.length > 1) {
  4464. if (style.vertical) {
  4465. textDiv.dataset.canvasWidth = geom.height * viewport.scale;
  4466. } else {
  4467. textDiv.dataset.canvasWidth = geom.width * viewport.scale;
  4468. }
  4469. }
  4470. }
  4471. function render(task) {
  4472. if (task._canceled) {
  4473. return;
  4474. }
  4475. var textLayerFrag = task._container;
  4476. var textDivs = task._textDivs;
  4477. var capability = task._capability;
  4478. var textDivsLength = textDivs.length;
  4479. // No point in rendering many divs as it would make the browser
  4480. // unusable even after the divs are rendered.
  4481. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4482. capability.resolve();
  4483. return;
  4484. }
  4485. var canvas = document.createElement('canvas');
  4486. canvas.mozOpaque = true;
  4487. var ctx = canvas.getContext('2d', {alpha: false});
  4488. var lastFontSize;
  4489. var lastFontFamily;
  4490. for (var i = 0; i < textDivsLength; i++) {
  4491. var textDiv = textDivs[i];
  4492. if (textDiv.dataset.isWhitespace !== undefined) {
  4493. continue;
  4494. }
  4495. var fontSize = textDiv.style.fontSize;
  4496. var fontFamily = textDiv.style.fontFamily;
  4497. // Only build font string and set to context if different from last.
  4498. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4499. ctx.font = fontSize + ' ' + fontFamily;
  4500. lastFontSize = fontSize;
  4501. lastFontFamily = fontFamily;
  4502. }
  4503. var width = ctx.measureText(textDiv.textContent).width;
  4504. if (width > 0) {
  4505. textLayerFrag.appendChild(textDiv);
  4506. var transform;
  4507. if (textDiv.dataset.canvasWidth !== undefined) {
  4508. // Dataset values come of type string.
  4509. var textScale = textDiv.dataset.canvasWidth / width;
  4510. transform = 'scaleX(' + textScale + ')';
  4511. } else {
  4512. transform = '';
  4513. }
  4514. var rotation = textDiv.dataset.angle;
  4515. if (rotation) {
  4516. transform = 'rotate(' + rotation + 'deg) ' + transform;
  4517. }
  4518. if (transform) {
  4519. CustomStyle.setProp('transform' , textDiv, transform);
  4520. }
  4521. }
  4522. }
  4523. capability.resolve();
  4524. }
  4525. /**
  4526. * Text layer rendering task.
  4527. *
  4528. * @param {TextContent} textContent
  4529. * @param {HTMLElement} container
  4530. * @param {PDFJS.PageViewport} viewport
  4531. * @param {Array} textDivs
  4532. * @private
  4533. */
  4534. function TextLayerRenderTask(textContent, container, viewport, textDivs) {
  4535. this._textContent = textContent;
  4536. this._container = container;
  4537. this._viewport = viewport;
  4538. textDivs = textDivs || [];
  4539. this._textDivs = textDivs;
  4540. this._canceled = false;
  4541. this._capability = createPromiseCapability();
  4542. this._renderTimer = null;
  4543. }
  4544. TextLayerRenderTask.prototype = {
  4545. get promise() {
  4546. return this._capability.promise;
  4547. },
  4548. cancel: function TextLayer_cancel() {
  4549. this._canceled = true;
  4550. if (this._renderTimer !== null) {
  4551. clearTimeout(this._renderTimer);
  4552. this._renderTimer = null;
  4553. }
  4554. this._capability.reject('canceled');
  4555. },
  4556. _render: function TextLayer_render(timeout) {
  4557. var textItems = this._textContent.items;
  4558. var styles = this._textContent.styles;
  4559. var textDivs = this._textDivs;
  4560. var viewport = this._viewport;
  4561. for (var i = 0, len = textItems.length; i < len; i++) {
  4562. appendText(textDivs, viewport, textItems[i], styles);
  4563. }
  4564. if (!timeout) { // Render right away
  4565. render(this);
  4566. } else { // Schedule
  4567. var self = this;
  4568. this._renderTimer = setTimeout(function() {
  4569. render(self);
  4570. self._renderTimer = null;
  4571. }, timeout);
  4572. }
  4573. }
  4574. };
  4575. /**
  4576. * Starts rendering of the text layer.
  4577. *
  4578. * @param {TextLayerRenderParameters} renderParameters
  4579. * @returns {TextLayerRenderTask}
  4580. */
  4581. function renderTextLayer(renderParameters) {
  4582. var task = new TextLayerRenderTask(renderParameters.textContent,
  4583. renderParameters.container,
  4584. renderParameters.viewport,
  4585. renderParameters.textDivs);
  4586. task._render(renderParameters.timeout);
  4587. return task;
  4588. }
  4589. return renderTextLayer;
  4590. })();
  4591. PDFJS.renderTextLayer = renderTextLayer;
  4592. exports.renderTextLayer = renderTextLayer;
  4593. }));
  4594. (function (root, factory) {
  4595. {
  4596. factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil);
  4597. }
  4598. }(this, function (exports, sharedUtil) {
  4599. var shadow = sharedUtil.shadow;
  4600. var WebGLUtils = (function WebGLUtilsClosure() {
  4601. function loadShader(gl, code, shaderType) {
  4602. var shader = gl.createShader(shaderType);
  4603. gl.shaderSource(shader, code);
  4604. gl.compileShader(shader);
  4605. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4606. if (!compiled) {
  4607. var errorMsg = gl.getShaderInfoLog(shader);
  4608. throw new Error('Error during shader compilation: ' + errorMsg);
  4609. }
  4610. return shader;
  4611. }
  4612. function createVertexShader(gl, code) {
  4613. return loadShader(gl, code, gl.VERTEX_SHADER);
  4614. }
  4615. function createFragmentShader(gl, code) {
  4616. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4617. }
  4618. function createProgram(gl, shaders) {
  4619. var program = gl.createProgram();
  4620. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4621. gl.attachShader(program, shaders[i]);
  4622. }
  4623. gl.linkProgram(program);
  4624. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4625. if (!linked) {
  4626. var errorMsg = gl.getProgramInfoLog(program);
  4627. throw new Error('Error during program linking: ' + errorMsg);
  4628. }
  4629. return program;
  4630. }
  4631. function createTexture(gl, image, textureId) {
  4632. gl.activeTexture(textureId);
  4633. var texture = gl.createTexture();
  4634. gl.bindTexture(gl.TEXTURE_2D, texture);
  4635. // Set the parameters so we can render any size image.
  4636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4640. // Upload the image into the texture.
  4641. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4642. return texture;
  4643. }
  4644. var currentGL, currentCanvas;
  4645. function generateGL() {
  4646. if (currentGL) {
  4647. return;
  4648. }
  4649. currentCanvas = document.createElement('canvas');
  4650. currentGL = currentCanvas.getContext('webgl',
  4651. { premultipliedalpha: false });
  4652. }
  4653. var smaskVertexShaderCode = '\
  4654. attribute vec2 a_position; \
  4655. attribute vec2 a_texCoord; \
  4656. \
  4657. uniform vec2 u_resolution; \
  4658. \
  4659. varying vec2 v_texCoord; \
  4660. \
  4661. void main() { \
  4662. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4663. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4664. \
  4665. v_texCoord = a_texCoord; \
  4666. } ';
  4667. var smaskFragmentShaderCode = '\
  4668. precision mediump float; \
  4669. \
  4670. uniform vec4 u_backdrop; \
  4671. uniform int u_subtype; \
  4672. uniform sampler2D u_image; \
  4673. uniform sampler2D u_mask; \
  4674. \
  4675. varying vec2 v_texCoord; \
  4676. \
  4677. void main() { \
  4678. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4679. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4680. if (u_backdrop.a > 0.0) { \
  4681. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4682. u_backdrop.rgb * (1.0 - maskColor.a); \
  4683. } \
  4684. float lum; \
  4685. if (u_subtype == 0) { \
  4686. lum = maskColor.a; \
  4687. } else { \
  4688. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4689. maskColor.b * 0.11; \
  4690. } \
  4691. imageColor.a *= lum; \
  4692. imageColor.rgb *= imageColor.a; \
  4693. gl_FragColor = imageColor; \
  4694. } ';
  4695. var smaskCache = null;
  4696. function initSmaskGL() {
  4697. var canvas, gl;
  4698. generateGL();
  4699. canvas = currentCanvas;
  4700. currentCanvas = null;
  4701. gl = currentGL;
  4702. currentGL = null;
  4703. // setup a GLSL program
  4704. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4705. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4706. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4707. gl.useProgram(program);
  4708. var cache = {};
  4709. cache.gl = gl;
  4710. cache.canvas = canvas;
  4711. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4712. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4713. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4714. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4715. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4716. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4717. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4718. // provide texture coordinates for the rectangle.
  4719. var texCoordBuffer = gl.createBuffer();
  4720. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4721. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4722. 0.0, 0.0,
  4723. 1.0, 0.0,
  4724. 0.0, 1.0,
  4725. 0.0, 1.0,
  4726. 1.0, 0.0,
  4727. 1.0, 1.0]), gl.STATIC_DRAW);
  4728. gl.enableVertexAttribArray(texCoordLocation);
  4729. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4730. gl.uniform1i(texLayerLocation, 0);
  4731. gl.uniform1i(texMaskLocation, 1);
  4732. smaskCache = cache;
  4733. }
  4734. function composeSMask(layer, mask, properties) {
  4735. var width = layer.width, height = layer.height;
  4736. if (!smaskCache) {
  4737. initSmaskGL();
  4738. }
  4739. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4740. canvas.width = width;
  4741. canvas.height = height;
  4742. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4743. gl.uniform2f(cache.resolutionLocation, width, height);
  4744. if (properties.backdrop) {
  4745. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4746. properties.backdrop[1], properties.backdrop[2], 1);
  4747. } else {
  4748. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4749. }
  4750. gl.uniform1i(cache.subtypeLocation,
  4751. properties.subtype === 'Luminosity' ? 1 : 0);
  4752. // Create a textures
  4753. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4754. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4755. // Create a buffer and put a single clipspace rectangle in
  4756. // it (2 triangles)
  4757. var buffer = gl.createBuffer();
  4758. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4759. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4760. 0, 0,
  4761. width, 0,
  4762. 0, height,
  4763. 0, height,
  4764. width, 0,
  4765. width, height]), gl.STATIC_DRAW);
  4766. gl.enableVertexAttribArray(cache.positionLocation);
  4767. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4768. // draw
  4769. gl.clearColor(0, 0, 0, 0);
  4770. gl.enable(gl.BLEND);
  4771. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4772. gl.clear(gl.COLOR_BUFFER_BIT);
  4773. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4774. gl.flush();
  4775. gl.deleteTexture(texture);
  4776. gl.deleteTexture(maskTexture);
  4777. gl.deleteBuffer(buffer);
  4778. return canvas;
  4779. }
  4780. var figuresVertexShaderCode = '\
  4781. attribute vec2 a_position; \
  4782. attribute vec3 a_color; \
  4783. \
  4784. uniform vec2 u_resolution; \
  4785. uniform vec2 u_scale; \
  4786. uniform vec2 u_offset; \
  4787. \
  4788. varying vec4 v_color; \
  4789. \
  4790. void main() { \
  4791. vec2 position = (a_position + u_offset) * u_scale; \
  4792. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4793. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4794. \
  4795. v_color = vec4(a_color / 255.0, 1.0); \
  4796. } ';
  4797. var figuresFragmentShaderCode = '\
  4798. precision mediump float; \
  4799. \
  4800. varying vec4 v_color; \
  4801. \
  4802. void main() { \
  4803. gl_FragColor = v_color; \
  4804. } ';
  4805. var figuresCache = null;
  4806. function initFiguresGL() {
  4807. var canvas, gl;
  4808. generateGL();
  4809. canvas = currentCanvas;
  4810. currentCanvas = null;
  4811. gl = currentGL;
  4812. currentGL = null;
  4813. // setup a GLSL program
  4814. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  4815. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  4816. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4817. gl.useProgram(program);
  4818. var cache = {};
  4819. cache.gl = gl;
  4820. cache.canvas = canvas;
  4821. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4822. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  4823. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  4824. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4825. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  4826. figuresCache = cache;
  4827. }
  4828. function drawFigures(width, height, backgroundColor, figures, context) {
  4829. if (!figuresCache) {
  4830. initFiguresGL();
  4831. }
  4832. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  4833. canvas.width = width;
  4834. canvas.height = height;
  4835. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4836. gl.uniform2f(cache.resolutionLocation, width, height);
  4837. // count triangle points
  4838. var count = 0;
  4839. var i, ii, rows;
  4840. for (i = 0, ii = figures.length; i < ii; i++) {
  4841. switch (figures[i].type) {
  4842. case 'lattice':
  4843. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  4844. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  4845. break;
  4846. case 'triangles':
  4847. count += figures[i].coords.length;
  4848. break;
  4849. }
  4850. }
  4851. // transfer data
  4852. var coords = new Float32Array(count * 2);
  4853. var colors = new Uint8Array(count * 3);
  4854. var coordsMap = context.coords, colorsMap = context.colors;
  4855. var pIndex = 0, cIndex = 0;
  4856. for (i = 0, ii = figures.length; i < ii; i++) {
  4857. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  4858. switch (figure.type) {
  4859. case 'lattice':
  4860. var cols = figure.verticesPerRow;
  4861. rows = (ps.length / cols) | 0;
  4862. for (var row = 1; row < rows; row++) {
  4863. var offset = row * cols + 1;
  4864. for (var col = 1; col < cols; col++, offset++) {
  4865. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  4866. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  4867. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  4868. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  4869. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  4870. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  4871. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  4872. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  4873. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  4874. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  4875. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  4876. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  4877. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  4878. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  4879. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  4880. coords[pIndex + 6] = coords[pIndex + 2];
  4881. coords[pIndex + 7] = coords[pIndex + 3];
  4882. coords[pIndex + 8] = coords[pIndex + 4];
  4883. coords[pIndex + 9] = coords[pIndex + 5];
  4884. coords[pIndex + 10] = coordsMap[ps[offset]];
  4885. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  4886. colors[cIndex + 9] = colors[cIndex + 3];
  4887. colors[cIndex + 10] = colors[cIndex + 4];
  4888. colors[cIndex + 11] = colors[cIndex + 5];
  4889. colors[cIndex + 12] = colors[cIndex + 6];
  4890. colors[cIndex + 13] = colors[cIndex + 7];
  4891. colors[cIndex + 14] = colors[cIndex + 8];
  4892. colors[cIndex + 15] = colorsMap[cs[offset]];
  4893. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  4894. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  4895. pIndex += 12;
  4896. cIndex += 18;
  4897. }
  4898. }
  4899. break;
  4900. case 'triangles':
  4901. for (var j = 0, jj = ps.length; j < jj; j++) {
  4902. coords[pIndex] = coordsMap[ps[j]];
  4903. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  4904. colors[cIndex] = colorsMap[cs[j]];
  4905. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  4906. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  4907. pIndex += 2;
  4908. cIndex += 3;
  4909. }
  4910. break;
  4911. }
  4912. }
  4913. // draw
  4914. if (backgroundColor) {
  4915. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  4916. backgroundColor[2] / 255, 1.0);
  4917. } else {
  4918. gl.clearColor(0, 0, 0, 0);
  4919. }
  4920. gl.clear(gl.COLOR_BUFFER_BIT);
  4921. var coordsBuffer = gl.createBuffer();
  4922. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  4923. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  4924. gl.enableVertexAttribArray(cache.positionLocation);
  4925. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4926. var colorsBuffer = gl.createBuffer();
  4927. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  4928. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  4929. gl.enableVertexAttribArray(cache.colorLocation);
  4930. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  4931. 0, 0);
  4932. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  4933. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  4934. gl.drawArrays(gl.TRIANGLES, 0, count);
  4935. gl.flush();
  4936. gl.deleteBuffer(coordsBuffer);
  4937. gl.deleteBuffer(colorsBuffer);
  4938. return canvas;
  4939. }
  4940. function cleanup() {
  4941. if (smaskCache && smaskCache.canvas) {
  4942. smaskCache.canvas.width = 0;
  4943. smaskCache.canvas.height = 0;
  4944. }
  4945. if (figuresCache && figuresCache.canvas) {
  4946. figuresCache.canvas.width = 0;
  4947. figuresCache.canvas.height = 0;
  4948. }
  4949. smaskCache = null;
  4950. figuresCache = null;
  4951. }
  4952. return {
  4953. get isEnabled() {
  4954. if (PDFJS.disableWebGL) {
  4955. return false;
  4956. }
  4957. var enabled = false;
  4958. try {
  4959. generateGL();
  4960. enabled = !!currentGL;
  4961. } catch (e) { }
  4962. return shadow(this, 'isEnabled', enabled);
  4963. },
  4964. composeSMask: composeSMask,
  4965. drawFigures: drawFigures,
  4966. clear: cleanup
  4967. };
  4968. })();
  4969. exports.WebGLUtils = WebGLUtils;
  4970. }));
  4971. (function (root, factory) {
  4972. {
  4973. factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
  4974. root.pdfjsDisplayWebGL);
  4975. }
  4976. }(this, function (exports, sharedUtil, displayWebGL) {
  4977. var Util = sharedUtil.Util;
  4978. var info = sharedUtil.info;
  4979. var isArray = sharedUtil.isArray;
  4980. var error = sharedUtil.error;
  4981. var WebGLUtils = displayWebGL.WebGLUtils;
  4982. var ShadingIRs = {};
  4983. ShadingIRs.RadialAxial = {
  4984. fromIR: function RadialAxial_fromIR(raw) {
  4985. var type = raw[1];
  4986. var colorStops = raw[2];
  4987. var p0 = raw[3];
  4988. var p1 = raw[4];
  4989. var r0 = raw[5];
  4990. var r1 = raw[6];
  4991. return {
  4992. type: 'Pattern',
  4993. getPattern: function RadialAxial_getPattern(ctx) {
  4994. var grad;
  4995. if (type === 'axial') {
  4996. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  4997. } else if (type === 'radial') {
  4998. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  4999. }
  5000. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5001. var c = colorStops[i];
  5002. grad.addColorStop(c[0], c[1]);
  5003. }
  5004. return grad;
  5005. }
  5006. };
  5007. }
  5008. };
  5009. var createMeshCanvas = (function createMeshCanvasClosure() {
  5010. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5011. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5012. var coords = context.coords, colors = context.colors;
  5013. var bytes = data.data, rowSize = data.width * 4;
  5014. var tmp;
  5015. if (coords[p1 + 1] > coords[p2 + 1]) {
  5016. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5017. }
  5018. if (coords[p2 + 1] > coords[p3 + 1]) {
  5019. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5020. }
  5021. if (coords[p1 + 1] > coords[p2 + 1]) {
  5022. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5023. }
  5024. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5025. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5026. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5027. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5028. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5029. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5030. if (y1 >= y3) {
  5031. return;
  5032. }
  5033. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5034. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5035. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5036. var minY = Math.round(y1), maxY = Math.round(y3);
  5037. var xa, car, cag, cab;
  5038. var xb, cbr, cbg, cbb;
  5039. var k;
  5040. for (var y = minY; y <= maxY; y++) {
  5041. if (y < y2) {
  5042. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5043. xa = x1 - (x1 - x2) * k;
  5044. car = c1r - (c1r - c2r) * k;
  5045. cag = c1g - (c1g - c2g) * k;
  5046. cab = c1b - (c1b - c2b) * k;
  5047. } else {
  5048. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5049. xa = x2 - (x2 - x3) * k;
  5050. car = c2r - (c2r - c3r) * k;
  5051. cag = c2g - (c2g - c3g) * k;
  5052. cab = c2b - (c2b - c3b) * k;
  5053. }
  5054. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5055. xb = x1 - (x1 - x3) * k;
  5056. cbr = c1r - (c1r - c3r) * k;
  5057. cbg = c1g - (c1g - c3g) * k;
  5058. cbb = c1b - (c1b - c3b) * k;
  5059. var x1_ = Math.round(Math.min(xa, xb));
  5060. var x2_ = Math.round(Math.max(xa, xb));
  5061. var j = rowSize * y + x1_ * 4;
  5062. for (var x = x1_; x <= x2_; x++) {
  5063. k = (xa - x) / (xa - xb);
  5064. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5065. bytes[j++] = (car - (car - cbr) * k) | 0;
  5066. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5067. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5068. bytes[j++] = 255;
  5069. }
  5070. }
  5071. }
  5072. function drawFigure(data, figure, context) {
  5073. var ps = figure.coords;
  5074. var cs = figure.colors;
  5075. var i, ii;
  5076. switch (figure.type) {
  5077. case 'lattice':
  5078. var verticesPerRow = figure.verticesPerRow;
  5079. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5080. var cols = verticesPerRow - 1;
  5081. for (i = 0; i < rows; i++) {
  5082. var q = i * verticesPerRow;
  5083. for (var j = 0; j < cols; j++, q++) {
  5084. drawTriangle(data, context,
  5085. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5086. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5087. drawTriangle(data, context,
  5088. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5089. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5090. }
  5091. }
  5092. break;
  5093. case 'triangles':
  5094. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5095. drawTriangle(data, context,
  5096. ps[i], ps[i + 1], ps[i + 2],
  5097. cs[i], cs[i + 1], cs[i + 2]);
  5098. }
  5099. break;
  5100. default:
  5101. error('illigal figure');
  5102. break;
  5103. }
  5104. }
  5105. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5106. backgroundColor, cachedCanvases) {
  5107. // we will increase scale on some weird factor to let antialiasing take
  5108. // care of "rough" edges
  5109. var EXPECTED_SCALE = 1.1;
  5110. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5111. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5112. var offsetX = Math.floor(bounds[0]);
  5113. var offsetY = Math.floor(bounds[1]);
  5114. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5115. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5116. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5117. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5118. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5119. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5120. var scaleX = boundsWidth / width;
  5121. var scaleY = boundsHeight / height;
  5122. var context = {
  5123. coords: coords,
  5124. colors: colors,
  5125. offsetX: -offsetX,
  5126. offsetY: -offsetY,
  5127. scaleX: 1 / scaleX,
  5128. scaleY: 1 / scaleY
  5129. };
  5130. var canvas, tmpCanvas, i, ii;
  5131. if (WebGLUtils.isEnabled) {
  5132. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5133. figures, context);
  5134. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5135. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5136. tmpCanvas.context.drawImage(canvas, 0, 0);
  5137. canvas = tmpCanvas.canvas;
  5138. } else {
  5139. tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
  5140. var tmpCtx = tmpCanvas.context;
  5141. var data = tmpCtx.createImageData(width, height);
  5142. if (backgroundColor) {
  5143. var bytes = data.data;
  5144. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5145. bytes[i] = backgroundColor[0];
  5146. bytes[i + 1] = backgroundColor[1];
  5147. bytes[i + 2] = backgroundColor[2];
  5148. bytes[i + 3] = 255;
  5149. }
  5150. }
  5151. for (i = 0; i < figures.length; i++) {
  5152. drawFigure(data, figures[i], context);
  5153. }
  5154. tmpCtx.putImageData(data, 0, 0);
  5155. canvas = tmpCanvas.canvas;
  5156. }
  5157. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5158. scaleX: scaleX, scaleY: scaleY};
  5159. }
  5160. return createMeshCanvas;
  5161. })();
  5162. ShadingIRs.Mesh = {
  5163. fromIR: function Mesh_fromIR(raw) {
  5164. //var type = raw[1];
  5165. var coords = raw[2];
  5166. var colors = raw[3];
  5167. var figures = raw[4];
  5168. var bounds = raw[5];
  5169. var matrix = raw[6];
  5170. //var bbox = raw[7];
  5171. var background = raw[8];
  5172. return {
  5173. type: 'Pattern',
  5174. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5175. var scale;
  5176. if (shadingFill) {
  5177. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5178. } else {
  5179. // Obtain scale from matrix and current transformation matrix.
  5180. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5181. if (matrix) {
  5182. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5183. scale = [scale[0] * matrixScale[0],
  5184. scale[1] * matrixScale[1]];
  5185. }
  5186. }
  5187. // Rasterizing on the main thread since sending/queue large canvases
  5188. // might cause OOM.
  5189. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5190. colors, figures, shadingFill ? null : background,
  5191. owner.cachedCanvases);
  5192. if (!shadingFill) {
  5193. ctx.setTransform.apply(ctx, owner.baseTransform);
  5194. if (matrix) {
  5195. ctx.transform.apply(ctx, matrix);
  5196. }
  5197. }
  5198. ctx.translate(temporaryPatternCanvas.offsetX,
  5199. temporaryPatternCanvas.offsetY);
  5200. ctx.scale(temporaryPatternCanvas.scaleX,
  5201. temporaryPatternCanvas.scaleY);
  5202. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5203. }
  5204. };
  5205. }
  5206. };
  5207. ShadingIRs.Dummy = {
  5208. fromIR: function Dummy_fromIR() {
  5209. return {
  5210. type: 'Pattern',
  5211. getPattern: function Dummy_fromIR_getPattern() {
  5212. return 'hotpink';
  5213. }
  5214. };
  5215. }
  5216. };
  5217. function getShadingPatternFromIR(raw) {
  5218. var shadingIR = ShadingIRs[raw[0]];
  5219. if (!shadingIR) {
  5220. error('Unknown IR type: ' + raw[0]);
  5221. }
  5222. return shadingIR.fromIR(raw);
  5223. }
  5224. var TilingPattern = (function TilingPatternClosure() {
  5225. var PaintType = {
  5226. COLORED: 1,
  5227. UNCOLORED: 2
  5228. };
  5229. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5230. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5231. this.operatorList = IR[2];
  5232. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5233. this.bbox = IR[4];
  5234. this.xstep = IR[5];
  5235. this.ystep = IR[6];
  5236. this.paintType = IR[7];
  5237. this.tilingType = IR[8];
  5238. this.color = color;
  5239. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5240. this.baseTransform = baseTransform;
  5241. this.type = 'Pattern';
  5242. this.ctx = ctx;
  5243. }
  5244. TilingPattern.prototype = {
  5245. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5246. var operatorList = this.operatorList;
  5247. var bbox = this.bbox;
  5248. var xstep = this.xstep;
  5249. var ystep = this.ystep;
  5250. var paintType = this.paintType;
  5251. var tilingType = this.tilingType;
  5252. var color = this.color;
  5253. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5254. info('TilingType: ' + tilingType);
  5255. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5256. var topLeft = [x0, y0];
  5257. // we want the canvas to be as large as the step size
  5258. var botRight = [x0 + xstep, y0 + ystep];
  5259. var width = botRight[0] - topLeft[0];
  5260. var height = botRight[1] - topLeft[1];
  5261. // Obtain scale from matrix and current transformation matrix.
  5262. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5263. var curMatrixScale = Util.singularValueDecompose2dScale(
  5264. this.baseTransform);
  5265. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5266. matrixScale[1] * curMatrixScale[1]];
  5267. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5268. // Use width and height values that are as close as possible to the end
  5269. // result when the pattern is used. Too low value makes the pattern look
  5270. // blurry. Too large value makes it look too crispy.
  5271. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5272. MAX_PATTERN_SIZE);
  5273. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5274. MAX_PATTERN_SIZE);
  5275. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
  5276. width, height, true);
  5277. var tmpCtx = tmpCanvas.context;
  5278. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5279. graphics.groupLevel = owner.groupLevel;
  5280. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5281. this.setScale(width, height, xstep, ystep);
  5282. this.transformToScale(graphics);
  5283. // transform coordinates to pattern space
  5284. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5285. graphics.transform.apply(graphics, tmpTranslate);
  5286. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5287. graphics.executeOperatorList(operatorList);
  5288. return tmpCanvas.canvas;
  5289. },
  5290. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5291. this.scale = [width / xstep, height / ystep];
  5292. },
  5293. transformToScale: function TilingPattern_transformToScale(graphics) {
  5294. var scale = this.scale;
  5295. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5296. graphics.transform.apply(graphics, tmpScale);
  5297. },
  5298. scaleToContext: function TilingPattern_scaleToContext() {
  5299. var scale = this.scale;
  5300. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5301. },
  5302. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5303. if (bbox && isArray(bbox) && bbox.length === 4) {
  5304. var bboxWidth = x1 - x0;
  5305. var bboxHeight = y1 - y0;
  5306. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5307. graphics.clip();
  5308. graphics.endPath();
  5309. }
  5310. },
  5311. setFillAndStrokeStyleToContext:
  5312. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5313. switch (paintType) {
  5314. case PaintType.COLORED:
  5315. var ctx = this.ctx;
  5316. context.fillStyle = ctx.fillStyle;
  5317. context.strokeStyle = ctx.strokeStyle;
  5318. break;
  5319. case PaintType.UNCOLORED:
  5320. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5321. context.fillStyle = cssColor;
  5322. context.strokeStyle = cssColor;
  5323. break;
  5324. default:
  5325. error('Unsupported paint type: ' + paintType);
  5326. }
  5327. },
  5328. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5329. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5330. ctx = this.ctx;
  5331. ctx.setTransform.apply(ctx, this.baseTransform);
  5332. ctx.transform.apply(ctx, this.matrix);
  5333. this.scaleToContext();
  5334. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5335. }
  5336. };
  5337. return TilingPattern;
  5338. })();
  5339. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  5340. exports.TilingPattern = TilingPattern;
  5341. }));
  5342. (function (root, factory) {
  5343. {
  5344. factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
  5345. root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  5346. }
  5347. }(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) {
  5348. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  5349. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  5350. var ImageKind = sharedUtil.ImageKind;
  5351. var OPS = sharedUtil.OPS;
  5352. var TextRenderingMode = sharedUtil.TextRenderingMode;
  5353. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  5354. var Util = sharedUtil.Util;
  5355. var assert = sharedUtil.assert;
  5356. var info = sharedUtil.info;
  5357. var isNum = sharedUtil.isNum;
  5358. var isArray = sharedUtil.isArray;
  5359. var error = sharedUtil.error;
  5360. var shadow = sharedUtil.shadow;
  5361. var warn = sharedUtil.warn;
  5362. var TilingPattern = displayPatternHelper.TilingPattern;
  5363. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  5364. var WebGLUtils = displayWebGL.WebGLUtils;
  5365. // <canvas> contexts store most of the state we need natively.
  5366. // However, PDF needs a bit more state, which we store here.
  5367. // Minimal font size that would be used during canvas fillText operations.
  5368. var MIN_FONT_SIZE = 16;
  5369. // Maximum font size that would be used during canvas fillText operations.
  5370. var MAX_FONT_SIZE = 100;
  5371. var MAX_GROUP_SIZE = 4096;
  5372. // Heuristic value used when enforcing minimum line widths.
  5373. var MIN_WIDTH_FACTOR = 0.65;
  5374. var COMPILE_TYPE3_GLYPHS = true;
  5375. var MAX_SIZE_TO_COMPILE = 1000;
  5376. var FULL_CHUNK_HEIGHT = 16;
  5377. function createScratchCanvas(width, height) {
  5378. var canvas = document.createElement('canvas');
  5379. canvas.width = width;
  5380. canvas.height = height;
  5381. return canvas;
  5382. }
  5383. function addContextCurrentTransform(ctx) {
  5384. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  5385. if (!ctx.mozCurrentTransform) {
  5386. ctx._originalSave = ctx.save;
  5387. ctx._originalRestore = ctx.restore;
  5388. ctx._originalRotate = ctx.rotate;
  5389. ctx._originalScale = ctx.scale;
  5390. ctx._originalTranslate = ctx.translate;
  5391. ctx._originalTransform = ctx.transform;
  5392. ctx._originalSetTransform = ctx.setTransform;
  5393. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  5394. ctx._transformStack = [];
  5395. Object.defineProperty(ctx, 'mozCurrentTransform', {
  5396. get: function getCurrentTransform() {
  5397. return this._transformMatrix;
  5398. }
  5399. });
  5400. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  5401. get: function getCurrentTransformInverse() {
  5402. // Calculation done using WolframAlpha:
  5403. // http://www.wolframalpha.com/input/?
  5404. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  5405. var m = this._transformMatrix;
  5406. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  5407. var ad_bc = a * d - b * c;
  5408. var bc_ad = b * c - a * d;
  5409. return [
  5410. d / ad_bc,
  5411. b / bc_ad,
  5412. c / bc_ad,
  5413. a / ad_bc,
  5414. (d * e - c * f) / bc_ad,
  5415. (b * e - a * f) / ad_bc
  5416. ];
  5417. }
  5418. });
  5419. ctx.save = function ctxSave() {
  5420. var old = this._transformMatrix;
  5421. this._transformStack.push(old);
  5422. this._transformMatrix = old.slice(0, 6);
  5423. this._originalSave();
  5424. };
  5425. ctx.restore = function ctxRestore() {
  5426. var prev = this._transformStack.pop();
  5427. if (prev) {
  5428. this._transformMatrix = prev;
  5429. this._originalRestore();
  5430. }
  5431. };
  5432. ctx.translate = function ctxTranslate(x, y) {
  5433. var m = this._transformMatrix;
  5434. m[4] = m[0] * x + m[2] * y + m[4];
  5435. m[5] = m[1] * x + m[3] * y + m[5];
  5436. this._originalTranslate(x, y);
  5437. };
  5438. ctx.scale = function ctxScale(x, y) {
  5439. var m = this._transformMatrix;
  5440. m[0] = m[0] * x;
  5441. m[1] = m[1] * x;
  5442. m[2] = m[2] * y;
  5443. m[3] = m[3] * y;
  5444. this._originalScale(x, y);
  5445. };
  5446. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  5447. var m = this._transformMatrix;
  5448. this._transformMatrix = [
  5449. m[0] * a + m[2] * b,
  5450. m[1] * a + m[3] * b,
  5451. m[0] * c + m[2] * d,
  5452. m[1] * c + m[3] * d,
  5453. m[0] * e + m[2] * f + m[4],
  5454. m[1] * e + m[3] * f + m[5]
  5455. ];
  5456. ctx._originalTransform(a, b, c, d, e, f);
  5457. };
  5458. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  5459. this._transformMatrix = [a, b, c, d, e, f];
  5460. ctx._originalSetTransform(a, b, c, d, e, f);
  5461. };
  5462. ctx.rotate = function ctxRotate(angle) {
  5463. var cosValue = Math.cos(angle);
  5464. var sinValue = Math.sin(angle);
  5465. var m = this._transformMatrix;
  5466. this._transformMatrix = [
  5467. m[0] * cosValue + m[2] * sinValue,
  5468. m[1] * cosValue + m[3] * sinValue,
  5469. m[0] * (-sinValue) + m[2] * cosValue,
  5470. m[1] * (-sinValue) + m[3] * cosValue,
  5471. m[4],
  5472. m[5]
  5473. ];
  5474. this._originalRotate(angle);
  5475. };
  5476. }
  5477. }
  5478. var CachedCanvases = (function CachedCanvasesClosure() {
  5479. function CachedCanvases() {
  5480. this.cache = Object.create(null);
  5481. }
  5482. CachedCanvases.prototype = {
  5483. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  5484. trackTransform) {
  5485. var canvasEntry;
  5486. if (this.cache[id] !== undefined) {
  5487. canvasEntry = this.cache[id];
  5488. canvasEntry.canvas.width = width;
  5489. canvasEntry.canvas.height = height;
  5490. // reset canvas transform for emulated mozCurrentTransform, if needed
  5491. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  5492. } else {
  5493. var canvas = createScratchCanvas(width, height);
  5494. var ctx = canvas.getContext('2d');
  5495. if (trackTransform) {
  5496. addContextCurrentTransform(ctx);
  5497. }
  5498. this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  5499. }
  5500. return canvasEntry;
  5501. },
  5502. clear: function () {
  5503. for (var id in this.cache) {
  5504. var canvasEntry = this.cache[id];
  5505. // Zeroing the width and height causes Firefox to release graphics
  5506. // resources immediately, which can greatly reduce memory consumption.
  5507. canvasEntry.canvas.width = 0;
  5508. canvasEntry.canvas.height = 0;
  5509. delete this.cache[id];
  5510. }
  5511. }
  5512. };
  5513. return CachedCanvases;
  5514. })();
  5515. function compileType3Glyph(imgData) {
  5516. var POINT_TO_PROCESS_LIMIT = 1000;
  5517. var width = imgData.width, height = imgData.height;
  5518. var i, j, j0, width1 = width + 1;
  5519. var points = new Uint8Array(width1 * (height + 1));
  5520. var POINT_TYPES =
  5521. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  5522. // decodes bit-packed mask data
  5523. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  5524. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  5525. for (i = 0, ii = data0.length; i < ii; i++) {
  5526. var mask = 128, elem = data0[i];
  5527. while (mask > 0) {
  5528. data[pos++] = (elem & mask) ? 0 : 255;
  5529. mask >>= 1;
  5530. }
  5531. }
  5532. // finding iteresting points: every point is located between mask pixels,
  5533. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  5534. // will have flags assigned based on neighboring mask pixels:
  5535. // 4 | 8
  5536. // --P--
  5537. // 2 | 1
  5538. // We are interested only in points with the flags:
  5539. // - outside corners: 1, 2, 4, 8;
  5540. // - inside corners: 7, 11, 13, 14;
  5541. // - and, intersections: 5, 10.
  5542. var count = 0;
  5543. pos = 0;
  5544. if (data[pos] !== 0) {
  5545. points[0] = 1;
  5546. ++count;
  5547. }
  5548. for (j = 1; j < width; j++) {
  5549. if (data[pos] !== data[pos + 1]) {
  5550. points[j] = data[pos] ? 2 : 1;
  5551. ++count;
  5552. }
  5553. pos++;
  5554. }
  5555. if (data[pos] !== 0) {
  5556. points[j] = 2;
  5557. ++count;
  5558. }
  5559. for (i = 1; i < height; i++) {
  5560. pos = i * lineSize;
  5561. j0 = i * width1;
  5562. if (data[pos - lineSize] !== data[pos]) {
  5563. points[j0] = data[pos] ? 1 : 8;
  5564. ++count;
  5565. }
  5566. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  5567. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  5568. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5569. for (j = 1; j < width; j++) {
  5570. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  5571. (data[pos - lineSize + 1] ? 8 : 0);
  5572. if (POINT_TYPES[sum]) {
  5573. points[j0 + j] = POINT_TYPES[sum];
  5574. ++count;
  5575. }
  5576. pos++;
  5577. }
  5578. if (data[pos - lineSize] !== data[pos]) {
  5579. points[j0 + j] = data[pos] ? 2 : 4;
  5580. ++count;
  5581. }
  5582. if (count > POINT_TO_PROCESS_LIMIT) {
  5583. return null;
  5584. }
  5585. }
  5586. pos = lineSize * (height - 1);
  5587. j0 = i * width1;
  5588. if (data[pos] !== 0) {
  5589. points[j0] = 8;
  5590. ++count;
  5591. }
  5592. for (j = 1; j < width; j++) {
  5593. if (data[pos] !== data[pos + 1]) {
  5594. points[j0 + j] = data[pos] ? 4 : 8;
  5595. ++count;
  5596. }
  5597. pos++;
  5598. }
  5599. if (data[pos] !== 0) {
  5600. points[j0 + j] = 4;
  5601. ++count;
  5602. }
  5603. if (count > POINT_TO_PROCESS_LIMIT) {
  5604. return null;
  5605. }
  5606. // building outlines
  5607. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5608. var outlines = [];
  5609. for (i = 0; count && i <= height; i++) {
  5610. var p = i * width1;
  5611. var end = p + width;
  5612. while (p < end && !points[p]) {
  5613. p++;
  5614. }
  5615. if (p === end) {
  5616. continue;
  5617. }
  5618. var coords = [p % width1, i];
  5619. var type = points[p], p0 = p, pp;
  5620. do {
  5621. var step = steps[type];
  5622. do {
  5623. p += step;
  5624. } while (!points[p]);
  5625. pp = points[p];
  5626. if (pp !== 5 && pp !== 10) {
  5627. // set new direction
  5628. type = pp;
  5629. // delete mark
  5630. points[p] = 0;
  5631. } else { // type is 5 or 10, ie, a crossing
  5632. // set new direction
  5633. type = pp & ((0x33 * type) >> 4);
  5634. // set new type for "future hit"
  5635. points[p] &= (type >> 2 | type << 2);
  5636. }
  5637. coords.push(p % width1);
  5638. coords.push((p / width1) | 0);
  5639. --count;
  5640. } while (p0 !== p);
  5641. outlines.push(coords);
  5642. --i;
  5643. }
  5644. var drawOutline = function(c) {
  5645. c.save();
  5646. // the path shall be painted in [0..1]x[0..1] space
  5647. c.scale(1 / width, -1 / height);
  5648. c.translate(0, -height);
  5649. c.beginPath();
  5650. for (var i = 0, ii = outlines.length; i < ii; i++) {
  5651. var o = outlines[i];
  5652. c.moveTo(o[0], o[1]);
  5653. for (var j = 2, jj = o.length; j < jj; j += 2) {
  5654. c.lineTo(o[j], o[j+1]);
  5655. }
  5656. }
  5657. c.fill();
  5658. c.beginPath();
  5659. c.restore();
  5660. };
  5661. return drawOutline;
  5662. }
  5663. var CanvasExtraState = (function CanvasExtraStateClosure() {
  5664. function CanvasExtraState(old) {
  5665. // Are soft masks and alpha values shapes or opacities?
  5666. this.alphaIsShape = false;
  5667. this.fontSize = 0;
  5668. this.fontSizeScale = 1;
  5669. this.textMatrix = IDENTITY_MATRIX;
  5670. this.textMatrixScale = 1;
  5671. this.fontMatrix = FONT_IDENTITY_MATRIX;
  5672. this.leading = 0;
  5673. // Current point (in user coordinates)
  5674. this.x = 0;
  5675. this.y = 0;
  5676. // Start of text line (in text coordinates)
  5677. this.lineX = 0;
  5678. this.lineY = 0;
  5679. // Character and word spacing
  5680. this.charSpacing = 0;
  5681. this.wordSpacing = 0;
  5682. this.textHScale = 1;
  5683. this.textRenderingMode = TextRenderingMode.FILL;
  5684. this.textRise = 0;
  5685. // Default fore and background colors
  5686. this.fillColor = '#000000';
  5687. this.strokeColor = '#000000';
  5688. this.patternFill = false;
  5689. // Note: fill alpha applies to all non-stroking operations
  5690. this.fillAlpha = 1;
  5691. this.strokeAlpha = 1;
  5692. this.lineWidth = 1;
  5693. this.activeSMask = null; // nonclonable field (see the save method below)
  5694. this.old = old;
  5695. }
  5696. CanvasExtraState.prototype = {
  5697. clone: function CanvasExtraState_clone() {
  5698. return Object.create(this);
  5699. },
  5700. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  5701. this.x = x;
  5702. this.y = y;
  5703. }
  5704. };
  5705. return CanvasExtraState;
  5706. })();
  5707. var CanvasGraphics = (function CanvasGraphicsClosure() {
  5708. // Defines the time the executeOperatorList is going to be executing
  5709. // before it stops and shedules a continue of execution.
  5710. var EXECUTION_TIME = 15;
  5711. // Defines the number of steps before checking the execution time
  5712. var EXECUTION_STEPS = 10;
  5713. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  5714. this.ctx = canvasCtx;
  5715. this.current = new CanvasExtraState();
  5716. this.stateStack = [];
  5717. this.pendingClip = null;
  5718. this.pendingEOFill = false;
  5719. this.res = null;
  5720. this.xobjs = null;
  5721. this.commonObjs = commonObjs;
  5722. this.objs = objs;
  5723. this.imageLayer = imageLayer;
  5724. this.groupStack = [];
  5725. this.processingType3 = null;
  5726. // Patterns are painted relative to the initial page/form transform, see pdf
  5727. // spec 8.7.2 NOTE 1.
  5728. this.baseTransform = null;
  5729. this.baseTransformStack = [];
  5730. this.groupLevel = 0;
  5731. this.smaskStack = [];
  5732. this.smaskCounter = 0;
  5733. this.tempSMask = null;
  5734. this.cachedCanvases = new CachedCanvases();
  5735. if (canvasCtx) {
  5736. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  5737. // the transformation must already be set in canvasCtx._transformMatrix.
  5738. addContextCurrentTransform(canvasCtx);
  5739. }
  5740. this.cachedGetSinglePixelWidth = null;
  5741. }
  5742. function putBinaryImageData(ctx, imgData) {
  5743. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  5744. ctx.putImageData(imgData, 0, 0);
  5745. return;
  5746. }
  5747. // Put the image data to the canvas in chunks, rather than putting the
  5748. // whole image at once. This saves JS memory, because the ImageData object
  5749. // is smaller. It also possibly saves C++ memory within the implementation
  5750. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  5751. // the data passed to putImageData()). |n| shouldn't be too small, however,
  5752. // because too many putImageData() calls will slow things down.
  5753. //
  5754. // Note: as written, if the last chunk is partial, the putImageData() call
  5755. // will (conceptually) put pixels past the bounds of the canvas. But
  5756. // that's ok; any such pixels are ignored.
  5757. var height = imgData.height, width = imgData.width;
  5758. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5759. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5760. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5761. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5762. var srcPos = 0, destPos;
  5763. var src = imgData.data;
  5764. var dest = chunkImgData.data;
  5765. var i, j, thisChunkHeight, elemsInThisChunk;
  5766. // There are multiple forms in which the pixel data can be passed, and
  5767. // imgData.kind tells us which one this is.
  5768. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  5769. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  5770. var srcLength = src.byteLength;
  5771. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  5772. new Uint32ArrayView(dest);
  5773. var dest32DataLength = dest32.length;
  5774. var fullSrcDiff = (width + 7) >> 3;
  5775. var white = 0xFFFFFFFF;
  5776. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  5777. 0xFF000000 : 0x000000FF;
  5778. for (i = 0; i < totalChunks; i++) {
  5779. thisChunkHeight =
  5780. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5781. destPos = 0;
  5782. for (j = 0; j < thisChunkHeight; j++) {
  5783. var srcDiff = srcLength - srcPos;
  5784. var k = 0;
  5785. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  5786. var kEndUnrolled = kEnd & ~7;
  5787. var mask = 0;
  5788. var srcByte = 0;
  5789. for (; k < kEndUnrolled; k += 8) {
  5790. srcByte = src[srcPos++];
  5791. dest32[destPos++] = (srcByte & 128) ? white : black;
  5792. dest32[destPos++] = (srcByte & 64) ? white : black;
  5793. dest32[destPos++] = (srcByte & 32) ? white : black;
  5794. dest32[destPos++] = (srcByte & 16) ? white : black;
  5795. dest32[destPos++] = (srcByte & 8) ? white : black;
  5796. dest32[destPos++] = (srcByte & 4) ? white : black;
  5797. dest32[destPos++] = (srcByte & 2) ? white : black;
  5798. dest32[destPos++] = (srcByte & 1) ? white : black;
  5799. }
  5800. for (; k < kEnd; k++) {
  5801. if (mask === 0) {
  5802. srcByte = src[srcPos++];
  5803. mask = 128;
  5804. }
  5805. dest32[destPos++] = (srcByte & mask) ? white : black;
  5806. mask >>= 1;
  5807. }
  5808. }
  5809. // We ran out of input. Make all remaining pixels transparent.
  5810. while (destPos < dest32DataLength) {
  5811. dest32[destPos++] = 0;
  5812. }
  5813. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5814. }
  5815. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  5816. // RGBA, 32-bits per pixel.
  5817. j = 0;
  5818. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5819. for (i = 0; i < fullChunks; i++) {
  5820. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5821. srcPos += elemsInThisChunk;
  5822. ctx.putImageData(chunkImgData, 0, j);
  5823. j += FULL_CHUNK_HEIGHT;
  5824. }
  5825. if (i < totalChunks) {
  5826. elemsInThisChunk = width * partialChunkHeight * 4;
  5827. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5828. ctx.putImageData(chunkImgData, 0, j);
  5829. }
  5830. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  5831. // RGB, 24-bits per pixel.
  5832. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5833. elemsInThisChunk = width * thisChunkHeight;
  5834. for (i = 0; i < totalChunks; i++) {
  5835. if (i >= fullChunks) {
  5836. thisChunkHeight = partialChunkHeight;
  5837. elemsInThisChunk = width * thisChunkHeight;
  5838. }
  5839. destPos = 0;
  5840. for (j = elemsInThisChunk; j--;) {
  5841. dest[destPos++] = src[srcPos++];
  5842. dest[destPos++] = src[srcPos++];
  5843. dest[destPos++] = src[srcPos++];
  5844. dest[destPos++] = 255;
  5845. }
  5846. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5847. }
  5848. } else {
  5849. error('bad image kind: ' + imgData.kind);
  5850. }
  5851. }
  5852. function putBinaryImageMask(ctx, imgData) {
  5853. var height = imgData.height, width = imgData.width;
  5854. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5855. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5856. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5857. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5858. var srcPos = 0;
  5859. var src = imgData.data;
  5860. var dest = chunkImgData.data;
  5861. for (var i = 0; i < totalChunks; i++) {
  5862. var thisChunkHeight =
  5863. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5864. // Expand the mask so it can be used by the canvas. Any required
  5865. // inversion has already been handled.
  5866. var destPos = 3; // alpha component offset
  5867. for (var j = 0; j < thisChunkHeight; j++) {
  5868. var mask = 0;
  5869. for (var k = 0; k < width; k++) {
  5870. if (!mask) {
  5871. var elem = src[srcPos++];
  5872. mask = 128;
  5873. }
  5874. dest[destPos] = (elem & mask) ? 0 : 255;
  5875. destPos += 4;
  5876. mask >>= 1;
  5877. }
  5878. }
  5879. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5880. }
  5881. }
  5882. function copyCtxState(sourceCtx, destCtx) {
  5883. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  5884. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  5885. 'globalCompositeOperation', 'font'];
  5886. for (var i = 0, ii = properties.length; i < ii; i++) {
  5887. var property = properties[i];
  5888. if (sourceCtx[property] !== undefined) {
  5889. destCtx[property] = sourceCtx[property];
  5890. }
  5891. }
  5892. if (sourceCtx.setLineDash !== undefined) {
  5893. destCtx.setLineDash(sourceCtx.getLineDash());
  5894. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5895. } else if (sourceCtx.mozDashOffset !== undefined) {
  5896. destCtx.mozDash = sourceCtx.mozDash;
  5897. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  5898. }
  5899. }
  5900. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5901. var length = bytes.length;
  5902. for (var i = 3; i < length; i += 4) {
  5903. var alpha = bytes[i];
  5904. if (alpha === 0) {
  5905. bytes[i - 3] = r0;
  5906. bytes[i - 2] = g0;
  5907. bytes[i - 1] = b0;
  5908. } else if (alpha < 255) {
  5909. var alpha_ = 255 - alpha;
  5910. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  5911. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  5912. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  5913. }
  5914. }
  5915. }
  5916. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5917. var length = maskData.length;
  5918. var scale = 1 / 255;
  5919. for (var i = 3; i < length; i += 4) {
  5920. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5921. layerData[i] = (layerData[i] * alpha * scale) | 0;
  5922. }
  5923. }
  5924. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5925. var length = maskData.length;
  5926. for (var i = 3; i < length; i += 4) {
  5927. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  5928. (maskData[i - 2] * 152) + // * 0.59 ....
  5929. (maskData[i - 1] * 28); // * 0.11 ....
  5930. layerData[i] = transferMap ?
  5931. (layerData[i] * transferMap[y >> 8]) >> 8 :
  5932. (layerData[i] * y) >> 16;
  5933. }
  5934. }
  5935. function genericComposeSMask(maskCtx, layerCtx, width, height,
  5936. subtype, backdrop, transferMap) {
  5937. var hasBackdrop = !!backdrop;
  5938. var r0 = hasBackdrop ? backdrop[0] : 0;
  5939. var g0 = hasBackdrop ? backdrop[1] : 0;
  5940. var b0 = hasBackdrop ? backdrop[2] : 0;
  5941. var composeFn;
  5942. if (subtype === 'Luminosity') {
  5943. composeFn = composeSMaskLuminosity;
  5944. } else {
  5945. composeFn = composeSMaskAlpha;
  5946. }
  5947. // processing image in chunks to save memory
  5948. var PIXELS_TO_PROCESS = 1048576;
  5949. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5950. for (var row = 0; row < height; row += chunkSize) {
  5951. var chunkHeight = Math.min(chunkSize, height - row);
  5952. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  5953. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  5954. if (hasBackdrop) {
  5955. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5956. }
  5957. composeFn(maskData.data, layerData.data, transferMap);
  5958. maskCtx.putImageData(layerData, 0, row);
  5959. }
  5960. }
  5961. function composeSMask(ctx, smask, layerCtx) {
  5962. var mask = smask.canvas;
  5963. var maskCtx = smask.context;
  5964. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  5965. smask.offsetX, smask.offsetY);
  5966. var backdrop = smask.backdrop || null;
  5967. if (!smask.transferMap && WebGLUtils.isEnabled) {
  5968. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  5969. {subtype: smask.subtype, backdrop: backdrop});
  5970. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5971. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  5972. return;
  5973. }
  5974. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  5975. smask.subtype, backdrop, smask.transferMap);
  5976. ctx.drawImage(mask, 0, 0);
  5977. }
  5978. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  5979. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  5980. var NORMAL_CLIP = {};
  5981. var EO_CLIP = {};
  5982. CanvasGraphics.prototype = {
  5983. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
  5984. transparency) {
  5985. // For pdfs that use blend modes we have to clear the canvas else certain
  5986. // blend modes can look wrong since we'd be blending with a white
  5987. // backdrop. The problem with a transparent backdrop though is we then
  5988. // don't get sub pixel anti aliasing on text, creating temporary
  5989. // transparent canvas when we have blend modes.
  5990. var width = this.ctx.canvas.width;
  5991. var height = this.ctx.canvas.height;
  5992. this.ctx.save();
  5993. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  5994. this.ctx.fillRect(0, 0, width, height);
  5995. this.ctx.restore();
  5996. if (transparency) {
  5997. var transparentCanvas = this.cachedCanvases.getCanvas(
  5998. 'transparent', width, height, true);
  5999. this.compositeCtx = this.ctx;
  6000. this.transparentCanvas = transparentCanvas.canvas;
  6001. this.ctx = transparentCanvas.context;
  6002. this.ctx.save();
  6003. // The transform can be applied before rendering, transferring it to
  6004. // the new canvas.
  6005. this.ctx.transform.apply(this.ctx,
  6006. this.compositeCtx.mozCurrentTransform);
  6007. }
  6008. this.ctx.save();
  6009. if (transform) {
  6010. this.ctx.transform.apply(this.ctx, transform);
  6011. }
  6012. this.ctx.transform.apply(this.ctx, viewport.transform);
  6013. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6014. if (this.imageLayer) {
  6015. this.imageLayer.beginLayout();
  6016. }
  6017. },
  6018. executeOperatorList: function CanvasGraphics_executeOperatorList(
  6019. operatorList,
  6020. executionStartIdx, continueCallback,
  6021. stepper) {
  6022. var argsArray = operatorList.argsArray;
  6023. var fnArray = operatorList.fnArray;
  6024. var i = executionStartIdx || 0;
  6025. var argsArrayLen = argsArray.length;
  6026. // Sometimes the OperatorList to execute is empty.
  6027. if (argsArrayLen === i) {
  6028. return i;
  6029. }
  6030. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  6031. typeof continueCallback === 'function');
  6032. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6033. var steps = 0;
  6034. var commonObjs = this.commonObjs;
  6035. var objs = this.objs;
  6036. var fnId;
  6037. while (true) {
  6038. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6039. stepper.breakIt(i, continueCallback);
  6040. return i;
  6041. }
  6042. fnId = fnArray[i];
  6043. if (fnId !== OPS.dependency) {
  6044. this[fnId].apply(this, argsArray[i]);
  6045. } else {
  6046. var deps = argsArray[i];
  6047. for (var n = 0, nn = deps.length; n < nn; n++) {
  6048. var depObjId = deps[n];
  6049. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6050. var objsPool = common ? commonObjs : objs;
  6051. // If the promise isn't resolved yet, add the continueCallback
  6052. // to the promise and bail out.
  6053. if (!objsPool.isResolved(depObjId)) {
  6054. objsPool.get(depObjId, continueCallback);
  6055. return i;
  6056. }
  6057. }
  6058. }
  6059. i++;
  6060. // If the entire operatorList was executed, stop as were done.
  6061. if (i === argsArrayLen) {
  6062. return i;
  6063. }
  6064. // If the execution took longer then a certain amount of time and
  6065. // `continueCallback` is specified, interrupt the execution.
  6066. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6067. if (Date.now() > endTime) {
  6068. continueCallback();
  6069. return i;
  6070. }
  6071. steps = 0;
  6072. }
  6073. // If the operatorList isn't executed completely yet OR the execution
  6074. // time was short enough, do another execution round.
  6075. }
  6076. },
  6077. endDrawing: function CanvasGraphics_endDrawing() {
  6078. this.ctx.restore();
  6079. if (this.transparentCanvas) {
  6080. this.ctx = this.compositeCtx;
  6081. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6082. this.transparentCanvas = null;
  6083. }
  6084. this.cachedCanvases.clear();
  6085. WebGLUtils.clear();
  6086. if (this.imageLayer) {
  6087. this.imageLayer.endLayout();
  6088. }
  6089. },
  6090. // Graphics state
  6091. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6092. this.current.lineWidth = width;
  6093. this.ctx.lineWidth = width;
  6094. },
  6095. setLineCap: function CanvasGraphics_setLineCap(style) {
  6096. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6097. },
  6098. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6099. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6100. },
  6101. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6102. this.ctx.miterLimit = limit;
  6103. },
  6104. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6105. var ctx = this.ctx;
  6106. if (ctx.setLineDash !== undefined) {
  6107. ctx.setLineDash(dashArray);
  6108. ctx.lineDashOffset = dashPhase;
  6109. } else {
  6110. ctx.mozDash = dashArray;
  6111. ctx.mozDashOffset = dashPhase;
  6112. }
  6113. },
  6114. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6115. // Maybe if we one day fully support color spaces this will be important
  6116. // for now we can ignore.
  6117. // TODO set rendering intent?
  6118. },
  6119. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6120. // There's no way to control this with canvas, but we can safely ignore.
  6121. // TODO set flatness?
  6122. },
  6123. setGState: function CanvasGraphics_setGState(states) {
  6124. for (var i = 0, ii = states.length; i < ii; i++) {
  6125. var state = states[i];
  6126. var key = state[0];
  6127. var value = state[1];
  6128. switch (key) {
  6129. case 'LW':
  6130. this.setLineWidth(value);
  6131. break;
  6132. case 'LC':
  6133. this.setLineCap(value);
  6134. break;
  6135. case 'LJ':
  6136. this.setLineJoin(value);
  6137. break;
  6138. case 'ML':
  6139. this.setMiterLimit(value);
  6140. break;
  6141. case 'D':
  6142. this.setDash(value[0], value[1]);
  6143. break;
  6144. case 'RI':
  6145. this.setRenderingIntent(value);
  6146. break;
  6147. case 'FL':
  6148. this.setFlatness(value);
  6149. break;
  6150. case 'Font':
  6151. this.setFont(value[0], value[1]);
  6152. break;
  6153. case 'CA':
  6154. this.current.strokeAlpha = state[1];
  6155. break;
  6156. case 'ca':
  6157. this.current.fillAlpha = state[1];
  6158. this.ctx.globalAlpha = state[1];
  6159. break;
  6160. case 'BM':
  6161. if (value && value.name && (value.name !== 'Normal')) {
  6162. var mode = value.name.replace(/([A-Z])/g,
  6163. function(c) {
  6164. return '-' + c.toLowerCase();
  6165. }
  6166. ).substring(1);
  6167. this.ctx.globalCompositeOperation = mode;
  6168. if (this.ctx.globalCompositeOperation !== mode) {
  6169. warn('globalCompositeOperation "' + mode +
  6170. '" is not supported');
  6171. }
  6172. } else {
  6173. this.ctx.globalCompositeOperation = 'source-over';
  6174. }
  6175. break;
  6176. case 'SMask':
  6177. if (this.current.activeSMask) {
  6178. this.endSMaskGroup();
  6179. }
  6180. this.current.activeSMask = value ? this.tempSMask : null;
  6181. if (this.current.activeSMask) {
  6182. this.beginSMaskGroup();
  6183. }
  6184. this.tempSMask = null;
  6185. break;
  6186. }
  6187. }
  6188. },
  6189. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6190. var activeSMask = this.current.activeSMask;
  6191. var drawnWidth = activeSMask.canvas.width;
  6192. var drawnHeight = activeSMask.canvas.height;
  6193. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6194. var scratchCanvas = this.cachedCanvases.getCanvas(
  6195. cacheId, drawnWidth, drawnHeight, true);
  6196. var currentCtx = this.ctx;
  6197. var currentTransform = currentCtx.mozCurrentTransform;
  6198. this.ctx.save();
  6199. var groupCtx = scratchCanvas.context;
  6200. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6201. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6202. groupCtx.transform.apply(groupCtx, currentTransform);
  6203. copyCtxState(currentCtx, groupCtx);
  6204. this.ctx = groupCtx;
  6205. this.setGState([
  6206. ['BM', 'Normal'],
  6207. ['ca', 1],
  6208. ['CA', 1]
  6209. ]);
  6210. this.groupStack.push(currentCtx);
  6211. this.groupLevel++;
  6212. },
  6213. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6214. var groupCtx = this.ctx;
  6215. this.groupLevel--;
  6216. this.ctx = this.groupStack.pop();
  6217. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6218. this.ctx.restore();
  6219. copyCtxState(groupCtx, this.ctx);
  6220. },
  6221. save: function CanvasGraphics_save() {
  6222. this.ctx.save();
  6223. var old = this.current;
  6224. this.stateStack.push(old);
  6225. this.current = old.clone();
  6226. this.current.activeSMask = null;
  6227. },
  6228. restore: function CanvasGraphics_restore() {
  6229. if (this.stateStack.length !== 0) {
  6230. if (this.current.activeSMask !== null) {
  6231. this.endSMaskGroup();
  6232. }
  6233. this.current = this.stateStack.pop();
  6234. this.ctx.restore();
  6235. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  6236. this.pendingClip = null;
  6237. this.cachedGetSinglePixelWidth = null;
  6238. }
  6239. },
  6240. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  6241. this.ctx.transform(a, b, c, d, e, f);
  6242. this.cachedGetSinglePixelWidth = null;
  6243. },
  6244. // Path
  6245. constructPath: function CanvasGraphics_constructPath(ops, args) {
  6246. var ctx = this.ctx;
  6247. var current = this.current;
  6248. var x = current.x, y = current.y;
  6249. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6250. switch (ops[i] | 0) {
  6251. case OPS.rectangle:
  6252. x = args[j++];
  6253. y = args[j++];
  6254. var width = args[j++];
  6255. var height = args[j++];
  6256. if (width === 0) {
  6257. width = this.getSinglePixelWidth();
  6258. }
  6259. if (height === 0) {
  6260. height = this.getSinglePixelWidth();
  6261. }
  6262. var xw = x + width;
  6263. var yh = y + height;
  6264. this.ctx.moveTo(x, y);
  6265. this.ctx.lineTo(xw, y);
  6266. this.ctx.lineTo(xw, yh);
  6267. this.ctx.lineTo(x, yh);
  6268. this.ctx.lineTo(x, y);
  6269. this.ctx.closePath();
  6270. break;
  6271. case OPS.moveTo:
  6272. x = args[j++];
  6273. y = args[j++];
  6274. ctx.moveTo(x, y);
  6275. break;
  6276. case OPS.lineTo:
  6277. x = args[j++];
  6278. y = args[j++];
  6279. ctx.lineTo(x, y);
  6280. break;
  6281. case OPS.curveTo:
  6282. x = args[j + 4];
  6283. y = args[j + 5];
  6284. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  6285. x, y);
  6286. j += 6;
  6287. break;
  6288. case OPS.curveTo2:
  6289. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  6290. args[j + 2], args[j + 3]);
  6291. x = args[j + 2];
  6292. y = args[j + 3];
  6293. j += 4;
  6294. break;
  6295. case OPS.curveTo3:
  6296. x = args[j + 2];
  6297. y = args[j + 3];
  6298. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6299. j += 4;
  6300. break;
  6301. case OPS.closePath:
  6302. ctx.closePath();
  6303. break;
  6304. }
  6305. }
  6306. current.setCurrentPoint(x, y);
  6307. },
  6308. closePath: function CanvasGraphics_closePath() {
  6309. this.ctx.closePath();
  6310. },
  6311. stroke: function CanvasGraphics_stroke(consumePath) {
  6312. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6313. var ctx = this.ctx;
  6314. var strokeColor = this.current.strokeColor;
  6315. // Prevent drawing too thin lines by enforcing a minimum line width.
  6316. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  6317. this.current.lineWidth);
  6318. // For stroke we want to temporarily change the global alpha to the
  6319. // stroking alpha.
  6320. ctx.globalAlpha = this.current.strokeAlpha;
  6321. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  6322. strokeColor.type === 'Pattern') {
  6323. // for patterns, we transform to pattern space, calculate
  6324. // the pattern, call stroke, and restore to user space
  6325. ctx.save();
  6326. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  6327. ctx.stroke();
  6328. ctx.restore();
  6329. } else {
  6330. ctx.stroke();
  6331. }
  6332. if (consumePath) {
  6333. this.consumePath();
  6334. }
  6335. // Restore the global alpha to the fill alpha
  6336. ctx.globalAlpha = this.current.fillAlpha;
  6337. },
  6338. closeStroke: function CanvasGraphics_closeStroke() {
  6339. this.closePath();
  6340. this.stroke();
  6341. },
  6342. fill: function CanvasGraphics_fill(consumePath) {
  6343. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6344. var ctx = this.ctx;
  6345. var fillColor = this.current.fillColor;
  6346. var isPatternFill = this.current.patternFill;
  6347. var needRestore = false;
  6348. if (isPatternFill) {
  6349. ctx.save();
  6350. if (this.baseTransform) {
  6351. ctx.setTransform.apply(ctx, this.baseTransform);
  6352. }
  6353. ctx.fillStyle = fillColor.getPattern(ctx, this);
  6354. needRestore = true;
  6355. }
  6356. if (this.pendingEOFill) {
  6357. if (ctx.mozFillRule !== undefined) {
  6358. ctx.mozFillRule = 'evenodd';
  6359. ctx.fill();
  6360. ctx.mozFillRule = 'nonzero';
  6361. } else {
  6362. ctx.fill('evenodd');
  6363. }
  6364. this.pendingEOFill = false;
  6365. } else {
  6366. ctx.fill();
  6367. }
  6368. if (needRestore) {
  6369. ctx.restore();
  6370. }
  6371. if (consumePath) {
  6372. this.consumePath();
  6373. }
  6374. },
  6375. eoFill: function CanvasGraphics_eoFill() {
  6376. this.pendingEOFill = true;
  6377. this.fill();
  6378. },
  6379. fillStroke: function CanvasGraphics_fillStroke() {
  6380. this.fill(false);
  6381. this.stroke(false);
  6382. this.consumePath();
  6383. },
  6384. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  6385. this.pendingEOFill = true;
  6386. this.fillStroke();
  6387. },
  6388. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  6389. this.closePath();
  6390. this.fillStroke();
  6391. },
  6392. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  6393. this.pendingEOFill = true;
  6394. this.closePath();
  6395. this.fillStroke();
  6396. },
  6397. endPath: function CanvasGraphics_endPath() {
  6398. this.consumePath();
  6399. },
  6400. // Clipping
  6401. clip: function CanvasGraphics_clip() {
  6402. this.pendingClip = NORMAL_CLIP;
  6403. },
  6404. eoClip: function CanvasGraphics_eoClip() {
  6405. this.pendingClip = EO_CLIP;
  6406. },
  6407. // Text
  6408. beginText: function CanvasGraphics_beginText() {
  6409. this.current.textMatrix = IDENTITY_MATRIX;
  6410. this.current.textMatrixScale = 1;
  6411. this.current.x = this.current.lineX = 0;
  6412. this.current.y = this.current.lineY = 0;
  6413. },
  6414. endText: function CanvasGraphics_endText() {
  6415. var paths = this.pendingTextPaths;
  6416. var ctx = this.ctx;
  6417. if (paths === undefined) {
  6418. ctx.beginPath();
  6419. return;
  6420. }
  6421. ctx.save();
  6422. ctx.beginPath();
  6423. for (var i = 0; i < paths.length; i++) {
  6424. var path = paths[i];
  6425. ctx.setTransform.apply(ctx, path.transform);
  6426. ctx.translate(path.x, path.y);
  6427. path.addToPath(ctx, path.fontSize);
  6428. }
  6429. ctx.restore();
  6430. ctx.clip();
  6431. ctx.beginPath();
  6432. delete this.pendingTextPaths;
  6433. },
  6434. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  6435. this.current.charSpacing = spacing;
  6436. },
  6437. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  6438. this.current.wordSpacing = spacing;
  6439. },
  6440. setHScale: function CanvasGraphics_setHScale(scale) {
  6441. this.current.textHScale = scale / 100;
  6442. },
  6443. setLeading: function CanvasGraphics_setLeading(leading) {
  6444. this.current.leading = -leading;
  6445. },
  6446. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  6447. var fontObj = this.commonObjs.get(fontRefName);
  6448. var current = this.current;
  6449. if (!fontObj) {
  6450. error('Can\'t find font for ' + fontRefName);
  6451. }
  6452. current.fontMatrix = (fontObj.fontMatrix ?
  6453. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6454. // A valid matrix needs all main diagonal elements to be non-zero
  6455. // This also ensures we bypass FF bugzilla bug #719844.
  6456. if (current.fontMatrix[0] === 0 ||
  6457. current.fontMatrix[3] === 0) {
  6458. warn('Invalid font matrix for font ' + fontRefName);
  6459. }
  6460. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  6461. // and in some docs this can be negative (inverted x-y axes).
  6462. if (size < 0) {
  6463. size = -size;
  6464. current.fontDirection = -1;
  6465. } else {
  6466. current.fontDirection = 1;
  6467. }
  6468. this.current.font = fontObj;
  6469. this.current.fontSize = size;
  6470. if (fontObj.isType3Font) {
  6471. return; // we don't need ctx.font for Type3 fonts
  6472. }
  6473. var name = fontObj.loadedName || 'sans-serif';
  6474. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  6475. (fontObj.bold ? 'bold' : 'normal');
  6476. var italic = fontObj.italic ? 'italic' : 'normal';
  6477. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  6478. // Some font backends cannot handle fonts below certain size.
  6479. // Keeping the font at minimal size and using the fontSizeScale to change
  6480. // the current transformation matrix before the fillText/strokeText.
  6481. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  6482. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  6483. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  6484. this.current.fontSizeScale = size / browserFontSize;
  6485. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  6486. this.ctx.font = rule;
  6487. },
  6488. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  6489. this.current.textRenderingMode = mode;
  6490. },
  6491. setTextRise: function CanvasGraphics_setTextRise(rise) {
  6492. this.current.textRise = rise;
  6493. },
  6494. moveText: function CanvasGraphics_moveText(x, y) {
  6495. this.current.x = this.current.lineX += x;
  6496. this.current.y = this.current.lineY += y;
  6497. },
  6498. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  6499. this.setLeading(-y);
  6500. this.moveText(x, y);
  6501. },
  6502. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  6503. this.current.textMatrix = [a, b, c, d, e, f];
  6504. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  6505. this.current.x = this.current.lineX = 0;
  6506. this.current.y = this.current.lineY = 0;
  6507. },
  6508. nextLine: function CanvasGraphics_nextLine() {
  6509. this.moveText(0, this.current.leading);
  6510. },
  6511. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  6512. var ctx = this.ctx;
  6513. var current = this.current;
  6514. var font = current.font;
  6515. var textRenderingMode = current.textRenderingMode;
  6516. var fontSize = current.fontSize / current.fontSizeScale;
  6517. var fillStrokeMode = textRenderingMode &
  6518. TextRenderingMode.FILL_STROKE_MASK;
  6519. var isAddToPathSet = !!(textRenderingMode &
  6520. TextRenderingMode.ADD_TO_PATH_FLAG);
  6521. var addToPath;
  6522. if (font.disableFontFace || isAddToPathSet) {
  6523. addToPath = font.getPathGenerator(this.commonObjs, character);
  6524. }
  6525. if (font.disableFontFace) {
  6526. ctx.save();
  6527. ctx.translate(x, y);
  6528. ctx.beginPath();
  6529. addToPath(ctx, fontSize);
  6530. if (fillStrokeMode === TextRenderingMode.FILL ||
  6531. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6532. ctx.fill();
  6533. }
  6534. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6535. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6536. ctx.stroke();
  6537. }
  6538. ctx.restore();
  6539. } else {
  6540. if (fillStrokeMode === TextRenderingMode.FILL ||
  6541. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6542. ctx.fillText(character, x, y);
  6543. }
  6544. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6545. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6546. ctx.strokeText(character, x, y);
  6547. }
  6548. }
  6549. if (isAddToPathSet) {
  6550. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6551. paths.push({
  6552. transform: ctx.mozCurrentTransform,
  6553. x: x,
  6554. y: y,
  6555. fontSize: fontSize,
  6556. addToPath: addToPath
  6557. });
  6558. }
  6559. },
  6560. get isFontSubpixelAAEnabled() {
  6561. // Checks if anti-aliasing is enabled when scaled text is painted.
  6562. // On Windows GDI scaled fonts looks bad.
  6563. var ctx = document.createElement('canvas').getContext('2d');
  6564. ctx.scale(1.5, 1);
  6565. ctx.fillText('I', 0, 10);
  6566. var data = ctx.getImageData(0, 0, 10, 10).data;
  6567. var enabled = false;
  6568. for (var i = 3; i < data.length; i += 4) {
  6569. if (data[i] > 0 && data[i] < 255) {
  6570. enabled = true;
  6571. break;
  6572. }
  6573. }
  6574. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  6575. },
  6576. showText: function CanvasGraphics_showText(glyphs) {
  6577. var current = this.current;
  6578. var font = current.font;
  6579. if (font.isType3Font) {
  6580. return this.showType3Text(glyphs);
  6581. }
  6582. var fontSize = current.fontSize;
  6583. if (fontSize === 0) {
  6584. return;
  6585. }
  6586. var ctx = this.ctx;
  6587. var fontSizeScale = current.fontSizeScale;
  6588. var charSpacing = current.charSpacing;
  6589. var wordSpacing = current.wordSpacing;
  6590. var fontDirection = current.fontDirection;
  6591. var textHScale = current.textHScale * fontDirection;
  6592. var glyphsLength = glyphs.length;
  6593. var vertical = font.vertical;
  6594. var spacingDir = vertical ? 1 : -1;
  6595. var defaultVMetrics = font.defaultVMetrics;
  6596. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6597. var simpleFillText =
  6598. current.textRenderingMode === TextRenderingMode.FILL &&
  6599. !font.disableFontFace;
  6600. ctx.save();
  6601. ctx.transform.apply(ctx, current.textMatrix);
  6602. ctx.translate(current.x, current.y + current.textRise);
  6603. if (current.patternFill) {
  6604. // TODO: Some shading patterns are not applied correctly to text,
  6605. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  6606. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  6607. }
  6608. if (fontDirection > 0) {
  6609. ctx.scale(textHScale, -1);
  6610. } else {
  6611. ctx.scale(textHScale, 1);
  6612. }
  6613. var lineWidth = current.lineWidth;
  6614. var scale = current.textMatrixScale;
  6615. if (scale === 0 || lineWidth === 0) {
  6616. var fillStrokeMode = current.textRenderingMode &
  6617. TextRenderingMode.FILL_STROKE_MASK;
  6618. if (fillStrokeMode === TextRenderingMode.STROKE ||
  6619. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6620. this.cachedGetSinglePixelWidth = null;
  6621. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  6622. }
  6623. } else {
  6624. lineWidth /= scale;
  6625. }
  6626. if (fontSizeScale !== 1.0) {
  6627. ctx.scale(fontSizeScale, fontSizeScale);
  6628. lineWidth /= fontSizeScale;
  6629. }
  6630. ctx.lineWidth = lineWidth;
  6631. var x = 0, i;
  6632. for (i = 0; i < glyphsLength; ++i) {
  6633. var glyph = glyphs[i];
  6634. if (isNum(glyph)) {
  6635. x += spacingDir * glyph * fontSize / 1000;
  6636. continue;
  6637. }
  6638. var restoreNeeded = false;
  6639. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6640. var character = glyph.fontChar;
  6641. var accent = glyph.accent;
  6642. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  6643. var width = glyph.width;
  6644. if (vertical) {
  6645. var vmetric, vx, vy;
  6646. vmetric = glyph.vmetric || defaultVMetrics;
  6647. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  6648. vx = -vx * widthAdvanceScale;
  6649. vy = vmetric[2] * widthAdvanceScale;
  6650. width = vmetric ? -vmetric[0] : width;
  6651. scaledX = vx / fontSizeScale;
  6652. scaledY = (x + vy) / fontSizeScale;
  6653. } else {
  6654. scaledX = x / fontSizeScale;
  6655. scaledY = 0;
  6656. }
  6657. if (font.remeasure && width > 0) {
  6658. // Some standard fonts may not have the exact width: rescale per
  6659. // character if measured width is greater than expected glyph width
  6660. // and subpixel-aa is enabled, otherwise just center the glyph.
  6661. var measuredWidth = ctx.measureText(character).width * 1000 /
  6662. fontSize * fontSizeScale;
  6663. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6664. var characterScaleX = width / measuredWidth;
  6665. restoreNeeded = true;
  6666. ctx.save();
  6667. ctx.scale(characterScaleX, 1);
  6668. scaledX /= characterScaleX;
  6669. } else if (width !== measuredWidth) {
  6670. scaledX += (width - measuredWidth) / 2000 *
  6671. fontSize / fontSizeScale;
  6672. }
  6673. }
  6674. if (simpleFillText && !accent) {
  6675. // common case
  6676. ctx.fillText(character, scaledX, scaledY);
  6677. } else {
  6678. this.paintChar(character, scaledX, scaledY);
  6679. if (accent) {
  6680. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  6681. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  6682. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  6683. }
  6684. }
  6685. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6686. x += charWidth;
  6687. if (restoreNeeded) {
  6688. ctx.restore();
  6689. }
  6690. }
  6691. if (vertical) {
  6692. current.y -= x * textHScale;
  6693. } else {
  6694. current.x += x * textHScale;
  6695. }
  6696. ctx.restore();
  6697. },
  6698. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  6699. // Type3 fonts - each glyph is a "mini-PDF"
  6700. var ctx = this.ctx;
  6701. var current = this.current;
  6702. var font = current.font;
  6703. var fontSize = current.fontSize;
  6704. var fontDirection = current.fontDirection;
  6705. var spacingDir = font.vertical ? 1 : -1;
  6706. var charSpacing = current.charSpacing;
  6707. var wordSpacing = current.wordSpacing;
  6708. var textHScale = current.textHScale * fontDirection;
  6709. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  6710. var glyphsLength = glyphs.length;
  6711. var isTextInvisible =
  6712. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  6713. var i, glyph, width, spacingLength;
  6714. if (isTextInvisible || fontSize === 0) {
  6715. return;
  6716. }
  6717. this.cachedGetSinglePixelWidth = null;
  6718. ctx.save();
  6719. ctx.transform.apply(ctx, current.textMatrix);
  6720. ctx.translate(current.x, current.y);
  6721. ctx.scale(textHScale, fontDirection);
  6722. for (i = 0; i < glyphsLength; ++i) {
  6723. glyph = glyphs[i];
  6724. if (isNum(glyph)) {
  6725. spacingLength = spacingDir * glyph * fontSize / 1000;
  6726. this.ctx.translate(spacingLength, 0);
  6727. current.x += spacingLength * textHScale;
  6728. continue;
  6729. }
  6730. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6731. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  6732. if (!operatorList) {
  6733. warn('Type3 character \"' + glyph.operatorListId +
  6734. '\" is not available');
  6735. continue;
  6736. }
  6737. this.processingType3 = glyph;
  6738. this.save();
  6739. ctx.scale(fontSize, fontSize);
  6740. ctx.transform.apply(ctx, fontMatrix);
  6741. this.executeOperatorList(operatorList);
  6742. this.restore();
  6743. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  6744. width = transformed[0] * fontSize + spacing;
  6745. ctx.translate(width, 0);
  6746. current.x += width * textHScale;
  6747. }
  6748. ctx.restore();
  6749. this.processingType3 = null;
  6750. },
  6751. // Type3 fonts
  6752. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  6753. // We can safely ignore this since the width should be the same
  6754. // as the width in the Widths array.
  6755. },
  6756. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  6757. yWidth,
  6758. llx,
  6759. lly,
  6760. urx,
  6761. ury) {
  6762. // TODO According to the spec we're also suppose to ignore any operators
  6763. // that set color or include images while processing this type3 font.
  6764. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6765. this.clip();
  6766. this.endPath();
  6767. },
  6768. // Color
  6769. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  6770. var pattern;
  6771. if (IR[0] === 'TilingPattern') {
  6772. var color = IR[1];
  6773. var baseTransform = this.baseTransform ||
  6774. this.ctx.mozCurrentTransform.slice();
  6775. var self = this;
  6776. var canvasGraphicsFactory = {
  6777. createCanvasGraphics: function (ctx) {
  6778. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  6779. }
  6780. };
  6781. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
  6782. baseTransform);
  6783. } else {
  6784. pattern = getShadingPatternFromIR(IR);
  6785. }
  6786. return pattern;
  6787. },
  6788. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  6789. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6790. },
  6791. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  6792. this.current.fillColor = this.getColorN_Pattern(arguments);
  6793. this.current.patternFill = true;
  6794. },
  6795. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  6796. var color = Util.makeCssRgb(r, g, b);
  6797. this.ctx.strokeStyle = color;
  6798. this.current.strokeColor = color;
  6799. },
  6800. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  6801. var color = Util.makeCssRgb(r, g, b);
  6802. this.ctx.fillStyle = color;
  6803. this.current.fillColor = color;
  6804. this.current.patternFill = false;
  6805. },
  6806. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  6807. var ctx = this.ctx;
  6808. this.save();
  6809. var pattern = getShadingPatternFromIR(patternIR);
  6810. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  6811. var inv = ctx.mozCurrentTransformInverse;
  6812. if (inv) {
  6813. var canvas = ctx.canvas;
  6814. var width = canvas.width;
  6815. var height = canvas.height;
  6816. var bl = Util.applyTransform([0, 0], inv);
  6817. var br = Util.applyTransform([0, height], inv);
  6818. var ul = Util.applyTransform([width, 0], inv);
  6819. var ur = Util.applyTransform([width, height], inv);
  6820. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6821. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6822. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6823. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6824. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6825. } else {
  6826. // HACK to draw the gradient onto an infinite rectangle.
  6827. // PDF gradients are drawn across the entire image while
  6828. // Canvas only allows gradients to be drawn in a rectangle
  6829. // The following bug should allow us to remove this.
  6830. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  6831. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6832. }
  6833. this.restore();
  6834. },
  6835. // Images
  6836. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  6837. error('Should not call beginInlineImage');
  6838. },
  6839. beginImageData: function CanvasGraphics_beginImageData() {
  6840. error('Should not call beginImageData');
  6841. },
  6842. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  6843. bbox) {
  6844. this.save();
  6845. this.baseTransformStack.push(this.baseTransform);
  6846. if (isArray(matrix) && 6 === matrix.length) {
  6847. this.transform.apply(this, matrix);
  6848. }
  6849. this.baseTransform = this.ctx.mozCurrentTransform;
  6850. if (isArray(bbox) && 4 === bbox.length) {
  6851. var width = bbox[2] - bbox[0];
  6852. var height = bbox[3] - bbox[1];
  6853. this.ctx.rect(bbox[0], bbox[1], width, height);
  6854. this.clip();
  6855. this.endPath();
  6856. }
  6857. },
  6858. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  6859. this.restore();
  6860. this.baseTransform = this.baseTransformStack.pop();
  6861. },
  6862. beginGroup: function CanvasGraphics_beginGroup(group) {
  6863. this.save();
  6864. var currentCtx = this.ctx;
  6865. // TODO non-isolated groups - according to Rik at adobe non-isolated
  6866. // group results aren't usually that different and they even have tools
  6867. // that ignore this setting. Notes from Rik on implmenting:
  6868. // - When you encounter an transparency group, create a new canvas with
  6869. // the dimensions of the bbox
  6870. // - copy the content from the previous canvas to the new canvas
  6871. // - draw as usual
  6872. // - remove the backdrop alpha:
  6873. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  6874. // value of your transparency group and 'alphaBackdrop' the alpha of the
  6875. // backdrop
  6876. // - remove background color:
  6877. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  6878. if (!group.isolated) {
  6879. info('TODO: Support non-isolated groups.');
  6880. }
  6881. // TODO knockout - supposedly possible with the clever use of compositing
  6882. // modes.
  6883. if (group.knockout) {
  6884. warn('Knockout groups not supported.');
  6885. }
  6886. var currentTransform = currentCtx.mozCurrentTransform;
  6887. if (group.matrix) {
  6888. currentCtx.transform.apply(currentCtx, group.matrix);
  6889. }
  6890. assert(group.bbox, 'Bounding box is required.');
  6891. // Based on the current transform figure out how big the bounding box
  6892. // will actually be.
  6893. var bounds = Util.getAxialAlignedBoundingBox(
  6894. group.bbox,
  6895. currentCtx.mozCurrentTransform);
  6896. // Clip the bounding box to the current canvas.
  6897. var canvasBounds = [0,
  6898. 0,
  6899. currentCtx.canvas.width,
  6900. currentCtx.canvas.height];
  6901. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6902. // Use ceil in case we're between sizes so we don't create canvas that is
  6903. // too small and make the canvas at least 1x1 pixels.
  6904. var offsetX = Math.floor(bounds[0]);
  6905. var offsetY = Math.floor(bounds[1]);
  6906. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6907. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6908. var scaleX = 1, scaleY = 1;
  6909. if (drawnWidth > MAX_GROUP_SIZE) {
  6910. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6911. drawnWidth = MAX_GROUP_SIZE;
  6912. }
  6913. if (drawnHeight > MAX_GROUP_SIZE) {
  6914. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6915. drawnHeight = MAX_GROUP_SIZE;
  6916. }
  6917. var cacheId = 'groupAt' + this.groupLevel;
  6918. if (group.smask) {
  6919. // Using two cache entries is case if masks are used one after another.
  6920. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  6921. }
  6922. var scratchCanvas = this.cachedCanvases.getCanvas(
  6923. cacheId, drawnWidth, drawnHeight, true);
  6924. var groupCtx = scratchCanvas.context;
  6925. // Since we created a new canvas that is just the size of the bounding box
  6926. // we have to translate the group ctx.
  6927. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6928. groupCtx.translate(-offsetX, -offsetY);
  6929. groupCtx.transform.apply(groupCtx, currentTransform);
  6930. if (group.smask) {
  6931. // Saving state and cached mask to be used in setGState.
  6932. this.smaskStack.push({
  6933. canvas: scratchCanvas.canvas,
  6934. context: groupCtx,
  6935. offsetX: offsetX,
  6936. offsetY: offsetY,
  6937. scaleX: scaleX,
  6938. scaleY: scaleY,
  6939. subtype: group.smask.subtype,
  6940. backdrop: group.smask.backdrop,
  6941. transferMap: group.smask.transferMap || null
  6942. });
  6943. } else {
  6944. // Setup the current ctx so when the group is popped we draw it at the
  6945. // right location.
  6946. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6947. currentCtx.translate(offsetX, offsetY);
  6948. currentCtx.scale(scaleX, scaleY);
  6949. }
  6950. // The transparency group inherits all off the current graphics state
  6951. // except the blend mode, soft mask, and alpha constants.
  6952. copyCtxState(currentCtx, groupCtx);
  6953. this.ctx = groupCtx;
  6954. this.setGState([
  6955. ['BM', 'Normal'],
  6956. ['ca', 1],
  6957. ['CA', 1]
  6958. ]);
  6959. this.groupStack.push(currentCtx);
  6960. this.groupLevel++;
  6961. },
  6962. endGroup: function CanvasGraphics_endGroup(group) {
  6963. this.groupLevel--;
  6964. var groupCtx = this.ctx;
  6965. this.ctx = this.groupStack.pop();
  6966. // Turn off image smoothing to avoid sub pixel interpolation which can
  6967. // look kind of blurry for some pdfs.
  6968. if (this.ctx.imageSmoothingEnabled !== undefined) {
  6969. this.ctx.imageSmoothingEnabled = false;
  6970. } else {
  6971. this.ctx.mozImageSmoothingEnabled = false;
  6972. }
  6973. if (group.smask) {
  6974. this.tempSMask = this.smaskStack.pop();
  6975. } else {
  6976. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6977. }
  6978. this.restore();
  6979. },
  6980. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  6981. this.save();
  6982. this.current = new CanvasExtraState();
  6983. if (this.baseTransform) {
  6984. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  6985. }
  6986. },
  6987. endAnnotations: function CanvasGraphics_endAnnotations() {
  6988. this.restore();
  6989. },
  6990. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  6991. matrix) {
  6992. this.save();
  6993. if (isArray(rect) && 4 === rect.length) {
  6994. var width = rect[2] - rect[0];
  6995. var height = rect[3] - rect[1];
  6996. this.ctx.rect(rect[0], rect[1], width, height);
  6997. this.clip();
  6998. this.endPath();
  6999. }
  7000. this.transform.apply(this, transform);
  7001. this.transform.apply(this, matrix);
  7002. },
  7003. endAnnotation: function CanvasGraphics_endAnnotation() {
  7004. this.restore();
  7005. },
  7006. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7007. var domImage = this.objs.get(objId);
  7008. if (!domImage) {
  7009. warn('Dependent image isn\'t ready yet');
  7010. return;
  7011. }
  7012. this.save();
  7013. var ctx = this.ctx;
  7014. // scale the image to the unit square
  7015. ctx.scale(1 / w, -1 / h);
  7016. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  7017. 0, -h, w, h);
  7018. if (this.imageLayer) {
  7019. var currentTransform = ctx.mozCurrentTransformInverse;
  7020. var position = this.getCanvasPosition(0, 0);
  7021. this.imageLayer.appendImage({
  7022. objId: objId,
  7023. left: position[0],
  7024. top: position[1],
  7025. width: w / currentTransform[0],
  7026. height: h / currentTransform[3]
  7027. });
  7028. }
  7029. this.restore();
  7030. },
  7031. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7032. var ctx = this.ctx;
  7033. var width = img.width, height = img.height;
  7034. var fillColor = this.current.fillColor;
  7035. var isPatternFill = this.current.patternFill;
  7036. var glyph = this.processingType3;
  7037. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7038. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7039. glyph.compiled =
  7040. compileType3Glyph({data: img.data, width: width, height: height});
  7041. } else {
  7042. glyph.compiled = null;
  7043. }
  7044. }
  7045. if (glyph && glyph.compiled) {
  7046. glyph.compiled(ctx);
  7047. return;
  7048. }
  7049. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7050. width, height);
  7051. var maskCtx = maskCanvas.context;
  7052. maskCtx.save();
  7053. putBinaryImageMask(maskCtx, img);
  7054. maskCtx.globalCompositeOperation = 'source-in';
  7055. maskCtx.fillStyle = isPatternFill ?
  7056. fillColor.getPattern(maskCtx, this) : fillColor;
  7057. maskCtx.fillRect(0, 0, width, height);
  7058. maskCtx.restore();
  7059. this.paintInlineImageXObject(maskCanvas.canvas);
  7060. },
  7061. paintImageMaskXObjectRepeat:
  7062. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  7063. scaleY, positions) {
  7064. var width = imgData.width;
  7065. var height = imgData.height;
  7066. var fillColor = this.current.fillColor;
  7067. var isPatternFill = this.current.patternFill;
  7068. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7069. width, height);
  7070. var maskCtx = maskCanvas.context;
  7071. maskCtx.save();
  7072. putBinaryImageMask(maskCtx, imgData);
  7073. maskCtx.globalCompositeOperation = 'source-in';
  7074. maskCtx.fillStyle = isPatternFill ?
  7075. fillColor.getPattern(maskCtx, this) : fillColor;
  7076. maskCtx.fillRect(0, 0, width, height);
  7077. maskCtx.restore();
  7078. var ctx = this.ctx;
  7079. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7080. ctx.save();
  7081. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7082. ctx.scale(1, -1);
  7083. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7084. 0, -1, 1, 1);
  7085. ctx.restore();
  7086. }
  7087. },
  7088. paintImageMaskXObjectGroup:
  7089. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7090. var ctx = this.ctx;
  7091. var fillColor = this.current.fillColor;
  7092. var isPatternFill = this.current.patternFill;
  7093. for (var i = 0, ii = images.length; i < ii; i++) {
  7094. var image = images[i];
  7095. var width = image.width, height = image.height;
  7096. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
  7097. width, height);
  7098. var maskCtx = maskCanvas.context;
  7099. maskCtx.save();
  7100. putBinaryImageMask(maskCtx, image);
  7101. maskCtx.globalCompositeOperation = 'source-in';
  7102. maskCtx.fillStyle = isPatternFill ?
  7103. fillColor.getPattern(maskCtx, this) : fillColor;
  7104. maskCtx.fillRect(0, 0, width, height);
  7105. maskCtx.restore();
  7106. ctx.save();
  7107. ctx.transform.apply(ctx, image.transform);
  7108. ctx.scale(1, -1);
  7109. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  7110. 0, -1, 1, 1);
  7111. ctx.restore();
  7112. }
  7113. },
  7114. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7115. var imgData = this.objs.get(objId);
  7116. if (!imgData) {
  7117. warn('Dependent image isn\'t ready yet');
  7118. return;
  7119. }
  7120. this.paintInlineImageXObject(imgData);
  7121. },
  7122. paintImageXObjectRepeat:
  7123. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  7124. positions) {
  7125. var imgData = this.objs.get(objId);
  7126. if (!imgData) {
  7127. warn('Dependent image isn\'t ready yet');
  7128. return;
  7129. }
  7130. var width = imgData.width;
  7131. var height = imgData.height;
  7132. var map = [];
  7133. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7134. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  7135. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  7136. }
  7137. this.paintInlineImageXObjectGroup(imgData, map);
  7138. },
  7139. paintInlineImageXObject:
  7140. function CanvasGraphics_paintInlineImageXObject(imgData) {
  7141. var width = imgData.width;
  7142. var height = imgData.height;
  7143. var ctx = this.ctx;
  7144. this.save();
  7145. // scale the image to the unit square
  7146. ctx.scale(1 / width, -1 / height);
  7147. var currentTransform = ctx.mozCurrentTransformInverse;
  7148. var a = currentTransform[0], b = currentTransform[1];
  7149. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7150. var c = currentTransform[2], d = currentTransform[3];
  7151. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7152. var imgToPaint, tmpCanvas;
  7153. // instanceof HTMLElement does not work in jsdom node.js module
  7154. if (imgData instanceof HTMLElement || !imgData.data) {
  7155. imgToPaint = imgData;
  7156. } else {
  7157. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
  7158. width, height);
  7159. var tmpCtx = tmpCanvas.context;
  7160. putBinaryImageData(tmpCtx, imgData);
  7161. imgToPaint = tmpCanvas.canvas;
  7162. }
  7163. var paintWidth = width, paintHeight = height;
  7164. var tmpCanvasId = 'prescale1';
  7165. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  7166. // pixels during drawImage operation, painting on the temporary canvas(es)
  7167. // that are twice smaller in size
  7168. while ((widthScale > 2 && paintWidth > 1) ||
  7169. (heightScale > 2 && paintHeight > 1)) {
  7170. var newWidth = paintWidth, newHeight = paintHeight;
  7171. if (widthScale > 2 && paintWidth > 1) {
  7172. newWidth = Math.ceil(paintWidth / 2);
  7173. widthScale /= paintWidth / newWidth;
  7174. }
  7175. if (heightScale > 2 && paintHeight > 1) {
  7176. newHeight = Math.ceil(paintHeight / 2);
  7177. heightScale /= paintHeight / newHeight;
  7178. }
  7179. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
  7180. newWidth, newHeight);
  7181. tmpCtx = tmpCanvas.context;
  7182. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7183. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7184. 0, 0, newWidth, newHeight);
  7185. imgToPaint = tmpCanvas.canvas;
  7186. paintWidth = newWidth;
  7187. paintHeight = newHeight;
  7188. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7189. }
  7190. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  7191. 0, -height, width, height);
  7192. if (this.imageLayer) {
  7193. var position = this.getCanvasPosition(0, -height);
  7194. this.imageLayer.appendImage({
  7195. imgData: imgData,
  7196. left: position[0],
  7197. top: position[1],
  7198. width: width / currentTransform[0],
  7199. height: height / currentTransform[3]
  7200. });
  7201. }
  7202. this.restore();
  7203. },
  7204. paintInlineImageXObjectGroup:
  7205. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7206. var ctx = this.ctx;
  7207. var w = imgData.width;
  7208. var h = imgData.height;
  7209. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7210. var tmpCtx = tmpCanvas.context;
  7211. putBinaryImageData(tmpCtx, imgData);
  7212. for (var i = 0, ii = map.length; i < ii; i++) {
  7213. var entry = map[i];
  7214. ctx.save();
  7215. ctx.transform.apply(ctx, entry.transform);
  7216. ctx.scale(1, -1);
  7217. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  7218. 0, -1, 1, 1);
  7219. if (this.imageLayer) {
  7220. var position = this.getCanvasPosition(entry.x, entry.y);
  7221. this.imageLayer.appendImage({
  7222. imgData: imgData,
  7223. left: position[0],
  7224. top: position[1],
  7225. width: w,
  7226. height: h
  7227. });
  7228. }
  7229. ctx.restore();
  7230. }
  7231. },
  7232. paintSolidColorImageMask:
  7233. function CanvasGraphics_paintSolidColorImageMask() {
  7234. this.ctx.fillRect(0, 0, 1, 1);
  7235. },
  7236. paintXObject: function CanvasGraphics_paintXObject() {
  7237. warn('Unsupported \'paintXObject\' command.');
  7238. },
  7239. // Marked content
  7240. markPoint: function CanvasGraphics_markPoint(tag) {
  7241. // TODO Marked content.
  7242. },
  7243. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  7244. // TODO Marked content.
  7245. },
  7246. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  7247. // TODO Marked content.
  7248. },
  7249. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  7250. tag, properties) {
  7251. // TODO Marked content.
  7252. },
  7253. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  7254. // TODO Marked content.
  7255. },
  7256. // Compatibility
  7257. beginCompat: function CanvasGraphics_beginCompat() {
  7258. // TODO ignore undefined operators (should we do that anyway?)
  7259. },
  7260. endCompat: function CanvasGraphics_endCompat() {
  7261. // TODO stop ignoring undefined operators
  7262. },
  7263. // Helper functions
  7264. consumePath: function CanvasGraphics_consumePath() {
  7265. var ctx = this.ctx;
  7266. if (this.pendingClip) {
  7267. if (this.pendingClip === EO_CLIP) {
  7268. if (ctx.mozFillRule !== undefined) {
  7269. ctx.mozFillRule = 'evenodd';
  7270. ctx.clip();
  7271. ctx.mozFillRule = 'nonzero';
  7272. } else {
  7273. ctx.clip('evenodd');
  7274. }
  7275. } else {
  7276. ctx.clip();
  7277. }
  7278. this.pendingClip = null;
  7279. }
  7280. ctx.beginPath();
  7281. },
  7282. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  7283. if (this.cachedGetSinglePixelWidth === null) {
  7284. var inverse = this.ctx.mozCurrentTransformInverse;
  7285. // max of the current horizontal and vertical scale
  7286. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  7287. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  7288. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  7289. }
  7290. return this.cachedGetSinglePixelWidth;
  7291. },
  7292. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  7293. var transform = this.ctx.mozCurrentTransform;
  7294. return [
  7295. transform[0] * x + transform[2] * y + transform[4],
  7296. transform[1] * x + transform[3] * y + transform[5]
  7297. ];
  7298. }
  7299. };
  7300. for (var op in OPS) {
  7301. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  7302. }
  7303. return CanvasGraphics;
  7304. })();
  7305. exports.CanvasGraphics = CanvasGraphics;
  7306. exports.createScratchCanvas = createScratchCanvas;
  7307. }));
  7308. (function (root, factory) {
  7309. {
  7310. factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
  7311. root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
  7312. root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal);
  7313. }
  7314. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
  7315. displayMetadata, sharedGlobal, amdRequire) {
  7316. var InvalidPDFException = sharedUtil.InvalidPDFException;
  7317. var MessageHandler = sharedUtil.MessageHandler;
  7318. var MissingPDFException = sharedUtil.MissingPDFException;
  7319. var PasswordResponses = sharedUtil.PasswordResponses;
  7320. var PasswordException = sharedUtil.PasswordException;
  7321. var StatTimer = sharedUtil.StatTimer;
  7322. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  7323. var UnknownErrorException = sharedUtil.UnknownErrorException;
  7324. var Util = sharedUtil.Util;
  7325. var createPromiseCapability = sharedUtil.createPromiseCapability;
  7326. var combineUrl = sharedUtil.combineUrl;
  7327. var error = sharedUtil.error;
  7328. var deprecated = sharedUtil.deprecated;
  7329. var info = sharedUtil.info;
  7330. var isArrayBuffer = sharedUtil.isArrayBuffer;
  7331. var loadJpegStream = sharedUtil.loadJpegStream;
  7332. var stringToBytes = sharedUtil.stringToBytes;
  7333. var warn = sharedUtil.warn;
  7334. var FontFaceObject = displayFontLoader.FontFaceObject;
  7335. var FontLoader = displayFontLoader.FontLoader;
  7336. var CanvasGraphics = displayCanvas.CanvasGraphics;
  7337. var createScratchCanvas = displayCanvas.createScratchCanvas;
  7338. var Metadata = displayMetadata.Metadata;
  7339. var PDFJS = sharedGlobal.PDFJS;
  7340. var globalScope = sharedGlobal.globalScope;
  7341. var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
  7342. var useRequireEnsure = false;
  7343. if (typeof module !== 'undefined' && module.require) {
  7344. // node.js - disable worker and set require.ensure.
  7345. PDFJS.disableWorker = true;
  7346. if (typeof require.ensure === 'undefined') {
  7347. require.ensure = require('node-ensure');
  7348. }
  7349. useRequireEnsure = true;
  7350. }
  7351. if (typeof __webpack_require__ !== 'undefined') {
  7352. // Webpack - get/bundle pdf.worker.js as additional file.
  7353. PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js');
  7354. useRequireEnsure = true;
  7355. }
  7356. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  7357. PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  7358. }
  7359. var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
  7360. require.ensure([], function () {
  7361. require('./pdf.worker.js');
  7362. callback();
  7363. });
  7364. }) : (typeof requirejs !== 'undefined') ? (function (callback) {
  7365. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  7366. callback();
  7367. });
  7368. }) : null;
  7369. /**
  7370. * The maximum allowed image size in total pixels e.g. width * height. Images
  7371. * above this value will not be drawn. Use -1 for no limit.
  7372. * @var {number}
  7373. */
  7374. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  7375. -1 : PDFJS.maxImageSize);
  7376. /**
  7377. * The url of where the predefined Adobe CMaps are located. Include trailing
  7378. * slash.
  7379. * @var {string}
  7380. */
  7381. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  7382. /**
  7383. * Specifies if CMaps are binary packed.
  7384. * @var {boolean}
  7385. */
  7386. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  7387. /**
  7388. * By default fonts are converted to OpenType fonts and loaded via font face
  7389. * rules. If disabled, the font will be rendered using a built in font renderer
  7390. * that constructs the glyphs with primitive path commands.
  7391. * @var {boolean}
  7392. */
  7393. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  7394. false : PDFJS.disableFontFace);
  7395. /**
  7396. * Path for image resources, mainly for annotation icons. Include trailing
  7397. * slash.
  7398. * @var {string}
  7399. */
  7400. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  7401. '' : PDFJS.imageResourcesPath);
  7402. /**
  7403. * Disable the web worker and run all code on the main thread. This will happen
  7404. * automatically if the browser doesn't support workers or sending typed arrays
  7405. * to workers.
  7406. * @var {boolean}
  7407. */
  7408. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  7409. false : PDFJS.disableWorker);
  7410. /**
  7411. * Path and filename of the worker file. Required when the worker is enabled in
  7412. * development mode. If unspecified in the production build, the worker will be
  7413. * loaded based on the location of the pdf.js file. It is recommended that
  7414. * the workerSrc is set in a custom application to prevent issues caused by
  7415. * third-party frameworks and libraries.
  7416. * @var {string}
  7417. */
  7418. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  7419. /**
  7420. * Disable range request loading of PDF files. When enabled and if the server
  7421. * supports partial content requests then the PDF will be fetched in chunks.
  7422. * Enabled (false) by default.
  7423. * @var {boolean}
  7424. */
  7425. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  7426. false : PDFJS.disableRange);
  7427. /**
  7428. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  7429. * in chunks. This default behavior can be disabled.
  7430. * @var {boolean}
  7431. */
  7432. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  7433. false : PDFJS.disableStream);
  7434. /**
  7435. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  7436. * will automatically keep fetching more data even if it isn't needed to display
  7437. * the current page. This default behavior can be disabled.
  7438. *
  7439. * NOTE: It is also necessary to disable streaming, see above,
  7440. * in order for disabling of pre-fetching to work correctly.
  7441. * @var {boolean}
  7442. */
  7443. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  7444. false : PDFJS.disableAutoFetch);
  7445. /**
  7446. * Enables special hooks for debugging PDF.js.
  7447. * @var {boolean}
  7448. */
  7449. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  7450. /**
  7451. * Enables transfer usage in postMessage for ArrayBuffers.
  7452. * @var {boolean}
  7453. */
  7454. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  7455. true : PDFJS.postMessageTransfers);
  7456. /**
  7457. * Disables URL.createObjectURL usage.
  7458. * @var {boolean}
  7459. */
  7460. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  7461. false : PDFJS.disableCreateObjectURL);
  7462. /**
  7463. * Disables WebGL usage.
  7464. * @var {boolean}
  7465. */
  7466. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  7467. true : PDFJS.disableWebGL);
  7468. /**
  7469. * Disables fullscreen support, and by extension Presentation Mode,
  7470. * in browsers which support the fullscreen API.
  7471. * @var {boolean}
  7472. */
  7473. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  7474. false : PDFJS.disableFullscreen);
  7475. /**
  7476. * Enables CSS only zooming.
  7477. * @var {boolean}
  7478. */
  7479. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  7480. false : PDFJS.useOnlyCssZoom);
  7481. /**
  7482. * Controls the logging level.
  7483. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  7484. * - errors
  7485. * - warnings [default]
  7486. * - infos
  7487. * @var {number}
  7488. */
  7489. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  7490. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  7491. /**
  7492. * The maximum supported canvas size in total pixels e.g. width * height.
  7493. * The default value is 4096 * 4096. Use -1 for no limit.
  7494. * @var {number}
  7495. */
  7496. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  7497. 16777216 : PDFJS.maxCanvasPixels);
  7498. /**
  7499. * (Deprecated) Opens external links in a new window if enabled.
  7500. * The default behavior opens external links in the PDF.js window.
  7501. *
  7502. * NOTE: This property has been deprecated, please use
  7503. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  7504. * @var {boolean}
  7505. */
  7506. PDFJS.openExternalLinksInNewWindow = (
  7507. PDFJS.openExternalLinksInNewWindow === undefined ?
  7508. false : PDFJS.openExternalLinksInNewWindow);
  7509. /**
  7510. * Specifies the |target| attribute for external links.
  7511. * The constants from PDFJS.LinkTarget should be used:
  7512. * - NONE [default]
  7513. * - SELF
  7514. * - BLANK
  7515. * - PARENT
  7516. * - TOP
  7517. * @var {number}
  7518. */
  7519. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  7520. PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget);
  7521. /**
  7522. * Specifies the |rel| attribute for external links. Defaults to stripping
  7523. * the referrer.
  7524. * @var {string}
  7525. */
  7526. PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
  7527. 'noreferrer' : PDFJS.externalLinkRel);
  7528. /**
  7529. * Determines if we can eval strings as JS. Primarily used to improve
  7530. * performance for font rendering.
  7531. * @var {boolean}
  7532. */
  7533. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  7534. true : PDFJS.isEvalSupported);
  7535. /**
  7536. * Document initialization / loading parameters object.
  7537. *
  7538. * @typedef {Object} DocumentInitParameters
  7539. * @property {string} url - The URL of the PDF.
  7540. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  7541. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  7542. * use atob() to convert it to a binary string first.
  7543. * @property {Object} httpHeaders - Basic authentication headers.
  7544. * @property {boolean} withCredentials - Indicates whether or not cross-site
  7545. * Access-Control requests should be made using credentials such as cookies
  7546. * or authorization headers. The default is false.
  7547. * @property {string} password - For decrypting password-protected PDFs.
  7548. * @property {TypedArray} initialData - A typed array with the first portion or
  7549. * all of the pdf data. Used by the extension since some data is already
  7550. * loaded before the switch to range requests.
  7551. * @property {number} length - The PDF file length. It's used for progress
  7552. * reports and range requests operations.
  7553. * @property {PDFDataRangeTransport} range
  7554. * @property {number} rangeChunkSize - Optional parameter to specify
  7555. * maximum number of bytes fetched per range request. The default value is
  7556. * 2^16 = 65536.
  7557. * @property {PDFWorker} worker - The worker that will be used for the loading
  7558. * and parsing of the PDF data.
  7559. */
  7560. /**
  7561. * @typedef {Object} PDFDocumentStats
  7562. * @property {Array} streamTypes - Used stream types in the document (an item
  7563. * is set to true if specific stream ID was used in the document).
  7564. * @property {Array} fontTypes - Used font type in the document (an item is set
  7565. * to true if specific font ID was used in the document).
  7566. */
  7567. /**
  7568. * This is the main entry point for loading a PDF and interacting with it.
  7569. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  7570. * is used, which means it must follow the same origin rules that any XHR does
  7571. * e.g. No cross domain requests without CORS.
  7572. *
  7573. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  7574. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  7575. * already populated with data or parameter object.
  7576. *
  7577. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  7578. * if you want to manually serve range requests for data in the PDF.
  7579. *
  7580. * @param {function} passwordCallback (deprecated) It is used to request a
  7581. * password if wrong or no password was provided. The callback receives two
  7582. * parameters: function that needs to be called with new password and reason
  7583. * (see {PasswordResponses}).
  7584. *
  7585. * @param {function} progressCallback (deprecated) It is used to be able to
  7586. * monitor the loading progress of the PDF file (necessary to implement e.g.
  7587. * a loading bar). The callback receives an {Object} with the properties:
  7588. * {number} loaded and {number} total.
  7589. *
  7590. * @return {PDFDocumentLoadingTask}
  7591. */
  7592. PDFJS.getDocument = function getDocument(src,
  7593. pdfDataRangeTransport,
  7594. passwordCallback,
  7595. progressCallback) {
  7596. var task = new PDFDocumentLoadingTask();
  7597. // Support of the obsolete arguments (for compatibility with API v1.0)
  7598. if (arguments.length > 1) {
  7599. deprecated('getDocument is called with pdfDataRangeTransport, ' +
  7600. 'passwordCallback or progressCallback argument');
  7601. }
  7602. if (pdfDataRangeTransport) {
  7603. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  7604. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  7605. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  7606. pdfDataRangeTransport.length = src.length;
  7607. pdfDataRangeTransport.initialData = src.initialData;
  7608. if (!pdfDataRangeTransport.abort) {
  7609. pdfDataRangeTransport.abort = function () {};
  7610. }
  7611. }
  7612. src = Object.create(src);
  7613. src.range = pdfDataRangeTransport;
  7614. }
  7615. task.onPassword = passwordCallback || null;
  7616. task.onProgress = progressCallback || null;
  7617. var source;
  7618. if (typeof src === 'string') {
  7619. source = { url: src };
  7620. } else if (isArrayBuffer(src)) {
  7621. source = { data: src };
  7622. } else if (src instanceof PDFDataRangeTransport) {
  7623. source = { range: src };
  7624. } else {
  7625. if (typeof src !== 'object') {
  7626. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  7627. 'string or a parameter object');
  7628. }
  7629. if (!src.url && !src.data && !src.range) {
  7630. error('Invalid parameter object: need either .data, .range or .url');
  7631. }
  7632. source = src;
  7633. }
  7634. var params = {};
  7635. var rangeTransport = null;
  7636. var worker = null;
  7637. for (var key in source) {
  7638. if (key === 'url' && typeof window !== 'undefined') {
  7639. // The full path is required in the 'url' field.
  7640. params[key] = combineUrl(window.location.href, source[key]);
  7641. continue;
  7642. } else if (key === 'range') {
  7643. rangeTransport = source[key];
  7644. continue;
  7645. } else if (key === 'worker') {
  7646. worker = source[key];
  7647. continue;
  7648. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  7649. // Converting string or array-like data to Uint8Array.
  7650. var pdfBytes = source[key];
  7651. if (typeof pdfBytes === 'string') {
  7652. params[key] = stringToBytes(pdfBytes);
  7653. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  7654. !isNaN(pdfBytes.length)) {
  7655. params[key] = new Uint8Array(pdfBytes);
  7656. } else if (isArrayBuffer(pdfBytes)) {
  7657. params[key] = new Uint8Array(pdfBytes);
  7658. } else {
  7659. error('Invalid PDF binary data: either typed array, string or ' +
  7660. 'array-like object is expected in the data property.');
  7661. }
  7662. continue;
  7663. }
  7664. params[key] = source[key];
  7665. }
  7666. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  7667. if (!worker) {
  7668. // Worker was not provided -- creating and owning our own.
  7669. worker = new PDFWorker();
  7670. task._worker = worker;
  7671. }
  7672. var docId = task.docId;
  7673. worker.promise.then(function () {
  7674. if (task.destroyed) {
  7675. throw new Error('Loading aborted');
  7676. }
  7677. return _fetchDocument(worker, params, rangeTransport, docId).then(
  7678. function (workerId) {
  7679. if (task.destroyed) {
  7680. throw new Error('Loading aborted');
  7681. }
  7682. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  7683. messageHandler.send('Ready', null);
  7684. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  7685. task._transport = transport;
  7686. });
  7687. }).catch(task._capability.reject);
  7688. return task;
  7689. };
  7690. /**
  7691. * Starts fetching of specified PDF document/data.
  7692. * @param {PDFWorker} worker
  7693. * @param {Object} source
  7694. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  7695. * @param {string} docId Unique document id, used as MessageHandler id.
  7696. * @returns {Promise} The promise, which is resolved when worker id of
  7697. * MessageHandler is known.
  7698. * @private
  7699. */
  7700. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  7701. if (worker.destroyed) {
  7702. return Promise.reject(new Error('Worker was destroyed'));
  7703. }
  7704. source.disableAutoFetch = PDFJS.disableAutoFetch;
  7705. source.disableStream = PDFJS.disableStream;
  7706. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  7707. if (pdfDataRangeTransport) {
  7708. source.length = pdfDataRangeTransport.length;
  7709. source.initialData = pdfDataRangeTransport.initialData;
  7710. }
  7711. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  7712. docId: docId,
  7713. source: source,
  7714. disableRange: PDFJS.disableRange,
  7715. maxImageSize: PDFJS.maxImageSize,
  7716. cMapUrl: PDFJS.cMapUrl,
  7717. cMapPacked: PDFJS.cMapPacked,
  7718. disableFontFace: PDFJS.disableFontFace,
  7719. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  7720. verbosity: PDFJS.verbosity
  7721. }).then(function (workerId) {
  7722. if (worker.destroyed) {
  7723. throw new Error('Worker was destroyed');
  7724. }
  7725. return workerId;
  7726. });
  7727. }
  7728. /**
  7729. * PDF document loading operation.
  7730. * @class
  7731. * @alias PDFDocumentLoadingTask
  7732. */
  7733. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  7734. var nextDocumentId = 0;
  7735. /** @constructs PDFDocumentLoadingTask */
  7736. function PDFDocumentLoadingTask() {
  7737. this._capability = createPromiseCapability();
  7738. this._transport = null;
  7739. this._worker = null;
  7740. /**
  7741. * Unique document loading task id -- used in MessageHandlers.
  7742. * @type {string}
  7743. */
  7744. this.docId = 'd' + (nextDocumentId++);
  7745. /**
  7746. * Shows if loading task is destroyed.
  7747. * @type {boolean}
  7748. */
  7749. this.destroyed = false;
  7750. /**
  7751. * Callback to request a password if wrong or no password was provided.
  7752. * The callback receives two parameters: function that needs to be called
  7753. * with new password and reason (see {PasswordResponses}).
  7754. */
  7755. this.onPassword = null;
  7756. /**
  7757. * Callback to be able to monitor the loading progress of the PDF file
  7758. * (necessary to implement e.g. a loading bar). The callback receives
  7759. * an {Object} with the properties: {number} loaded and {number} total.
  7760. */
  7761. this.onProgress = null;
  7762. /**
  7763. * Callback to when unsupported feature is used. The callback receives
  7764. * an {PDFJS.UNSUPPORTED_FEATURES} argument.
  7765. */
  7766. this.onUnsupportedFeature = null;
  7767. }
  7768. PDFDocumentLoadingTask.prototype =
  7769. /** @lends PDFDocumentLoadingTask.prototype */ {
  7770. /**
  7771. * @return {Promise}
  7772. */
  7773. get promise() {
  7774. return this._capability.promise;
  7775. },
  7776. /**
  7777. * Aborts all network requests and destroys worker.
  7778. * @return {Promise} A promise that is resolved after destruction activity
  7779. * is completed.
  7780. */
  7781. destroy: function () {
  7782. this.destroyed = true;
  7783. var transportDestroyed = !this._transport ? Promise.resolve() :
  7784. this._transport.destroy();
  7785. return transportDestroyed.then(function () {
  7786. this._transport = null;
  7787. if (this._worker) {
  7788. this._worker.destroy();
  7789. this._worker = null;
  7790. }
  7791. }.bind(this));
  7792. },
  7793. /**
  7794. * Registers callbacks to indicate the document loading completion.
  7795. *
  7796. * @param {function} onFulfilled The callback for the loading completion.
  7797. * @param {function} onRejected The callback for the loading failure.
  7798. * @return {Promise} A promise that is resolved after the onFulfilled or
  7799. * onRejected callback.
  7800. */
  7801. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  7802. return this.promise.then.apply(this.promise, arguments);
  7803. }
  7804. };
  7805. return PDFDocumentLoadingTask;
  7806. })();
  7807. /**
  7808. * Abstract class to support range requests file loading.
  7809. * @class
  7810. * @alias PDFJS.PDFDataRangeTransport
  7811. * @param {number} length
  7812. * @param {Uint8Array} initialData
  7813. */
  7814. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  7815. function PDFDataRangeTransport(length, initialData) {
  7816. this.length = length;
  7817. this.initialData = initialData;
  7818. this._rangeListeners = [];
  7819. this._progressListeners = [];
  7820. this._progressiveReadListeners = [];
  7821. this._readyCapability = createPromiseCapability();
  7822. }
  7823. PDFDataRangeTransport.prototype =
  7824. /** @lends PDFDataRangeTransport.prototype */ {
  7825. addRangeListener:
  7826. function PDFDataRangeTransport_addRangeListener(listener) {
  7827. this._rangeListeners.push(listener);
  7828. },
  7829. addProgressListener:
  7830. function PDFDataRangeTransport_addProgressListener(listener) {
  7831. this._progressListeners.push(listener);
  7832. },
  7833. addProgressiveReadListener:
  7834. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  7835. this._progressiveReadListeners.push(listener);
  7836. },
  7837. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  7838. var listeners = this._rangeListeners;
  7839. for (var i = 0, n = listeners.length; i < n; ++i) {
  7840. listeners[i](begin, chunk);
  7841. }
  7842. },
  7843. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  7844. this._readyCapability.promise.then(function () {
  7845. var listeners = this._progressListeners;
  7846. for (var i = 0, n = listeners.length; i < n; ++i) {
  7847. listeners[i](loaded);
  7848. }
  7849. }.bind(this));
  7850. },
  7851. onDataProgressiveRead:
  7852. function PDFDataRangeTransport_onDataProgress(chunk) {
  7853. this._readyCapability.promise.then(function () {
  7854. var listeners = this._progressiveReadListeners;
  7855. for (var i = 0, n = listeners.length; i < n; ++i) {
  7856. listeners[i](chunk);
  7857. }
  7858. }.bind(this));
  7859. },
  7860. transportReady: function PDFDataRangeTransport_transportReady() {
  7861. this._readyCapability.resolve();
  7862. },
  7863. requestDataRange:
  7864. function PDFDataRangeTransport_requestDataRange(begin, end) {
  7865. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  7866. },
  7867. abort: function PDFDataRangeTransport_abort() {
  7868. }
  7869. };
  7870. return PDFDataRangeTransport;
  7871. })();
  7872. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  7873. /**
  7874. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  7875. * properties that can be read synchronously.
  7876. * @class
  7877. * @alias PDFDocumentProxy
  7878. */
  7879. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  7880. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  7881. this.pdfInfo = pdfInfo;
  7882. this.transport = transport;
  7883. this.loadingTask = loadingTask;
  7884. }
  7885. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  7886. /**
  7887. * @return {number} Total number of pages the PDF contains.
  7888. */
  7889. get numPages() {
  7890. return this.pdfInfo.numPages;
  7891. },
  7892. /**
  7893. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  7894. * unique.
  7895. */
  7896. get fingerprint() {
  7897. return this.pdfInfo.fingerprint;
  7898. },
  7899. /**
  7900. * @param {number} pageNumber The page number to get. The first page is 1.
  7901. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  7902. * object.
  7903. */
  7904. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  7905. return this.transport.getPage(pageNumber);
  7906. },
  7907. /**
  7908. * @param {{num: number, gen: number}} ref The page reference. Must have
  7909. * the 'num' and 'gen' properties.
  7910. * @return {Promise} A promise that is resolved with the page index that is
  7911. * associated with the reference.
  7912. */
  7913. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  7914. return this.transport.getPageIndex(ref);
  7915. },
  7916. /**
  7917. * @return {Promise} A promise that is resolved with a lookup table for
  7918. * mapping named destinations to reference numbers.
  7919. *
  7920. * This can be slow for large documents: use getDestination instead
  7921. */
  7922. getDestinations: function PDFDocumentProxy_getDestinations() {
  7923. return this.transport.getDestinations();
  7924. },
  7925. /**
  7926. * @param {string} id The named destination to get.
  7927. * @return {Promise} A promise that is resolved with all information
  7928. * of the given named destination.
  7929. */
  7930. getDestination: function PDFDocumentProxy_getDestination(id) {
  7931. return this.transport.getDestination(id);
  7932. },
  7933. /**
  7934. * @return {Promise} A promise that is resolved with:
  7935. * an Array containing the pageLabels that correspond to the pageIndexes,
  7936. * or `null` when no pageLabels are present in the PDF file.
  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. }));