pdf.js 346 KB

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