pdf.js 274 KB

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