pdf.js 255 KB

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