pdf.js 254 KB

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