2
0

pdf.js 219 KB

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