pdf.js 255 KB

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