pdf.js 255 KB

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