pdf.js 255 KB

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