pdf.js 273 KB

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