pdf.js 207 KB

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