pdf.js 281 KB

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