pdf.js 294 KB

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