pdf.js 275 KB

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