pdf.js 273 KB

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