pdf.js 297 KB

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