pdf.js 258 KB

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