pdf.js 243 KB

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