pdf.js 255 KB

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