pdf.js 359 KB

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