pdf.js 300 KB

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