pdf.js 254 KB

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