pdf.js 273 KB

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