pdf.js 259 KB

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