2
0

pdf.js 253 KB

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