pdf.js 247 KB

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