pdf.js 271 KB

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