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