pdf.js 422 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580
  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. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/build/pdf', ['exports'], factory);
  19. } else if (typeof exports !== 'undefined') {
  20. factory(exports);
  21. } else {
  22. factory(root['pdfjsDistBuildPdf'] = {});
  23. }
  24. }(this, function (exports) {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. var pdfjsVersion = '1.6.313';
  28. var pdfjsBuild = 'c23f124';
  29. var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  30. var pdfjsLibs = {};
  31. (function pdfjsWrapper() {
  32. (function (root, factory) {
  33. factory(root.pdfjsSharedUtil = {});
  34. }(this, function (exports) {
  35. var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
  36. var FONT_IDENTITY_MATRIX = [
  37. 0.001,
  38. 0,
  39. 0,
  40. 0.001,
  41. 0,
  42. 0
  43. ];
  44. var TextRenderingMode = {
  45. FILL: 0,
  46. STROKE: 1,
  47. FILL_STROKE: 2,
  48. INVISIBLE: 3,
  49. FILL_ADD_TO_PATH: 4,
  50. STROKE_ADD_TO_PATH: 5,
  51. FILL_STROKE_ADD_TO_PATH: 6,
  52. ADD_TO_PATH: 7,
  53. FILL_STROKE_MASK: 3,
  54. ADD_TO_PATH_FLAG: 4
  55. };
  56. var ImageKind = {
  57. GRAYSCALE_1BPP: 1,
  58. RGB_24BPP: 2,
  59. RGBA_32BPP: 3
  60. };
  61. var AnnotationType = {
  62. TEXT: 1,
  63. LINK: 2,
  64. FREETEXT: 3,
  65. LINE: 4,
  66. SQUARE: 5,
  67. CIRCLE: 6,
  68. POLYGON: 7,
  69. POLYLINE: 8,
  70. HIGHLIGHT: 9,
  71. UNDERLINE: 10,
  72. SQUIGGLY: 11,
  73. STRIKEOUT: 12,
  74. STAMP: 13,
  75. CARET: 14,
  76. INK: 15,
  77. POPUP: 16,
  78. FILEATTACHMENT: 17,
  79. SOUND: 18,
  80. MOVIE: 19,
  81. WIDGET: 20,
  82. SCREEN: 21,
  83. PRINTERMARK: 22,
  84. TRAPNET: 23,
  85. WATERMARK: 24,
  86. THREED: 25,
  87. REDACT: 26
  88. };
  89. var AnnotationFlag = {
  90. INVISIBLE: 0x01,
  91. HIDDEN: 0x02,
  92. PRINT: 0x04,
  93. NOZOOM: 0x08,
  94. NOROTATE: 0x10,
  95. NOVIEW: 0x20,
  96. READONLY: 0x40,
  97. LOCKED: 0x80,
  98. TOGGLENOVIEW: 0x100,
  99. LOCKEDCONTENTS: 0x200
  100. };
  101. var AnnotationFieldFlag = {
  102. READONLY: 0x0000001,
  103. REQUIRED: 0x0000002,
  104. NOEXPORT: 0x0000004,
  105. MULTILINE: 0x0001000,
  106. PASSWORD: 0x0002000,
  107. NOTOGGLETOOFF: 0x0004000,
  108. RADIO: 0x0008000,
  109. PUSHBUTTON: 0x0010000,
  110. COMBO: 0x0020000,
  111. EDIT: 0x0040000,
  112. SORT: 0x0080000,
  113. FILESELECT: 0x0100000,
  114. MULTISELECT: 0x0200000,
  115. DONOTSPELLCHECK: 0x0400000,
  116. DONOTSCROLL: 0x0800000,
  117. COMB: 0x1000000,
  118. RICHTEXT: 0x2000000,
  119. RADIOSINUNISON: 0x2000000,
  120. COMMITONSELCHANGE: 0x4000000
  121. };
  122. var AnnotationBorderStyleType = {
  123. SOLID: 1,
  124. DASHED: 2,
  125. BEVELED: 3,
  126. INSET: 4,
  127. UNDERLINE: 5
  128. };
  129. var StreamType = {
  130. UNKNOWN: 0,
  131. FLATE: 1,
  132. LZW: 2,
  133. DCT: 3,
  134. JPX: 4,
  135. JBIG: 5,
  136. A85: 6,
  137. AHX: 7,
  138. CCF: 8,
  139. RL: 9
  140. };
  141. var FontType = {
  142. UNKNOWN: 0,
  143. TYPE1: 1,
  144. TYPE1C: 2,
  145. CIDFONTTYPE0: 3,
  146. CIDFONTTYPE0C: 4,
  147. TRUETYPE: 5,
  148. CIDFONTTYPE2: 6,
  149. TYPE3: 7,
  150. OPENTYPE: 8,
  151. TYPE0: 9,
  152. MMTYPE1: 10
  153. };
  154. var VERBOSITY_LEVELS = {
  155. errors: 0,
  156. warnings: 1,
  157. infos: 5
  158. };
  159. // All the possible operations for an operator list.
  160. var OPS = {
  161. // Intentionally start from 1 so it is easy to spot bad operators that will be
  162. // 0's.
  163. dependency: 1,
  164. setLineWidth: 2,
  165. setLineCap: 3,
  166. setLineJoin: 4,
  167. setMiterLimit: 5,
  168. setDash: 6,
  169. setRenderingIntent: 7,
  170. setFlatness: 8,
  171. setGState: 9,
  172. save: 10,
  173. restore: 11,
  174. transform: 12,
  175. moveTo: 13,
  176. lineTo: 14,
  177. curveTo: 15,
  178. curveTo2: 16,
  179. curveTo3: 17,
  180. closePath: 18,
  181. rectangle: 19,
  182. stroke: 20,
  183. closeStroke: 21,
  184. fill: 22,
  185. eoFill: 23,
  186. fillStroke: 24,
  187. eoFillStroke: 25,
  188. closeFillStroke: 26,
  189. closeEOFillStroke: 27,
  190. endPath: 28,
  191. clip: 29,
  192. eoClip: 30,
  193. beginText: 31,
  194. endText: 32,
  195. setCharSpacing: 33,
  196. setWordSpacing: 34,
  197. setHScale: 35,
  198. setLeading: 36,
  199. setFont: 37,
  200. setTextRenderingMode: 38,
  201. setTextRise: 39,
  202. moveText: 40,
  203. setLeadingMoveText: 41,
  204. setTextMatrix: 42,
  205. nextLine: 43,
  206. showText: 44,
  207. showSpacedText: 45,
  208. nextLineShowText: 46,
  209. nextLineSetSpacingShowText: 47,
  210. setCharWidth: 48,
  211. setCharWidthAndBounds: 49,
  212. setStrokeColorSpace: 50,
  213. setFillColorSpace: 51,
  214. setStrokeColor: 52,
  215. setStrokeColorN: 53,
  216. setFillColor: 54,
  217. setFillColorN: 55,
  218. setStrokeGray: 56,
  219. setFillGray: 57,
  220. setStrokeRGBColor: 58,
  221. setFillRGBColor: 59,
  222. setStrokeCMYKColor: 60,
  223. setFillCMYKColor: 61,
  224. shadingFill: 62,
  225. beginInlineImage: 63,
  226. beginImageData: 64,
  227. endInlineImage: 65,
  228. paintXObject: 66,
  229. markPoint: 67,
  230. markPointProps: 68,
  231. beginMarkedContent: 69,
  232. beginMarkedContentProps: 70,
  233. endMarkedContent: 71,
  234. beginCompat: 72,
  235. endCompat: 73,
  236. paintFormXObjectBegin: 74,
  237. paintFormXObjectEnd: 75,
  238. beginGroup: 76,
  239. endGroup: 77,
  240. beginAnnotations: 78,
  241. endAnnotations: 79,
  242. beginAnnotation: 80,
  243. endAnnotation: 81,
  244. paintJpegXObject: 82,
  245. paintImageMaskXObject: 83,
  246. paintImageMaskXObjectGroup: 84,
  247. paintImageXObject: 85,
  248. paintInlineImageXObject: 86,
  249. paintInlineImageXObjectGroup: 87,
  250. paintImageXObjectRepeat: 88,
  251. paintImageMaskXObjectRepeat: 89,
  252. paintSolidColorImageMask: 90,
  253. constructPath: 91
  254. };
  255. var verbosity = VERBOSITY_LEVELS.warnings;
  256. function setVerbosityLevel(level) {
  257. verbosity = level;
  258. }
  259. function getVerbosityLevel() {
  260. return verbosity;
  261. }
  262. // A notice for devs. These are good for things that are helpful to devs, such
  263. // as warning that Workers were disabled, which is important to devs but not
  264. // end users.
  265. function info(msg) {
  266. if (verbosity >= VERBOSITY_LEVELS.infos) {
  267. console.log('Info: ' + msg);
  268. }
  269. }
  270. // Non-fatal warnings.
  271. function warn(msg) {
  272. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  273. console.log('Warning: ' + msg);
  274. }
  275. }
  276. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  277. function deprecated(details) {
  278. console.log('Deprecated API usage: ' + details);
  279. }
  280. // Fatal errors that should trigger the fallback UI and halt execution by
  281. // throwing an exception.
  282. function error(msg) {
  283. if (verbosity >= VERBOSITY_LEVELS.errors) {
  284. console.log('Error: ' + msg);
  285. console.log(backtrace());
  286. }
  287. throw new Error(msg);
  288. }
  289. function backtrace() {
  290. try {
  291. throw new Error();
  292. } catch (e) {
  293. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  294. }
  295. }
  296. function assert(cond, msg) {
  297. if (!cond) {
  298. error(msg);
  299. }
  300. }
  301. var UNSUPPORTED_FEATURES = {
  302. unknown: 'unknown',
  303. forms: 'forms',
  304. javaScript: 'javaScript',
  305. smask: 'smask',
  306. shadingPattern: 'shadingPattern',
  307. font: 'font'
  308. };
  309. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  310. function isSameOrigin(baseUrl, otherUrl) {
  311. try {
  312. var base = new URL(baseUrl);
  313. if (!base.origin || base.origin === 'null') {
  314. return false;
  315. }
  316. } // non-HTTP url
  317. catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Checks if URLs use one of the whitelisted protocols, e.g. to avoid XSS.
  324. function isValidProtocol(url) {
  325. if (!url) {
  326. return false;
  327. }
  328. switch (url.protocol) {
  329. case 'http:':
  330. case 'https:':
  331. case 'ftp:':
  332. case 'mailto:':
  333. case 'tel:':
  334. return true;
  335. default:
  336. return false;
  337. }
  338. }
  339. /**
  340. * Attempts to create a valid absolute URL (utilizing `isValidProtocol`).
  341. * @param {URL|string} url - An absolute, or relative, URL.
  342. * @param {URL|string} baseUrl - An absolute URL.
  343. * @returns Either a valid {URL}, or `null` otherwise.
  344. */
  345. function createValidAbsoluteUrl(url, baseUrl) {
  346. if (!url) {
  347. return null;
  348. }
  349. try {
  350. var absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  351. if (isValidProtocol(absoluteUrl)) {
  352. return absoluteUrl;
  353. }
  354. } catch (ex) {
  355. }
  356. return null;
  357. }
  358. function shadow(obj, prop, value) {
  359. Object.defineProperty(obj, prop, {
  360. value: value,
  361. enumerable: true,
  362. configurable: true,
  363. writable: false
  364. });
  365. return value;
  366. }
  367. function getLookupTableFactory(initializer) {
  368. var lookup;
  369. return function () {
  370. if (initializer) {
  371. lookup = Object.create(null);
  372. initializer(lookup);
  373. initializer = null;
  374. }
  375. return lookup;
  376. };
  377. }
  378. var PasswordResponses = {
  379. NEED_PASSWORD: 1,
  380. INCORRECT_PASSWORD: 2
  381. };
  382. var PasswordException = function PasswordExceptionClosure() {
  383. function PasswordException(msg, code) {
  384. this.name = 'PasswordException';
  385. this.message = msg;
  386. this.code = code;
  387. }
  388. PasswordException.prototype = new Error();
  389. PasswordException.constructor = PasswordException;
  390. return PasswordException;
  391. }();
  392. var UnknownErrorException = function UnknownErrorExceptionClosure() {
  393. function UnknownErrorException(msg, details) {
  394. this.name = 'UnknownErrorException';
  395. this.message = msg;
  396. this.details = details;
  397. }
  398. UnknownErrorException.prototype = new Error();
  399. UnknownErrorException.constructor = UnknownErrorException;
  400. return UnknownErrorException;
  401. }();
  402. var InvalidPDFException = function InvalidPDFExceptionClosure() {
  403. function InvalidPDFException(msg) {
  404. this.name = 'InvalidPDFException';
  405. this.message = msg;
  406. }
  407. InvalidPDFException.prototype = new Error();
  408. InvalidPDFException.constructor = InvalidPDFException;
  409. return InvalidPDFException;
  410. }();
  411. var MissingPDFException = function MissingPDFExceptionClosure() {
  412. function MissingPDFException(msg) {
  413. this.name = 'MissingPDFException';
  414. this.message = msg;
  415. }
  416. MissingPDFException.prototype = new Error();
  417. MissingPDFException.constructor = MissingPDFException;
  418. return MissingPDFException;
  419. }();
  420. var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
  421. function UnexpectedResponseException(msg, status) {
  422. this.name = 'UnexpectedResponseException';
  423. this.message = msg;
  424. this.status = status;
  425. }
  426. UnexpectedResponseException.prototype = new Error();
  427. UnexpectedResponseException.constructor = UnexpectedResponseException;
  428. return UnexpectedResponseException;
  429. }();
  430. var NotImplementedException = function NotImplementedExceptionClosure() {
  431. function NotImplementedException(msg) {
  432. this.message = msg;
  433. }
  434. NotImplementedException.prototype = new Error();
  435. NotImplementedException.prototype.name = 'NotImplementedException';
  436. NotImplementedException.constructor = NotImplementedException;
  437. return NotImplementedException;
  438. }();
  439. var MissingDataException = function MissingDataExceptionClosure() {
  440. function MissingDataException(begin, end) {
  441. this.begin = begin;
  442. this.end = end;
  443. this.message = 'Missing data [' + begin + ', ' + end + ')';
  444. }
  445. MissingDataException.prototype = new Error();
  446. MissingDataException.prototype.name = 'MissingDataException';
  447. MissingDataException.constructor = MissingDataException;
  448. return MissingDataException;
  449. }();
  450. var XRefParseException = function XRefParseExceptionClosure() {
  451. function XRefParseException(msg) {
  452. this.message = msg;
  453. }
  454. XRefParseException.prototype = new Error();
  455. XRefParseException.prototype.name = 'XRefParseException';
  456. XRefParseException.constructor = XRefParseException;
  457. return XRefParseException;
  458. }();
  459. var NullCharactersRegExp = /\x00/g;
  460. function removeNullCharacters(str) {
  461. if (typeof str !== 'string') {
  462. warn('The argument for removeNullCharacters must be a string.');
  463. return str;
  464. }
  465. return str.replace(NullCharactersRegExp, '');
  466. }
  467. function bytesToString(bytes) {
  468. assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
  469. var length = bytes.length;
  470. var MAX_ARGUMENT_COUNT = 8192;
  471. if (length < MAX_ARGUMENT_COUNT) {
  472. return String.fromCharCode.apply(null, bytes);
  473. }
  474. var strBuf = [];
  475. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  476. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  477. var chunk = bytes.subarray(i, chunkEnd);
  478. strBuf.push(String.fromCharCode.apply(null, chunk));
  479. }
  480. return strBuf.join('');
  481. }
  482. function stringToBytes(str) {
  483. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  484. var length = str.length;
  485. var bytes = new Uint8Array(length);
  486. for (var i = 0; i < length; ++i) {
  487. bytes[i] = str.charCodeAt(i) & 0xFF;
  488. }
  489. return bytes;
  490. }
  491. /**
  492. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  493. * @param {Array|Uint8Array|string} arr
  494. * @returns {number}
  495. */
  496. function arrayByteLength(arr) {
  497. if (arr.length !== undefined) {
  498. return arr.length;
  499. }
  500. assert(arr.byteLength !== undefined);
  501. return arr.byteLength;
  502. }
  503. /**
  504. * Combines array items (arrays) into single Uint8Array object.
  505. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  506. * @returns {Uint8Array}
  507. */
  508. function arraysToBytes(arr) {
  509. // Shortcut: if first and only item is Uint8Array, return it.
  510. if (arr.length === 1 && arr[0] instanceof Uint8Array) {
  511. return arr[0];
  512. }
  513. var resultLength = 0;
  514. var i, ii = arr.length;
  515. var item, itemLength;
  516. for (i = 0; i < ii; i++) {
  517. item = arr[i];
  518. itemLength = arrayByteLength(item);
  519. resultLength += itemLength;
  520. }
  521. var pos = 0;
  522. var data = new Uint8Array(resultLength);
  523. for (i = 0; i < ii; i++) {
  524. item = arr[i];
  525. if (!(item instanceof Uint8Array)) {
  526. if (typeof item === 'string') {
  527. item = stringToBytes(item);
  528. } else {
  529. item = new Uint8Array(item);
  530. }
  531. }
  532. itemLength = item.byteLength;
  533. data.set(item, pos);
  534. pos += itemLength;
  535. }
  536. return data;
  537. }
  538. function string32(value) {
  539. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  540. }
  541. function log2(x) {
  542. var n = 1, i = 0;
  543. while (x > n) {
  544. n <<= 1;
  545. i++;
  546. }
  547. return i;
  548. }
  549. function readInt8(data, start) {
  550. return data[start] << 24 >> 24;
  551. }
  552. function readUint16(data, offset) {
  553. return data[offset] << 8 | data[offset + 1];
  554. }
  555. function readUint32(data, offset) {
  556. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  557. }
  558. // Lazy test the endianness of the platform
  559. // NOTE: This will be 'true' for simulated TypedArrays
  560. function isLittleEndian() {
  561. var buffer8 = new Uint8Array(2);
  562. buffer8[0] = 1;
  563. var buffer16 = new Uint16Array(buffer8.buffer);
  564. return buffer16[0] === 1;
  565. }
  566. // Checks if it's possible to eval JS expressions.
  567. function isEvalSupported() {
  568. try {
  569. new Function('');
  570. return true;
  571. } catch (e) {
  572. return false;
  573. }
  574. }
  575. var Uint32ArrayView = function Uint32ArrayViewClosure() {
  576. function Uint32ArrayView(buffer, length) {
  577. this.buffer = buffer;
  578. this.byteLength = buffer.length;
  579. this.length = length === undefined ? this.byteLength >> 2 : length;
  580. ensureUint32ArrayViewProps(this.length);
  581. }
  582. Uint32ArrayView.prototype = Object.create(null);
  583. var uint32ArrayViewSetters = 0;
  584. function createUint32ArrayProp(index) {
  585. return {
  586. get: function () {
  587. var buffer = this.buffer, offset = index << 2;
  588. return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
  589. },
  590. set: function (value) {
  591. var buffer = this.buffer, offset = index << 2;
  592. buffer[offset] = value & 255;
  593. buffer[offset + 1] = value >> 8 & 255;
  594. buffer[offset + 2] = value >> 16 & 255;
  595. buffer[offset + 3] = value >>> 24 & 255;
  596. }
  597. };
  598. }
  599. function ensureUint32ArrayViewProps(length) {
  600. while (uint32ArrayViewSetters < length) {
  601. Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
  602. uint32ArrayViewSetters++;
  603. }
  604. }
  605. return Uint32ArrayView;
  606. }();
  607. exports.Uint32ArrayView = Uint32ArrayView;
  608. var IDENTITY_MATRIX = [
  609. 1,
  610. 0,
  611. 0,
  612. 1,
  613. 0,
  614. 0
  615. ];
  616. var Util = function UtilClosure() {
  617. function Util() {
  618. }
  619. var rgbBuf = [
  620. 'rgb(',
  621. 0,
  622. ',',
  623. 0,
  624. ',',
  625. 0,
  626. ')'
  627. ];
  628. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  629. // creating many intermediate strings.
  630. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  631. rgbBuf[1] = r;
  632. rgbBuf[3] = g;
  633. rgbBuf[5] = b;
  634. return rgbBuf.join('');
  635. };
  636. // Concatenates two transformation matrices together and returns the result.
  637. Util.transform = function Util_transform(m1, m2) {
  638. return [
  639. m1[0] * m2[0] + m1[2] * m2[1],
  640. m1[1] * m2[0] + m1[3] * m2[1],
  641. m1[0] * m2[2] + m1[2] * m2[3],
  642. m1[1] * m2[2] + m1[3] * m2[3],
  643. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  644. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  645. ];
  646. };
  647. // For 2d affine transforms
  648. Util.applyTransform = function Util_applyTransform(p, m) {
  649. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  650. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  651. return [
  652. xt,
  653. yt
  654. ];
  655. };
  656. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  657. var d = m[0] * m[3] - m[1] * m[2];
  658. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  659. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  660. return [
  661. xt,
  662. yt
  663. ];
  664. };
  665. // Applies the transform to the rectangle and finds the minimum axially
  666. // aligned bounding box.
  667. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
  668. var p1 = Util.applyTransform(r, m);
  669. var p2 = Util.applyTransform(r.slice(2, 4), m);
  670. var p3 = Util.applyTransform([
  671. r[0],
  672. r[3]
  673. ], m);
  674. var p4 = Util.applyTransform([
  675. r[2],
  676. r[1]
  677. ], m);
  678. return [
  679. Math.min(p1[0], p2[0], p3[0], p4[0]),
  680. Math.min(p1[1], p2[1], p3[1], p4[1]),
  681. Math.max(p1[0], p2[0], p3[0], p4[0]),
  682. Math.max(p1[1], p2[1], p3[1], p4[1])
  683. ];
  684. };
  685. Util.inverseTransform = function Util_inverseTransform(m) {
  686. var d = m[0] * m[3] - m[1] * m[2];
  687. return [
  688. m[3] / d,
  689. -m[1] / d,
  690. -m[2] / d,
  691. m[0] / d,
  692. (m[2] * m[5] - m[4] * m[3]) / d,
  693. (m[4] * m[1] - m[5] * m[0]) / d
  694. ];
  695. };
  696. // Apply a generic 3d matrix M on a 3-vector v:
  697. // | a b c | | X |
  698. // | d e f | x | Y |
  699. // | g h i | | Z |
  700. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  701. // with v as [X,Y,Z]
  702. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  703. return [
  704. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  705. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  706. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  707. ];
  708. };
  709. // This calculation uses Singular Value Decomposition.
  710. // The SVD can be represented with formula A = USV. We are interested in the
  711. // matrix S here because it represents the scale values.
  712. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
  713. var transpose = [
  714. m[0],
  715. m[2],
  716. m[1],
  717. m[3]
  718. ];
  719. // Multiply matrix m with its transpose.
  720. var a = m[0] * transpose[0] + m[1] * transpose[2];
  721. var b = m[0] * transpose[1] + m[1] * transpose[3];
  722. var c = m[2] * transpose[0] + m[3] * transpose[2];
  723. var d = m[2] * transpose[1] + m[3] * transpose[3];
  724. // Solve the second degree polynomial to get roots.
  725. var first = (a + d) / 2;
  726. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  727. var sx = first + second || 1;
  728. var sy = first - second || 1;
  729. // Scale values are the square roots of the eigenvalues.
  730. return [
  731. Math.sqrt(sx),
  732. Math.sqrt(sy)
  733. ];
  734. };
  735. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  736. // For coordinate systems whose origin lies in the bottom-left, this
  737. // means normalization to (BL,TR) ordering. For systems with origin in the
  738. // top-left, this means (TL,BR) ordering.
  739. Util.normalizeRect = function Util_normalizeRect(rect) {
  740. var r = rect.slice(0);
  741. // clone rect
  742. if (rect[0] > rect[2]) {
  743. r[0] = rect[2];
  744. r[2] = rect[0];
  745. }
  746. if (rect[1] > rect[3]) {
  747. r[1] = rect[3];
  748. r[3] = rect[1];
  749. }
  750. return r;
  751. };
  752. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  753. // intersection of rect1 and rect2. If no intersection, returns 'false'
  754. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  755. Util.intersect = function Util_intersect(rect1, rect2) {
  756. function compare(a, b) {
  757. return a - b;
  758. }
  759. // Order points along the axes
  760. var orderedX = [
  761. rect1[0],
  762. rect1[2],
  763. rect2[0],
  764. rect2[2]
  765. ].sort(compare), orderedY = [
  766. rect1[1],
  767. rect1[3],
  768. rect2[1],
  769. rect2[3]
  770. ].sort(compare), result = [];
  771. rect1 = Util.normalizeRect(rect1);
  772. rect2 = Util.normalizeRect(rect2);
  773. // X: first and second points belong to different rectangles?
  774. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  775. // Intersection must be between second and third points
  776. result[0] = orderedX[1];
  777. result[2] = orderedX[2];
  778. } else {
  779. return false;
  780. }
  781. // Y: first and second points belong to different rectangles?
  782. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  783. // Intersection must be between second and third points
  784. result[1] = orderedY[1];
  785. result[3] = orderedY[2];
  786. } else {
  787. return false;
  788. }
  789. return result;
  790. };
  791. Util.sign = function Util_sign(num) {
  792. return num < 0 ? -1 : 1;
  793. };
  794. var ROMAN_NUMBER_MAP = [
  795. '',
  796. 'C',
  797. 'CC',
  798. 'CCC',
  799. 'CD',
  800. 'D',
  801. 'DC',
  802. 'DCC',
  803. 'DCCC',
  804. 'CM',
  805. '',
  806. 'X',
  807. 'XX',
  808. 'XXX',
  809. 'XL',
  810. 'L',
  811. 'LX',
  812. 'LXX',
  813. 'LXXX',
  814. 'XC',
  815. '',
  816. 'I',
  817. 'II',
  818. 'III',
  819. 'IV',
  820. 'V',
  821. 'VI',
  822. 'VII',
  823. 'VIII',
  824. 'IX'
  825. ];
  826. /**
  827. * Converts positive integers to (upper case) Roman numerals.
  828. * @param {integer} number - The number that should be converted.
  829. * @param {boolean} lowerCase - Indicates if the result should be converted
  830. * to lower case letters. The default is false.
  831. * @return {string} The resulting Roman number.
  832. */
  833. Util.toRoman = function Util_toRoman(number, lowerCase) {
  834. assert(isInt(number) && number > 0, 'The number should be a positive integer.');
  835. var pos, romanBuf = [];
  836. // Thousands
  837. while (number >= 1000) {
  838. number -= 1000;
  839. romanBuf.push('M');
  840. }
  841. // Hundreds
  842. pos = number / 100 | 0;
  843. number %= 100;
  844. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  845. // Tens
  846. pos = number / 10 | 0;
  847. number %= 10;
  848. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  849. // Ones
  850. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  851. var romanStr = romanBuf.join('');
  852. return lowerCase ? romanStr.toLowerCase() : romanStr;
  853. };
  854. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  855. Array.prototype.push.apply(arr1, arr2);
  856. };
  857. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  858. Array.prototype.unshift.apply(arr1, arr2);
  859. };
  860. Util.extendObj = function extendObj(obj1, obj2) {
  861. for (var key in obj2) {
  862. obj1[key] = obj2[key];
  863. }
  864. };
  865. Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
  866. while (dict && !dict.has(name)) {
  867. dict = dict.get('Parent');
  868. }
  869. if (!dict) {
  870. return null;
  871. }
  872. return getArray ? dict.getArray(name) : dict.get(name);
  873. };
  874. Util.inherit = function Util_inherit(sub, base, prototype) {
  875. sub.prototype = Object.create(base.prototype);
  876. sub.prototype.constructor = sub;
  877. for (var prop in prototype) {
  878. sub.prototype[prop] = prototype[prop];
  879. }
  880. };
  881. Util.loadScript = function Util_loadScript(src, callback) {
  882. var script = document.createElement('script');
  883. var loaded = false;
  884. script.setAttribute('src', src);
  885. if (callback) {
  886. script.onload = function () {
  887. if (!loaded) {
  888. callback();
  889. }
  890. loaded = true;
  891. };
  892. }
  893. document.getElementsByTagName('head')[0].appendChild(script);
  894. };
  895. return Util;
  896. }();
  897. /**
  898. * PDF page viewport created based on scale, rotation and offset.
  899. * @class
  900. * @alias PageViewport
  901. */
  902. var PageViewport = function PageViewportClosure() {
  903. /**
  904. * @constructor
  905. * @private
  906. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  907. * @param scale {number} scale of the viewport.
  908. * @param rotation {number} rotations of the viewport in degrees.
  909. * @param offsetX {number} offset X
  910. * @param offsetY {number} offset Y
  911. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  912. */
  913. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  914. this.viewBox = viewBox;
  915. this.scale = scale;
  916. this.rotation = rotation;
  917. this.offsetX = offsetX;
  918. this.offsetY = offsetY;
  919. // creating transform to convert pdf coordinate system to the normal
  920. // canvas like coordinates taking in account scale and rotation
  921. var centerX = (viewBox[2] + viewBox[0]) / 2;
  922. var centerY = (viewBox[3] + viewBox[1]) / 2;
  923. var rotateA, rotateB, rotateC, rotateD;
  924. rotation = rotation % 360;
  925. rotation = rotation < 0 ? rotation + 360 : rotation;
  926. switch (rotation) {
  927. case 180:
  928. rotateA = -1;
  929. rotateB = 0;
  930. rotateC = 0;
  931. rotateD = 1;
  932. break;
  933. case 90:
  934. rotateA = 0;
  935. rotateB = 1;
  936. rotateC = 1;
  937. rotateD = 0;
  938. break;
  939. case 270:
  940. rotateA = 0;
  941. rotateB = -1;
  942. rotateC = -1;
  943. rotateD = 0;
  944. break;
  945. //case 0:
  946. default:
  947. rotateA = 1;
  948. rotateB = 0;
  949. rotateC = 0;
  950. rotateD = -1;
  951. break;
  952. }
  953. if (dontFlip) {
  954. rotateC = -rotateC;
  955. rotateD = -rotateD;
  956. }
  957. var offsetCanvasX, offsetCanvasY;
  958. var width, height;
  959. if (rotateA === 0) {
  960. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  961. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  962. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  963. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  964. } else {
  965. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  966. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  967. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  968. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  969. }
  970. // creating transform for the following operations:
  971. // translate(-centerX, -centerY), rotate and flip vertically,
  972. // scale, and translate(offsetCanvasX, offsetCanvasY)
  973. this.transform = [
  974. rotateA * scale,
  975. rotateB * scale,
  976. rotateC * scale,
  977. rotateD * scale,
  978. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  979. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  980. ];
  981. this.width = width;
  982. this.height = height;
  983. this.fontScale = scale;
  984. }
  985. PageViewport.prototype = /** @lends PageViewport.prototype */
  986. {
  987. /**
  988. * Clones viewport with additional properties.
  989. * @param args {Object} (optional) If specified, may contain the 'scale' or
  990. * 'rotation' properties to override the corresponding properties in
  991. * the cloned viewport.
  992. * @returns {PageViewport} Cloned viewport.
  993. */
  994. clone: function PageViewPort_clone(args) {
  995. args = args || {};
  996. var scale = 'scale' in args ? args.scale : this.scale;
  997. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  998. return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
  999. },
  1000. /**
  1001. * Converts PDF point to the viewport coordinates. For examples, useful for
  1002. * converting PDF location into canvas pixel coordinates.
  1003. * @param x {number} X coordinate.
  1004. * @param y {number} Y coordinate.
  1005. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1006. * point in the viewport coordinate space.
  1007. * @see {@link convertToPdfPoint}
  1008. * @see {@link convertToViewportRectangle}
  1009. */
  1010. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  1011. return Util.applyTransform([
  1012. x,
  1013. y
  1014. ], this.transform);
  1015. },
  1016. /**
  1017. * Converts PDF rectangle to the viewport coordinates.
  1018. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  1019. * @returns {Array} Contains corresponding coordinates of the rectangle
  1020. * in the viewport coordinate space.
  1021. * @see {@link convertToViewportPoint}
  1022. */
  1023. convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
  1024. var tl = Util.applyTransform([
  1025. rect[0],
  1026. rect[1]
  1027. ], this.transform);
  1028. var br = Util.applyTransform([
  1029. rect[2],
  1030. rect[3]
  1031. ], this.transform);
  1032. return [
  1033. tl[0],
  1034. tl[1],
  1035. br[0],
  1036. br[1]
  1037. ];
  1038. },
  1039. /**
  1040. * Converts viewport coordinates to the PDF location. For examples, useful
  1041. * for converting canvas pixel location into PDF one.
  1042. * @param x {number} X coordinate.
  1043. * @param y {number} Y coordinate.
  1044. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1045. * point in the PDF coordinate space.
  1046. * @see {@link convertToViewportPoint}
  1047. */
  1048. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  1049. return Util.applyInverseTransform([
  1050. x,
  1051. y
  1052. ], this.transform);
  1053. }
  1054. };
  1055. return PageViewport;
  1056. }();
  1057. var PDFStringTranslateTable = [
  1058. 0,
  1059. 0,
  1060. 0,
  1061. 0,
  1062. 0,
  1063. 0,
  1064. 0,
  1065. 0,
  1066. 0,
  1067. 0,
  1068. 0,
  1069. 0,
  1070. 0,
  1071. 0,
  1072. 0,
  1073. 0,
  1074. 0,
  1075. 0,
  1076. 0,
  1077. 0,
  1078. 0,
  1079. 0,
  1080. 0,
  1081. 0,
  1082. 0x2D8,
  1083. 0x2C7,
  1084. 0x2C6,
  1085. 0x2D9,
  1086. 0x2DD,
  1087. 0x2DB,
  1088. 0x2DA,
  1089. 0x2DC,
  1090. 0,
  1091. 0,
  1092. 0,
  1093. 0,
  1094. 0,
  1095. 0,
  1096. 0,
  1097. 0,
  1098. 0,
  1099. 0,
  1100. 0,
  1101. 0,
  1102. 0,
  1103. 0,
  1104. 0,
  1105. 0,
  1106. 0,
  1107. 0,
  1108. 0,
  1109. 0,
  1110. 0,
  1111. 0,
  1112. 0,
  1113. 0,
  1114. 0,
  1115. 0,
  1116. 0,
  1117. 0,
  1118. 0,
  1119. 0,
  1120. 0,
  1121. 0,
  1122. 0,
  1123. 0,
  1124. 0,
  1125. 0,
  1126. 0,
  1127. 0,
  1128. 0,
  1129. 0,
  1130. 0,
  1131. 0,
  1132. 0,
  1133. 0,
  1134. 0,
  1135. 0,
  1136. 0,
  1137. 0,
  1138. 0,
  1139. 0,
  1140. 0,
  1141. 0,
  1142. 0,
  1143. 0,
  1144. 0,
  1145. 0,
  1146. 0,
  1147. 0,
  1148. 0,
  1149. 0,
  1150. 0,
  1151. 0,
  1152. 0,
  1153. 0,
  1154. 0,
  1155. 0,
  1156. 0,
  1157. 0,
  1158. 0,
  1159. 0,
  1160. 0,
  1161. 0,
  1162. 0,
  1163. 0,
  1164. 0,
  1165. 0,
  1166. 0,
  1167. 0,
  1168. 0,
  1169. 0,
  1170. 0,
  1171. 0,
  1172. 0,
  1173. 0,
  1174. 0,
  1175. 0,
  1176. 0,
  1177. 0,
  1178. 0,
  1179. 0,
  1180. 0,
  1181. 0,
  1182. 0,
  1183. 0,
  1184. 0,
  1185. 0,
  1186. 0x2022,
  1187. 0x2020,
  1188. 0x2021,
  1189. 0x2026,
  1190. 0x2014,
  1191. 0x2013,
  1192. 0x192,
  1193. 0x2044,
  1194. 0x2039,
  1195. 0x203A,
  1196. 0x2212,
  1197. 0x2030,
  1198. 0x201E,
  1199. 0x201C,
  1200. 0x201D,
  1201. 0x2018,
  1202. 0x2019,
  1203. 0x201A,
  1204. 0x2122,
  1205. 0xFB01,
  1206. 0xFB02,
  1207. 0x141,
  1208. 0x152,
  1209. 0x160,
  1210. 0x178,
  1211. 0x17D,
  1212. 0x131,
  1213. 0x142,
  1214. 0x153,
  1215. 0x161,
  1216. 0x17E,
  1217. 0,
  1218. 0x20AC
  1219. ];
  1220. function stringToPDFString(str) {
  1221. var i, n = str.length, strBuf = [];
  1222. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1223. // UTF16BE BOM
  1224. for (i = 2; i < n; i += 2) {
  1225. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1226. }
  1227. } else {
  1228. for (i = 0; i < n; ++i) {
  1229. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1230. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1231. }
  1232. }
  1233. return strBuf.join('');
  1234. }
  1235. function stringToUTF8String(str) {
  1236. return decodeURIComponent(escape(str));
  1237. }
  1238. function utf8StringToString(str) {
  1239. return unescape(encodeURIComponent(str));
  1240. }
  1241. function isEmptyObj(obj) {
  1242. for (var key in obj) {
  1243. return false;
  1244. }
  1245. return true;
  1246. }
  1247. function isBool(v) {
  1248. return typeof v === 'boolean';
  1249. }
  1250. function isInt(v) {
  1251. return typeof v === 'number' && (v | 0) === v;
  1252. }
  1253. function isNum(v) {
  1254. return typeof v === 'number';
  1255. }
  1256. function isString(v) {
  1257. return typeof v === 'string';
  1258. }
  1259. function isArray(v) {
  1260. return v instanceof Array;
  1261. }
  1262. function isArrayBuffer(v) {
  1263. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1264. }
  1265. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1266. function isSpace(ch) {
  1267. return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
  1268. }
  1269. /**
  1270. * Promise Capability object.
  1271. *
  1272. * @typedef {Object} PromiseCapability
  1273. * @property {Promise} promise - A promise object.
  1274. * @property {function} resolve - Fulfills the promise.
  1275. * @property {function} reject - Rejects the promise.
  1276. */
  1277. /**
  1278. * Creates a promise capability object.
  1279. * @alias createPromiseCapability
  1280. *
  1281. * @return {PromiseCapability} A capability object contains:
  1282. * - a Promise, resolve and reject methods.
  1283. */
  1284. function createPromiseCapability() {
  1285. var capability = {};
  1286. capability.promise = new Promise(function (resolve, reject) {
  1287. capability.resolve = resolve;
  1288. capability.reject = reject;
  1289. });
  1290. return capability;
  1291. }
  1292. /**
  1293. * Polyfill for Promises:
  1294. * The following promise implementation tries to generally implement the
  1295. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1296. * - There currently isn't a separate deferred and promise object.
  1297. * - Unhandled rejections eventually show an error if they aren't handled.
  1298. *
  1299. * Based off of the work in:
  1300. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1301. */
  1302. (function PromiseClosure() {
  1303. if (globalScope.Promise) {
  1304. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1305. if (typeof globalScope.Promise.all !== 'function') {
  1306. globalScope.Promise.all = function (iterable) {
  1307. var count = 0, results = [], resolve, reject;
  1308. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1309. resolve = resolve_;
  1310. reject = reject_;
  1311. });
  1312. iterable.forEach(function (p, i) {
  1313. count++;
  1314. p.then(function (result) {
  1315. results[i] = result;
  1316. count--;
  1317. if (count === 0) {
  1318. resolve(results);
  1319. }
  1320. }, reject);
  1321. });
  1322. if (count === 0) {
  1323. resolve(results);
  1324. }
  1325. return promise;
  1326. };
  1327. }
  1328. if (typeof globalScope.Promise.resolve !== 'function') {
  1329. globalScope.Promise.resolve = function (value) {
  1330. return new globalScope.Promise(function (resolve) {
  1331. resolve(value);
  1332. });
  1333. };
  1334. }
  1335. if (typeof globalScope.Promise.reject !== 'function') {
  1336. globalScope.Promise.reject = function (reason) {
  1337. return new globalScope.Promise(function (resolve, reject) {
  1338. reject(reason);
  1339. });
  1340. };
  1341. }
  1342. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1343. globalScope.Promise.prototype.catch = function (onReject) {
  1344. return globalScope.Promise.prototype.then(undefined, onReject);
  1345. };
  1346. }
  1347. return;
  1348. }
  1349. var STATUS_PENDING = 0;
  1350. var STATUS_RESOLVED = 1;
  1351. var STATUS_REJECTED = 2;
  1352. // In an attempt to avoid silent exceptions, unhandled rejections are
  1353. // tracked and if they aren't handled in a certain amount of time an
  1354. // error is logged.
  1355. var REJECTION_TIMEOUT = 500;
  1356. var HandlerManager = {
  1357. handlers: [],
  1358. running: false,
  1359. unhandledRejections: [],
  1360. pendingRejectionCheck: false,
  1361. scheduleHandlers: function scheduleHandlers(promise) {
  1362. if (promise._status === STATUS_PENDING) {
  1363. return;
  1364. }
  1365. this.handlers = this.handlers.concat(promise._handlers);
  1366. promise._handlers = [];
  1367. if (this.running) {
  1368. return;
  1369. }
  1370. this.running = true;
  1371. setTimeout(this.runHandlers.bind(this), 0);
  1372. },
  1373. runHandlers: function runHandlers() {
  1374. var RUN_TIMEOUT = 1;
  1375. // ms
  1376. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1377. while (this.handlers.length > 0) {
  1378. var handler = this.handlers.shift();
  1379. var nextStatus = handler.thisPromise._status;
  1380. var nextValue = handler.thisPromise._value;
  1381. try {
  1382. if (nextStatus === STATUS_RESOLVED) {
  1383. if (typeof handler.onResolve === 'function') {
  1384. nextValue = handler.onResolve(nextValue);
  1385. }
  1386. } else if (typeof handler.onReject === 'function') {
  1387. nextValue = handler.onReject(nextValue);
  1388. nextStatus = STATUS_RESOLVED;
  1389. if (handler.thisPromise._unhandledRejection) {
  1390. this.removeUnhandeledRejection(handler.thisPromise);
  1391. }
  1392. }
  1393. } catch (ex) {
  1394. nextStatus = STATUS_REJECTED;
  1395. nextValue = ex;
  1396. }
  1397. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1398. if (Date.now() >= timeoutAt) {
  1399. break;
  1400. }
  1401. }
  1402. if (this.handlers.length > 0) {
  1403. setTimeout(this.runHandlers.bind(this), 0);
  1404. return;
  1405. }
  1406. this.running = false;
  1407. },
  1408. addUnhandledRejection: function addUnhandledRejection(promise) {
  1409. this.unhandledRejections.push({
  1410. promise: promise,
  1411. time: Date.now()
  1412. });
  1413. this.scheduleRejectionCheck();
  1414. },
  1415. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1416. promise._unhandledRejection = false;
  1417. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1418. if (this.unhandledRejections[i].promise === promise) {
  1419. this.unhandledRejections.splice(i);
  1420. i--;
  1421. }
  1422. }
  1423. },
  1424. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1425. if (this.pendingRejectionCheck) {
  1426. return;
  1427. }
  1428. this.pendingRejectionCheck = true;
  1429. setTimeout(function rejectionCheck() {
  1430. this.pendingRejectionCheck = false;
  1431. var now = Date.now();
  1432. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1433. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1434. var unhandled = this.unhandledRejections[i].promise._value;
  1435. var msg = 'Unhandled rejection: ' + unhandled;
  1436. if (unhandled.stack) {
  1437. msg += '\n' + unhandled.stack;
  1438. }
  1439. warn(msg);
  1440. this.unhandledRejections.splice(i);
  1441. i--;
  1442. }
  1443. }
  1444. if (this.unhandledRejections.length) {
  1445. this.scheduleRejectionCheck();
  1446. }
  1447. }.bind(this), REJECTION_TIMEOUT);
  1448. }
  1449. };
  1450. var Promise = function Promise(resolver) {
  1451. this._status = STATUS_PENDING;
  1452. this._handlers = [];
  1453. try {
  1454. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1455. } catch (e) {
  1456. this._reject(e);
  1457. }
  1458. };
  1459. /**
  1460. * Builds a promise that is resolved when all the passed in promises are
  1461. * resolved.
  1462. * @param {array} promises array of data and/or promises to wait for.
  1463. * @return {Promise} New dependent promise.
  1464. */
  1465. Promise.all = function Promise_all(promises) {
  1466. var resolveAll, rejectAll;
  1467. var deferred = new Promise(function (resolve, reject) {
  1468. resolveAll = resolve;
  1469. rejectAll = reject;
  1470. });
  1471. var unresolved = promises.length;
  1472. var results = [];
  1473. if (unresolved === 0) {
  1474. resolveAll(results);
  1475. return deferred;
  1476. }
  1477. function reject(reason) {
  1478. if (deferred._status === STATUS_REJECTED) {
  1479. return;
  1480. }
  1481. results = [];
  1482. rejectAll(reason);
  1483. }
  1484. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1485. var promise = promises[i];
  1486. var resolve = function (i) {
  1487. return function (value) {
  1488. if (deferred._status === STATUS_REJECTED) {
  1489. return;
  1490. }
  1491. results[i] = value;
  1492. unresolved--;
  1493. if (unresolved === 0) {
  1494. resolveAll(results);
  1495. }
  1496. };
  1497. }(i);
  1498. if (Promise.isPromise(promise)) {
  1499. promise.then(resolve, reject);
  1500. } else {
  1501. resolve(promise);
  1502. }
  1503. }
  1504. return deferred;
  1505. };
  1506. /**
  1507. * Checks if the value is likely a promise (has a 'then' function).
  1508. * @return {boolean} true if value is thenable
  1509. */
  1510. Promise.isPromise = function Promise_isPromise(value) {
  1511. return value && typeof value.then === 'function';
  1512. };
  1513. /**
  1514. * Creates resolved promise
  1515. * @param value resolve value
  1516. * @returns {Promise}
  1517. */
  1518. Promise.resolve = function Promise_resolve(value) {
  1519. return new Promise(function (resolve) {
  1520. resolve(value);
  1521. });
  1522. };
  1523. /**
  1524. * Creates rejected promise
  1525. * @param reason rejection value
  1526. * @returns {Promise}
  1527. */
  1528. Promise.reject = function Promise_reject(reason) {
  1529. return new Promise(function (resolve, reject) {
  1530. reject(reason);
  1531. });
  1532. };
  1533. Promise.prototype = {
  1534. _status: null,
  1535. _value: null,
  1536. _handlers: null,
  1537. _unhandledRejection: null,
  1538. _updateStatus: function Promise__updateStatus(status, value) {
  1539. if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) {
  1540. return;
  1541. }
  1542. if (status === STATUS_RESOLVED && Promise.isPromise(value)) {
  1543. value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED));
  1544. return;
  1545. }
  1546. this._status = status;
  1547. this._value = value;
  1548. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1549. this._unhandledRejection = true;
  1550. HandlerManager.addUnhandledRejection(this);
  1551. }
  1552. HandlerManager.scheduleHandlers(this);
  1553. },
  1554. _resolve: function Promise_resolve(value) {
  1555. this._updateStatus(STATUS_RESOLVED, value);
  1556. },
  1557. _reject: function Promise_reject(reason) {
  1558. this._updateStatus(STATUS_REJECTED, reason);
  1559. },
  1560. then: function Promise_then(onResolve, onReject) {
  1561. var nextPromise = new Promise(function (resolve, reject) {
  1562. this.resolve = resolve;
  1563. this.reject = reject;
  1564. });
  1565. this._handlers.push({
  1566. thisPromise: this,
  1567. onResolve: onResolve,
  1568. onReject: onReject,
  1569. nextPromise: nextPromise
  1570. });
  1571. HandlerManager.scheduleHandlers(this);
  1572. return nextPromise;
  1573. },
  1574. catch: function Promise_catch(onReject) {
  1575. return this.then(undefined, onReject);
  1576. }
  1577. };
  1578. globalScope.Promise = Promise;
  1579. }());
  1580. (function WeakMapClosure() {
  1581. if (globalScope.WeakMap) {
  1582. return;
  1583. }
  1584. var id = 0;
  1585. function WeakMap() {
  1586. this.id = '$weakmap' + id++;
  1587. }
  1588. WeakMap.prototype = {
  1589. has: function (obj) {
  1590. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1591. },
  1592. get: function (obj, defaultValue) {
  1593. return this.has(obj) ? obj[this.id] : defaultValue;
  1594. },
  1595. set: function (obj, value) {
  1596. Object.defineProperty(obj, this.id, {
  1597. value: value,
  1598. enumerable: false,
  1599. configurable: true
  1600. });
  1601. },
  1602. delete: function (obj) {
  1603. delete obj[this.id];
  1604. }
  1605. };
  1606. globalScope.WeakMap = WeakMap;
  1607. }());
  1608. var StatTimer = function StatTimerClosure() {
  1609. function rpad(str, pad, length) {
  1610. while (str.length < length) {
  1611. str += pad;
  1612. }
  1613. return str;
  1614. }
  1615. function StatTimer() {
  1616. this.started = Object.create(null);
  1617. this.times = [];
  1618. this.enabled = true;
  1619. }
  1620. StatTimer.prototype = {
  1621. time: function StatTimer_time(name) {
  1622. if (!this.enabled) {
  1623. return;
  1624. }
  1625. if (name in this.started) {
  1626. warn('Timer is already running for ' + name);
  1627. }
  1628. this.started[name] = Date.now();
  1629. },
  1630. timeEnd: function StatTimer_timeEnd(name) {
  1631. if (!this.enabled) {
  1632. return;
  1633. }
  1634. if (!(name in this.started)) {
  1635. warn('Timer has not been started for ' + name);
  1636. }
  1637. this.times.push({
  1638. 'name': name,
  1639. 'start': this.started[name],
  1640. 'end': Date.now()
  1641. });
  1642. // Remove timer from started so it can be called again.
  1643. delete this.started[name];
  1644. },
  1645. toString: function StatTimer_toString() {
  1646. var i, ii;
  1647. var times = this.times;
  1648. var out = '';
  1649. // Find the longest name for padding purposes.
  1650. var longest = 0;
  1651. for (i = 0, ii = times.length; i < ii; ++i) {
  1652. var name = times[i]['name'];
  1653. if (name.length > longest) {
  1654. longest = name.length;
  1655. }
  1656. }
  1657. for (i = 0, ii = times.length; i < ii; ++i) {
  1658. var span = times[i];
  1659. var duration = span.end - span.start;
  1660. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1661. }
  1662. return out;
  1663. }
  1664. };
  1665. return StatTimer;
  1666. }();
  1667. var createBlob = function createBlob(data, contentType) {
  1668. if (typeof Blob !== 'undefined') {
  1669. return new Blob([data], { type: contentType });
  1670. }
  1671. warn('The "Blob" constructor is not supported.');
  1672. };
  1673. var createObjectURL = function createObjectURLClosure() {
  1674. // Blob/createObjectURL is not available, falling back to data schema.
  1675. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1676. return function createObjectURL(data, contentType, forceDataSchema) {
  1677. if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
  1678. var blob = createBlob(data, contentType);
  1679. return URL.createObjectURL(blob);
  1680. }
  1681. var buffer = 'data:' + contentType + ';base64,';
  1682. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1683. var b1 = data[i] & 0xFF;
  1684. var b2 = data[i + 1] & 0xFF;
  1685. var b3 = data[i + 2] & 0xFF;
  1686. var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4;
  1687. var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
  1688. var d4 = i + 2 < ii ? b3 & 0x3F : 64;
  1689. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1690. }
  1691. return buffer;
  1692. };
  1693. }();
  1694. function MessageHandler(sourceName, targetName, comObj) {
  1695. this.sourceName = sourceName;
  1696. this.targetName = targetName;
  1697. this.comObj = comObj;
  1698. this.callbackIndex = 1;
  1699. this.postMessageTransfers = true;
  1700. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1701. var ah = this.actionHandler = Object.create(null);
  1702. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1703. var data = event.data;
  1704. if (data.targetName !== this.sourceName) {
  1705. return;
  1706. }
  1707. if (data.isReply) {
  1708. var callbackId = data.callbackId;
  1709. if (data.callbackId in callbacksCapabilities) {
  1710. var callback = callbacksCapabilities[callbackId];
  1711. delete callbacksCapabilities[callbackId];
  1712. if ('error' in data) {
  1713. callback.reject(data.error);
  1714. } else {
  1715. callback.resolve(data.data);
  1716. }
  1717. } else {
  1718. error('Cannot resolve callback ' + callbackId);
  1719. }
  1720. } else if (data.action in ah) {
  1721. var action = ah[data.action];
  1722. if (data.callbackId) {
  1723. var sourceName = this.sourceName;
  1724. var targetName = data.sourceName;
  1725. Promise.resolve().then(function () {
  1726. return action[0].call(action[1], data.data);
  1727. }).then(function (result) {
  1728. comObj.postMessage({
  1729. sourceName: sourceName,
  1730. targetName: targetName,
  1731. isReply: true,
  1732. callbackId: data.callbackId,
  1733. data: result
  1734. });
  1735. }, function (reason) {
  1736. if (reason instanceof Error) {
  1737. // Serialize error to avoid "DataCloneError"
  1738. reason = reason + '';
  1739. }
  1740. comObj.postMessage({
  1741. sourceName: sourceName,
  1742. targetName: targetName,
  1743. isReply: true,
  1744. callbackId: data.callbackId,
  1745. error: reason
  1746. });
  1747. });
  1748. } else {
  1749. action[0].call(action[1], data.data);
  1750. }
  1751. } else {
  1752. error('Unknown action from worker: ' + data.action);
  1753. }
  1754. }.bind(this);
  1755. comObj.addEventListener('message', this._onComObjOnMessage);
  1756. }
  1757. MessageHandler.prototype = {
  1758. on: function messageHandlerOn(actionName, handler, scope) {
  1759. var ah = this.actionHandler;
  1760. if (ah[actionName]) {
  1761. error('There is already an actionName called "' + actionName + '"');
  1762. }
  1763. ah[actionName] = [
  1764. handler,
  1765. scope
  1766. ];
  1767. },
  1768. /**
  1769. * Sends a message to the comObj to invoke the action with the supplied data.
  1770. * @param {String} actionName Action to call.
  1771. * @param {JSON} data JSON data to send.
  1772. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1773. */
  1774. send: function messageHandlerSend(actionName, data, transfers) {
  1775. var message = {
  1776. sourceName: this.sourceName,
  1777. targetName: this.targetName,
  1778. action: actionName,
  1779. data: data
  1780. };
  1781. this.postMessage(message, transfers);
  1782. },
  1783. /**
  1784. * Sends a message to the comObj to invoke the action with the supplied data.
  1785. * Expects that other side will callback with the response.
  1786. * @param {String} actionName Action to call.
  1787. * @param {JSON} data JSON data to send.
  1788. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1789. * @returns {Promise} Promise to be resolved with response data.
  1790. */
  1791. sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
  1792. var callbackId = this.callbackIndex++;
  1793. var message = {
  1794. sourceName: this.sourceName,
  1795. targetName: this.targetName,
  1796. action: actionName,
  1797. data: data,
  1798. callbackId: callbackId
  1799. };
  1800. var capability = createPromiseCapability();
  1801. this.callbacksCapabilities[callbackId] = capability;
  1802. try {
  1803. this.postMessage(message, transfers);
  1804. } catch (e) {
  1805. capability.reject(e);
  1806. }
  1807. return capability.promise;
  1808. },
  1809. /**
  1810. * Sends raw message to the comObj.
  1811. * @private
  1812. * @param message {Object} Raw message.
  1813. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1814. */
  1815. postMessage: function (message, transfers) {
  1816. if (transfers && this.postMessageTransfers) {
  1817. this.comObj.postMessage(message, transfers);
  1818. } else {
  1819. this.comObj.postMessage(message);
  1820. }
  1821. },
  1822. destroy: function () {
  1823. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1824. }
  1825. };
  1826. function loadJpegStream(id, imageUrl, objs) {
  1827. var img = new Image();
  1828. img.onload = function loadJpegStream_onloadClosure() {
  1829. objs.resolve(id, img);
  1830. };
  1831. img.onerror = function loadJpegStream_onerrorClosure() {
  1832. objs.resolve(id, null);
  1833. warn('Error during JPEG image loading');
  1834. };
  1835. img.src = imageUrl;
  1836. }
  1837. // Polyfill from https://github.com/Polymer/URL
  1838. /* Any copyright is dedicated to the Public Domain.
  1839. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1840. (function checkURLConstructor(scope) {
  1841. // feature detect for URL constructor
  1842. var hasWorkingUrl = false;
  1843. try {
  1844. if (typeof URL === 'function' && typeof URL.prototype === 'object' && 'origin' in URL.prototype) {
  1845. var u = new URL('b', 'http://a');
  1846. u.pathname = 'c%20d';
  1847. hasWorkingUrl = u.href === 'http://a/c%20d';
  1848. }
  1849. } catch (e) {
  1850. }
  1851. if (hasWorkingUrl) {
  1852. return;
  1853. }
  1854. var relative = Object.create(null);
  1855. relative['ftp'] = 21;
  1856. relative['file'] = 0;
  1857. relative['gopher'] = 70;
  1858. relative['http'] = 80;
  1859. relative['https'] = 443;
  1860. relative['ws'] = 80;
  1861. relative['wss'] = 443;
  1862. var relativePathDotMapping = Object.create(null);
  1863. relativePathDotMapping['%2e'] = '.';
  1864. relativePathDotMapping['.%2e'] = '..';
  1865. relativePathDotMapping['%2e.'] = '..';
  1866. relativePathDotMapping['%2e%2e'] = '..';
  1867. function isRelativeScheme(scheme) {
  1868. return relative[scheme] !== undefined;
  1869. }
  1870. function invalid() {
  1871. clear.call(this);
  1872. this._isInvalid = true;
  1873. }
  1874. function IDNAToASCII(h) {
  1875. if ('' === h) {
  1876. invalid.call(this);
  1877. }
  1878. // XXX
  1879. return h.toLowerCase();
  1880. }
  1881. function percentEscape(c) {
  1882. var unicode = c.charCodeAt(0);
  1883. if (unicode > 0x20 && unicode < 0x7F && // " # < > ? `
  1884. [
  1885. 0x22,
  1886. 0x23,
  1887. 0x3C,
  1888. 0x3E,
  1889. 0x3F,
  1890. 0x60
  1891. ].indexOf(unicode) === -1) {
  1892. return c;
  1893. }
  1894. return encodeURIComponent(c);
  1895. }
  1896. function percentEscapeQuery(c) {
  1897. // XXX This actually needs to encode c using encoding and then
  1898. // convert the bytes one-by-one.
  1899. var unicode = c.charCodeAt(0);
  1900. if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?')
  1901. [
  1902. 0x22,
  1903. 0x23,
  1904. 0x3C,
  1905. 0x3E,
  1906. 0x60
  1907. ].indexOf(unicode) === -1) {
  1908. return c;
  1909. }
  1910. return encodeURIComponent(c);
  1911. }
  1912. var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1913. function parse(input, stateOverride, base) {
  1914. function err(message) {
  1915. errors.push(message);
  1916. }
  1917. var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = [];
  1918. loop:
  1919. while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
  1920. var c = input[cursor];
  1921. switch (state) {
  1922. case 'scheme start':
  1923. if (c && ALPHA.test(c)) {
  1924. buffer += c.toLowerCase();
  1925. // ASCII-safe
  1926. state = 'scheme';
  1927. } else if (!stateOverride) {
  1928. buffer = '';
  1929. state = 'no scheme';
  1930. continue;
  1931. } else {
  1932. err('Invalid scheme.');
  1933. break loop;
  1934. }
  1935. break;
  1936. case 'scheme':
  1937. if (c && ALPHANUMERIC.test(c)) {
  1938. buffer += c.toLowerCase();
  1939. } else // ASCII-safe
  1940. if (':' === c) {
  1941. this._scheme = buffer;
  1942. buffer = '';
  1943. if (stateOverride) {
  1944. break loop;
  1945. }
  1946. if (isRelativeScheme(this._scheme)) {
  1947. this._isRelative = true;
  1948. }
  1949. if ('file' === this._scheme) {
  1950. state = 'relative';
  1951. } else if (this._isRelative && base && base._scheme === this._scheme) {
  1952. state = 'relative or authority';
  1953. } else if (this._isRelative) {
  1954. state = 'authority first slash';
  1955. } else {
  1956. state = 'scheme data';
  1957. }
  1958. } else if (!stateOverride) {
  1959. buffer = '';
  1960. cursor = 0;
  1961. state = 'no scheme';
  1962. continue;
  1963. } else if (EOF === c) {
  1964. break loop;
  1965. } else {
  1966. err('Code point not allowed in scheme: ' + c);
  1967. break loop;
  1968. }
  1969. break;
  1970. case 'scheme data':
  1971. if ('?' === c) {
  1972. this._query = '?';
  1973. state = 'query';
  1974. } else if ('#' === c) {
  1975. this._fragment = '#';
  1976. state = 'fragment';
  1977. } else {
  1978. // XXX error handling
  1979. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1980. this._schemeData += percentEscape(c);
  1981. }
  1982. }
  1983. break;
  1984. case 'no scheme':
  1985. if (!base || !isRelativeScheme(base._scheme)) {
  1986. err('Missing scheme.');
  1987. invalid.call(this);
  1988. } else {
  1989. state = 'relative';
  1990. continue;
  1991. }
  1992. break;
  1993. case 'relative or authority':
  1994. if ('/' === c && '/' === input[cursor + 1]) {
  1995. state = 'authority ignore slashes';
  1996. } else {
  1997. err('Expected /, got: ' + c);
  1998. state = 'relative';
  1999. continue;
  2000. }
  2001. break;
  2002. case 'relative':
  2003. this._isRelative = true;
  2004. if ('file' !== this._scheme) {
  2005. this._scheme = base._scheme;
  2006. }
  2007. if (EOF === c) {
  2008. this._host = base._host;
  2009. this._port = base._port;
  2010. this._path = base._path.slice();
  2011. this._query = base._query;
  2012. this._username = base._username;
  2013. this._password = base._password;
  2014. break loop;
  2015. } else if ('/' === c || '\\' === c) {
  2016. if ('\\' === c) {
  2017. err('\\ is an invalid code point.');
  2018. }
  2019. state = 'relative slash';
  2020. } else if ('?' === c) {
  2021. this._host = base._host;
  2022. this._port = base._port;
  2023. this._path = base._path.slice();
  2024. this._query = '?';
  2025. this._username = base._username;
  2026. this._password = base._password;
  2027. state = 'query';
  2028. } else if ('#' === c) {
  2029. this._host = base._host;
  2030. this._port = base._port;
  2031. this._path = base._path.slice();
  2032. this._query = base._query;
  2033. this._fragment = '#';
  2034. this._username = base._username;
  2035. this._password = base._password;
  2036. state = 'fragment';
  2037. } else {
  2038. var nextC = input[cursor + 1];
  2039. var nextNextC = input[cursor + 2];
  2040. if ('file' !== this._scheme || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC) {
  2041. this._host = base._host;
  2042. this._port = base._port;
  2043. this._username = base._username;
  2044. this._password = base._password;
  2045. this._path = base._path.slice();
  2046. this._path.pop();
  2047. }
  2048. state = 'relative path';
  2049. continue;
  2050. }
  2051. break;
  2052. case 'relative slash':
  2053. if ('/' === c || '\\' === c) {
  2054. if ('\\' === c) {
  2055. err('\\ is an invalid code point.');
  2056. }
  2057. if ('file' === this._scheme) {
  2058. state = 'file host';
  2059. } else {
  2060. state = 'authority ignore slashes';
  2061. }
  2062. } else {
  2063. if ('file' !== this._scheme) {
  2064. this._host = base._host;
  2065. this._port = base._port;
  2066. this._username = base._username;
  2067. this._password = base._password;
  2068. }
  2069. state = 'relative path';
  2070. continue;
  2071. }
  2072. break;
  2073. case 'authority first slash':
  2074. if ('/' === c) {
  2075. state = 'authority second slash';
  2076. } else {
  2077. err('Expected \'/\', got: ' + c);
  2078. state = 'authority ignore slashes';
  2079. continue;
  2080. }
  2081. break;
  2082. case 'authority second slash':
  2083. state = 'authority ignore slashes';
  2084. if ('/' !== c) {
  2085. err('Expected \'/\', got: ' + c);
  2086. continue;
  2087. }
  2088. break;
  2089. case 'authority ignore slashes':
  2090. if ('/' !== c && '\\' !== c) {
  2091. state = 'authority';
  2092. continue;
  2093. } else {
  2094. err('Expected authority, got: ' + c);
  2095. }
  2096. break;
  2097. case 'authority':
  2098. if ('@' === c) {
  2099. if (seenAt) {
  2100. err('@ already seen.');
  2101. buffer += '%40';
  2102. }
  2103. seenAt = true;
  2104. for (var i = 0; i < buffer.length; i++) {
  2105. var cp = buffer[i];
  2106. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  2107. err('Invalid whitespace in authority.');
  2108. continue;
  2109. }
  2110. // XXX check URL code points
  2111. if (':' === cp && null === this._password) {
  2112. this._password = '';
  2113. continue;
  2114. }
  2115. var tempC = percentEscape(cp);
  2116. if (null !== this._password) {
  2117. this._password += tempC;
  2118. } else {
  2119. this._username += tempC;
  2120. }
  2121. }
  2122. buffer = '';
  2123. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2124. cursor -= buffer.length;
  2125. buffer = '';
  2126. state = 'host';
  2127. continue;
  2128. } else {
  2129. buffer += c;
  2130. }
  2131. break;
  2132. case 'file host':
  2133. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2134. if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
  2135. state = 'relative path';
  2136. } else if (buffer.length === 0) {
  2137. state = 'relative path start';
  2138. } else {
  2139. this._host = IDNAToASCII.call(this, buffer);
  2140. buffer = '';
  2141. state = 'relative path start';
  2142. }
  2143. continue;
  2144. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2145. err('Invalid whitespace in file host.');
  2146. } else {
  2147. buffer += c;
  2148. }
  2149. break;
  2150. case 'host':
  2151. case 'hostname':
  2152. if (':' === c && !seenBracket) {
  2153. // XXX host parsing
  2154. this._host = IDNAToASCII.call(this, buffer);
  2155. buffer = '';
  2156. state = 'port';
  2157. if ('hostname' === stateOverride) {
  2158. break loop;
  2159. }
  2160. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2161. this._host = IDNAToASCII.call(this, buffer);
  2162. buffer = '';
  2163. state = 'relative path start';
  2164. if (stateOverride) {
  2165. break loop;
  2166. }
  2167. continue;
  2168. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2169. if ('[' === c) {
  2170. seenBracket = true;
  2171. } else if (']' === c) {
  2172. seenBracket = false;
  2173. }
  2174. buffer += c;
  2175. } else {
  2176. err('Invalid code point in host/hostname: ' + c);
  2177. }
  2178. break;
  2179. case 'port':
  2180. if (/[0-9]/.test(c)) {
  2181. buffer += c;
  2182. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) {
  2183. if ('' !== buffer) {
  2184. var temp = parseInt(buffer, 10);
  2185. if (temp !== relative[this._scheme]) {
  2186. this._port = temp + '';
  2187. }
  2188. buffer = '';
  2189. }
  2190. if (stateOverride) {
  2191. break loop;
  2192. }
  2193. state = 'relative path start';
  2194. continue;
  2195. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2196. err('Invalid code point in port: ' + c);
  2197. } else {
  2198. invalid.call(this);
  2199. }
  2200. break;
  2201. case 'relative path start':
  2202. if ('\\' === c) {
  2203. err('\'\\\' not allowed in path.');
  2204. }
  2205. state = 'relative path';
  2206. if ('/' !== c && '\\' !== c) {
  2207. continue;
  2208. }
  2209. break;
  2210. case 'relative path':
  2211. if (EOF === c || '/' === c || '\\' === c || !stateOverride && ('?' === c || '#' === c)) {
  2212. if ('\\' === c) {
  2213. err('\\ not allowed in relative path.');
  2214. }
  2215. var tmp;
  2216. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  2217. buffer = tmp;
  2218. }
  2219. if ('..' === buffer) {
  2220. this._path.pop();
  2221. if ('/' !== c && '\\' !== c) {
  2222. this._path.push('');
  2223. }
  2224. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  2225. this._path.push('');
  2226. } else if ('.' !== buffer) {
  2227. if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
  2228. buffer = buffer[0] + ':';
  2229. }
  2230. this._path.push(buffer);
  2231. }
  2232. buffer = '';
  2233. if ('?' === c) {
  2234. this._query = '?';
  2235. state = 'query';
  2236. } else if ('#' === c) {
  2237. this._fragment = '#';
  2238. state = 'fragment';
  2239. }
  2240. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2241. buffer += percentEscape(c);
  2242. }
  2243. break;
  2244. case 'query':
  2245. if (!stateOverride && '#' === c) {
  2246. this._fragment = '#';
  2247. state = 'fragment';
  2248. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2249. this._query += percentEscapeQuery(c);
  2250. }
  2251. break;
  2252. case 'fragment':
  2253. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2254. this._fragment += c;
  2255. }
  2256. break;
  2257. }
  2258. cursor++;
  2259. }
  2260. }
  2261. function clear() {
  2262. this._scheme = '';
  2263. this._schemeData = '';
  2264. this._username = '';
  2265. this._password = null;
  2266. this._host = '';
  2267. this._port = '';
  2268. this._path = [];
  2269. this._query = '';
  2270. this._fragment = '';
  2271. this._isInvalid = false;
  2272. this._isRelative = false;
  2273. }
  2274. // Does not process domain names or IP addresses.
  2275. // Does not handle encoding for the query parameter.
  2276. function JURL(url, base)
  2277. /* , encoding */
  2278. {
  2279. if (base !== undefined && !(base instanceof JURL)) {
  2280. base = new JURL(String(base));
  2281. }
  2282. this._url = url;
  2283. clear.call(this);
  2284. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2285. // encoding = encoding || 'utf-8'
  2286. parse.call(this, input, null, base);
  2287. }
  2288. JURL.prototype = {
  2289. toString: function () {
  2290. return this.href;
  2291. },
  2292. get href() {
  2293. if (this._isInvalid) {
  2294. return this._url;
  2295. }
  2296. var authority = '';
  2297. if ('' !== this._username || null !== this._password) {
  2298. authority = this._username + (null !== this._password ? ':' + this._password : '') + '@';
  2299. }
  2300. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  2301. },
  2302. set href(href) {
  2303. clear.call(this);
  2304. parse.call(this, href);
  2305. },
  2306. get protocol() {
  2307. return this._scheme + ':';
  2308. },
  2309. set protocol(protocol) {
  2310. if (this._isInvalid) {
  2311. return;
  2312. }
  2313. parse.call(this, protocol + ':', 'scheme start');
  2314. },
  2315. get host() {
  2316. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  2317. },
  2318. set host(host) {
  2319. if (this._isInvalid || !this._isRelative) {
  2320. return;
  2321. }
  2322. parse.call(this, host, 'host');
  2323. },
  2324. get hostname() {
  2325. return this._host;
  2326. },
  2327. set hostname(hostname) {
  2328. if (this._isInvalid || !this._isRelative) {
  2329. return;
  2330. }
  2331. parse.call(this, hostname, 'hostname');
  2332. },
  2333. get port() {
  2334. return this._port;
  2335. },
  2336. set port(port) {
  2337. if (this._isInvalid || !this._isRelative) {
  2338. return;
  2339. }
  2340. parse.call(this, port, 'port');
  2341. },
  2342. get pathname() {
  2343. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  2344. },
  2345. set pathname(pathname) {
  2346. if (this._isInvalid || !this._isRelative) {
  2347. return;
  2348. }
  2349. this._path = [];
  2350. parse.call(this, pathname, 'relative path start');
  2351. },
  2352. get search() {
  2353. return this._isInvalid || !this._query || '?' === this._query ? '' : this._query;
  2354. },
  2355. set search(search) {
  2356. if (this._isInvalid || !this._isRelative) {
  2357. return;
  2358. }
  2359. this._query = '?';
  2360. if ('?' === search[0]) {
  2361. search = search.slice(1);
  2362. }
  2363. parse.call(this, search, 'query');
  2364. },
  2365. get hash() {
  2366. return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment;
  2367. },
  2368. set hash(hash) {
  2369. if (this._isInvalid) {
  2370. return;
  2371. }
  2372. this._fragment = '#';
  2373. if ('#' === hash[0]) {
  2374. hash = hash.slice(1);
  2375. }
  2376. parse.call(this, hash, 'fragment');
  2377. },
  2378. get origin() {
  2379. var host;
  2380. if (this._isInvalid || !this._scheme) {
  2381. return '';
  2382. }
  2383. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2384. // Gecko throws error for "data://"
  2385. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2386. // Gecko returns String("") for file: mailto:
  2387. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2388. switch (this._scheme) {
  2389. case 'data':
  2390. case 'file':
  2391. case 'javascript':
  2392. case 'mailto':
  2393. return 'null';
  2394. }
  2395. host = this.host;
  2396. if (!host) {
  2397. return '';
  2398. }
  2399. return this._scheme + '://' + host;
  2400. }
  2401. };
  2402. // Copy over the static methods
  2403. var OriginalURL = scope.URL;
  2404. if (OriginalURL) {
  2405. JURL.createObjectURL = function (blob) {
  2406. // IE extension allows a second optional options argument.
  2407. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2408. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2409. };
  2410. JURL.revokeObjectURL = function (url) {
  2411. OriginalURL.revokeObjectURL(url);
  2412. };
  2413. }
  2414. scope.URL = JURL;
  2415. }(globalScope));
  2416. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2417. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2418. exports.OPS = OPS;
  2419. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2420. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2421. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2422. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2423. exports.AnnotationFlag = AnnotationFlag;
  2424. exports.AnnotationType = AnnotationType;
  2425. exports.FontType = FontType;
  2426. exports.ImageKind = ImageKind;
  2427. exports.InvalidPDFException = InvalidPDFException;
  2428. exports.MessageHandler = MessageHandler;
  2429. exports.MissingDataException = MissingDataException;
  2430. exports.MissingPDFException = MissingPDFException;
  2431. exports.NotImplementedException = NotImplementedException;
  2432. exports.PageViewport = PageViewport;
  2433. exports.PasswordException = PasswordException;
  2434. exports.PasswordResponses = PasswordResponses;
  2435. exports.StatTimer = StatTimer;
  2436. exports.StreamType = StreamType;
  2437. exports.TextRenderingMode = TextRenderingMode;
  2438. exports.UnexpectedResponseException = UnexpectedResponseException;
  2439. exports.UnknownErrorException = UnknownErrorException;
  2440. exports.Util = Util;
  2441. exports.XRefParseException = XRefParseException;
  2442. exports.arrayByteLength = arrayByteLength;
  2443. exports.arraysToBytes = arraysToBytes;
  2444. exports.assert = assert;
  2445. exports.bytesToString = bytesToString;
  2446. exports.createBlob = createBlob;
  2447. exports.createPromiseCapability = createPromiseCapability;
  2448. exports.createObjectURL = createObjectURL;
  2449. exports.deprecated = deprecated;
  2450. exports.error = error;
  2451. exports.getLookupTableFactory = getLookupTableFactory;
  2452. exports.getVerbosityLevel = getVerbosityLevel;
  2453. exports.globalScope = globalScope;
  2454. exports.info = info;
  2455. exports.isArray = isArray;
  2456. exports.isArrayBuffer = isArrayBuffer;
  2457. exports.isBool = isBool;
  2458. exports.isEmptyObj = isEmptyObj;
  2459. exports.isInt = isInt;
  2460. exports.isNum = isNum;
  2461. exports.isString = isString;
  2462. exports.isSpace = isSpace;
  2463. exports.isSameOrigin = isSameOrigin;
  2464. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  2465. exports.isLittleEndian = isLittleEndian;
  2466. exports.isEvalSupported = isEvalSupported;
  2467. exports.loadJpegStream = loadJpegStream;
  2468. exports.log2 = log2;
  2469. exports.readInt8 = readInt8;
  2470. exports.readUint16 = readUint16;
  2471. exports.readUint32 = readUint32;
  2472. exports.removeNullCharacters = removeNullCharacters;
  2473. exports.setVerbosityLevel = setVerbosityLevel;
  2474. exports.shadow = shadow;
  2475. exports.string32 = string32;
  2476. exports.stringToBytes = stringToBytes;
  2477. exports.stringToPDFString = stringToPDFString;
  2478. exports.stringToUTF8String = stringToUTF8String;
  2479. exports.utf8StringToString = utf8StringToString;
  2480. exports.warn = warn;
  2481. }));
  2482. (function (root, factory) {
  2483. factory(root.pdfjsDisplayDOMUtils = {}, root.pdfjsSharedUtil);
  2484. }(this, function (exports, sharedUtil) {
  2485. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2486. var warn = sharedUtil.warn;
  2487. var deprecated = sharedUtil.deprecated;
  2488. var createValidAbsoluteUrl = sharedUtil.createValidAbsoluteUrl;
  2489. /**
  2490. * Optimised CSS custom property getter/setter.
  2491. * @class
  2492. */
  2493. var CustomStyle = function CustomStyleClosure() {
  2494. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2495. // animate-css-transforms-firefox-webkit.html
  2496. // in some versions of IE9 it is critical that ms appear in this list
  2497. // before Moz
  2498. var prefixes = [
  2499. 'ms',
  2500. 'Moz',
  2501. 'Webkit',
  2502. 'O'
  2503. ];
  2504. var _cache = Object.create(null);
  2505. function CustomStyle() {
  2506. }
  2507. CustomStyle.getProp = function get(propName, element) {
  2508. // check cache only when no element is given
  2509. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2510. return _cache[propName];
  2511. }
  2512. element = element || document.documentElement;
  2513. var style = element.style, prefixed, uPropName;
  2514. // test standard property first
  2515. if (typeof style[propName] === 'string') {
  2516. return _cache[propName] = propName;
  2517. }
  2518. // capitalize
  2519. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2520. // test vendor specific properties
  2521. for (var i = 0, l = prefixes.length; i < l; i++) {
  2522. prefixed = prefixes[i] + uPropName;
  2523. if (typeof style[prefixed] === 'string') {
  2524. return _cache[propName] = prefixed;
  2525. }
  2526. }
  2527. //if all fails then set to undefined
  2528. return _cache[propName] = 'undefined';
  2529. };
  2530. CustomStyle.setProp = function set(propName, element, str) {
  2531. var prop = this.getProp(propName);
  2532. if (prop !== 'undefined') {
  2533. element.style[prop] = str;
  2534. }
  2535. };
  2536. return CustomStyle;
  2537. }();
  2538. var hasCanvasTypedArrays;
  2539. hasCanvasTypedArrays = function hasCanvasTypedArrays() {
  2540. var canvas = document.createElement('canvas');
  2541. canvas.width = canvas.height = 1;
  2542. var ctx = canvas.getContext('2d');
  2543. var imageData = ctx.createImageData(1, 1);
  2544. return typeof imageData.data.buffer !== 'undefined';
  2545. };
  2546. var LinkTarget = {
  2547. NONE: 0,
  2548. // Default value.
  2549. SELF: 1,
  2550. BLANK: 2,
  2551. PARENT: 3,
  2552. TOP: 4
  2553. };
  2554. var LinkTargetStringMap = [
  2555. '',
  2556. '_self',
  2557. '_blank',
  2558. '_parent',
  2559. '_top'
  2560. ];
  2561. /**
  2562. * @typedef ExternalLinkParameters
  2563. * @typedef {Object} ExternalLinkParameters
  2564. * @property {string} url - An absolute URL.
  2565. * @property {LinkTarget} target - The link target.
  2566. * @property {string} rel - The link relationship.
  2567. */
  2568. /**
  2569. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2570. * @param {HTMLLinkElement} link - The link element.
  2571. * @param {ExternalLinkParameters} params
  2572. */
  2573. function addLinkAttributes(link, params) {
  2574. var url = params && params.url;
  2575. link.href = link.title = url ? removeNullCharacters(url) : '';
  2576. if (url) {
  2577. var target = params.target;
  2578. if (typeof target === 'undefined') {
  2579. target = getDefaultSetting('externalLinkTarget');
  2580. }
  2581. link.target = LinkTargetStringMap[target];
  2582. var rel = params.rel;
  2583. if (typeof rel === 'undefined') {
  2584. rel = getDefaultSetting('externalLinkRel');
  2585. }
  2586. link.rel = rel;
  2587. }
  2588. }
  2589. // Gets the file name from a given URL.
  2590. function getFilenameFromUrl(url) {
  2591. var anchor = url.indexOf('#');
  2592. var query = url.indexOf('?');
  2593. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  2594. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2595. }
  2596. function getDefaultSetting(id) {
  2597. // The list of the settings and their default is maintained for backward
  2598. // compatibility and shall not be extended or modified. See also global.js.
  2599. var globalSettings = sharedUtil.globalScope.PDFJS;
  2600. switch (id) {
  2601. case 'pdfBug':
  2602. return globalSettings ? globalSettings.pdfBug : false;
  2603. case 'disableAutoFetch':
  2604. return globalSettings ? globalSettings.disableAutoFetch : false;
  2605. case 'disableStream':
  2606. return globalSettings ? globalSettings.disableStream : false;
  2607. case 'disableRange':
  2608. return globalSettings ? globalSettings.disableRange : false;
  2609. case 'disableFontFace':
  2610. return globalSettings ? globalSettings.disableFontFace : false;
  2611. case 'disableCreateObjectURL':
  2612. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2613. case 'disableWebGL':
  2614. return globalSettings ? globalSettings.disableWebGL : true;
  2615. case 'cMapUrl':
  2616. return globalSettings ? globalSettings.cMapUrl : null;
  2617. case 'cMapPacked':
  2618. return globalSettings ? globalSettings.cMapPacked : false;
  2619. case 'postMessageTransfers':
  2620. return globalSettings ? globalSettings.postMessageTransfers : true;
  2621. case 'workerSrc':
  2622. return globalSettings ? globalSettings.workerSrc : null;
  2623. case 'disableWorker':
  2624. return globalSettings ? globalSettings.disableWorker : false;
  2625. case 'maxImageSize':
  2626. return globalSettings ? globalSettings.maxImageSize : -1;
  2627. case 'imageResourcesPath':
  2628. return globalSettings ? globalSettings.imageResourcesPath : '';
  2629. case 'isEvalSupported':
  2630. return globalSettings ? globalSettings.isEvalSupported : true;
  2631. case 'externalLinkTarget':
  2632. if (!globalSettings) {
  2633. return LinkTarget.NONE;
  2634. }
  2635. switch (globalSettings.externalLinkTarget) {
  2636. case LinkTarget.NONE:
  2637. case LinkTarget.SELF:
  2638. case LinkTarget.BLANK:
  2639. case LinkTarget.PARENT:
  2640. case LinkTarget.TOP:
  2641. return globalSettings.externalLinkTarget;
  2642. }
  2643. warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  2644. // Reset the external link target, to suppress further warnings.
  2645. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2646. return LinkTarget.NONE;
  2647. case 'externalLinkRel':
  2648. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2649. case 'enableStats':
  2650. return !!(globalSettings && globalSettings.enableStats);
  2651. default:
  2652. throw new Error('Unknown default setting: ' + id);
  2653. }
  2654. }
  2655. function isExternalLinkTargetSet() {
  2656. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2657. switch (externalLinkTarget) {
  2658. case LinkTarget.NONE:
  2659. return false;
  2660. case LinkTarget.SELF:
  2661. case LinkTarget.BLANK:
  2662. case LinkTarget.PARENT:
  2663. case LinkTarget.TOP:
  2664. return true;
  2665. }
  2666. }
  2667. function isValidUrl(url, allowRelative) {
  2668. deprecated('isValidUrl(), please use createValidAbsoluteUrl() instead.');
  2669. var baseUrl = allowRelative ? 'http://example.com' : null;
  2670. return createValidAbsoluteUrl(url, baseUrl) !== null;
  2671. }
  2672. exports.CustomStyle = CustomStyle;
  2673. exports.addLinkAttributes = addLinkAttributes;
  2674. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2675. exports.isValidUrl = isValidUrl;
  2676. exports.getFilenameFromUrl = getFilenameFromUrl;
  2677. exports.LinkTarget = LinkTarget;
  2678. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2679. exports.getDefaultSetting = getDefaultSetting;
  2680. }));
  2681. (function (root, factory) {
  2682. factory(root.pdfjsDisplayFontLoader = {}, root.pdfjsSharedUtil);
  2683. }(this, function (exports, sharedUtil) {
  2684. var assert = sharedUtil.assert;
  2685. var bytesToString = sharedUtil.bytesToString;
  2686. var string32 = sharedUtil.string32;
  2687. var shadow = sharedUtil.shadow;
  2688. var warn = sharedUtil.warn;
  2689. function FontLoader(docId) {
  2690. this.docId = docId;
  2691. this.styleElement = null;
  2692. this.nativeFontFaces = [];
  2693. this.loadTestFontId = 0;
  2694. this.loadingContext = {
  2695. requests: [],
  2696. nextRequestId: 0
  2697. };
  2698. }
  2699. FontLoader.prototype = {
  2700. insertRule: function fontLoaderInsertRule(rule) {
  2701. var styleElement = this.styleElement;
  2702. if (!styleElement) {
  2703. styleElement = this.styleElement = document.createElement('style');
  2704. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2705. document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
  2706. }
  2707. var styleSheet = styleElement.sheet;
  2708. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2709. },
  2710. clear: function fontLoaderClear() {
  2711. var styleElement = this.styleElement;
  2712. if (styleElement) {
  2713. styleElement.parentNode.removeChild(styleElement);
  2714. styleElement = this.styleElement = null;
  2715. }
  2716. this.nativeFontFaces.forEach(function (nativeFontFace) {
  2717. document.fonts.delete(nativeFontFace);
  2718. });
  2719. this.nativeFontFaces.length = 0;
  2720. }
  2721. };
  2722. var getLoadTestFont = function () {
  2723. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2724. // height.
  2725. return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==');
  2726. };
  2727. Object.defineProperty(FontLoader.prototype, 'loadTestFont', {
  2728. get: function () {
  2729. return shadow(this, 'loadTestFont', getLoadTestFont());
  2730. },
  2731. configurable: true
  2732. });
  2733. FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) {
  2734. this.nativeFontFaces.push(nativeFontFace);
  2735. document.fonts.add(nativeFontFace);
  2736. };
  2737. FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) {
  2738. var rules = [];
  2739. var fontsToLoad = [];
  2740. var fontLoadPromises = [];
  2741. var getNativeFontPromise = function (nativeFontFace) {
  2742. // Return a promise that is always fulfilled, even when the font fails to
  2743. // load.
  2744. return nativeFontFace.loaded.catch(function (e) {
  2745. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2746. });
  2747. };
  2748. // Firefox Font Loading API does not work with mozPrintCallback --
  2749. // disabling it in this case.
  2750. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported;
  2751. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2752. var font = fonts[i];
  2753. // Add the font to the DOM only once or skip if the font
  2754. // is already loaded.
  2755. if (font.attached || font.loading === false) {
  2756. continue;
  2757. }
  2758. font.attached = true;
  2759. if (isFontLoadingAPISupported) {
  2760. var nativeFontFace = font.createNativeFontFace();
  2761. if (nativeFontFace) {
  2762. this.addNativeFontFace(nativeFontFace);
  2763. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2764. }
  2765. } else {
  2766. var rule = font.createFontFaceRule();
  2767. if (rule) {
  2768. this.insertRule(rule);
  2769. rules.push(rule);
  2770. fontsToLoad.push(font);
  2771. }
  2772. }
  2773. }
  2774. var request = this.queueLoadingCallback(callback);
  2775. if (isFontLoadingAPISupported) {
  2776. Promise.all(fontLoadPromises).then(function () {
  2777. request.complete();
  2778. });
  2779. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2780. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2781. } else {
  2782. request.complete();
  2783. }
  2784. };
  2785. FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) {
  2786. function LoadLoader_completeRequest() {
  2787. assert(!request.end, 'completeRequest() cannot be called twice');
  2788. request.end = Date.now();
  2789. // sending all completed requests in order how they were queued
  2790. while (context.requests.length > 0 && context.requests[0].end) {
  2791. var otherRequest = context.requests.shift();
  2792. setTimeout(otherRequest.callback, 0);
  2793. }
  2794. }
  2795. var context = this.loadingContext;
  2796. var requestId = 'pdfjs-font-loading-' + context.nextRequestId++;
  2797. var request = {
  2798. id: requestId,
  2799. complete: LoadLoader_completeRequest,
  2800. callback: callback,
  2801. started: Date.now()
  2802. };
  2803. context.requests.push(request);
  2804. return request;
  2805. };
  2806. FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) {
  2807. /** Hack begin */
  2808. // There's currently no event when a font has finished downloading so the
  2809. // following code is a dirty hack to 'guess' when a font is
  2810. // ready. It's assumed fonts are loaded in order, so add a known test
  2811. // font after the desired fonts and then test for the loading of that
  2812. // test font.
  2813. function int32(data, offset) {
  2814. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  2815. }
  2816. function spliceString(s, offset, remove, insert) {
  2817. var chunk1 = s.substr(0, offset);
  2818. var chunk2 = s.substr(offset + remove);
  2819. return chunk1 + insert + chunk2;
  2820. }
  2821. var i, ii;
  2822. var canvas = document.createElement('canvas');
  2823. canvas.width = 1;
  2824. canvas.height = 1;
  2825. var ctx = canvas.getContext('2d');
  2826. var called = 0;
  2827. function isFontReady(name, callback) {
  2828. called++;
  2829. // With setTimeout clamping this gives the font ~100ms to load.
  2830. if (called > 30) {
  2831. warn('Load test font never loaded.');
  2832. callback();
  2833. return;
  2834. }
  2835. ctx.font = '30px ' + name;
  2836. ctx.fillText('.', 0, 20);
  2837. var imageData = ctx.getImageData(0, 0, 1, 1);
  2838. if (imageData.data[3] > 0) {
  2839. callback();
  2840. return;
  2841. }
  2842. setTimeout(isFontReady.bind(null, name, callback));
  2843. }
  2844. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2845. // Chromium seems to cache fonts based on a hash of the actual font data,
  2846. // so the font must be modified for each load test else it will appear to
  2847. // be loaded already.
  2848. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2849. // font by splitting it in chunks before hand and padding the font id.
  2850. var data = this.loadTestFont;
  2851. var COMMENT_OFFSET = 976;
  2852. // has to be on 4 byte boundary (for checksum)
  2853. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  2854. // CFF checksum is important for IE, adjusting it
  2855. var CFF_CHECKSUM_OFFSET = 16;
  2856. var XXXX_VALUE = 0x58585858;
  2857. // the "comment" filled with 'X'
  2858. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2859. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2860. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  2861. }
  2862. if (i < loadTestFontId.length) {
  2863. // align to 4 bytes boundary
  2864. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
  2865. }
  2866. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2867. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2868. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}';
  2869. this.insertRule(rule);
  2870. var names = [];
  2871. for (i = 0, ii = fonts.length; i < ii; i++) {
  2872. names.push(fonts[i].loadedName);
  2873. }
  2874. names.push(loadTestFontId);
  2875. var div = document.createElement('div');
  2876. div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
  2877. for (i = 0, ii = names.length; i < ii; ++i) {
  2878. var span = document.createElement('span');
  2879. span.textContent = 'Hi';
  2880. span.style.fontFamily = names[i];
  2881. div.appendChild(span);
  2882. }
  2883. document.body.appendChild(div);
  2884. isFontReady(loadTestFontId, function () {
  2885. document.body.removeChild(div);
  2886. request.complete();
  2887. });
  2888. };
  2889. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts;
  2890. var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() {
  2891. if (typeof navigator === 'undefined') {
  2892. // node.js - we can pretend sync font loading is supported.
  2893. return true;
  2894. }
  2895. var supported = false;
  2896. // User agent string sniffing is bad, but there is no reliable way to tell
  2897. // if font is fully loaded and ready to be used with canvas.
  2898. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2899. if (m && m[1] >= 14) {
  2900. supported = true;
  2901. }
  2902. // TODO other browsers
  2903. return supported;
  2904. };
  2905. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2906. get: function () {
  2907. return shadow(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported());
  2908. },
  2909. enumerable: true,
  2910. configurable: true
  2911. });
  2912. var IsEvalSupportedCached = {
  2913. get value() {
  2914. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2915. }
  2916. };
  2917. var FontFaceObject = function FontFaceObjectClosure() {
  2918. function FontFaceObject(translatedData, options) {
  2919. this.compiledGlyphs = Object.create(null);
  2920. // importing translated data
  2921. for (var i in translatedData) {
  2922. this[i] = translatedData[i];
  2923. }
  2924. this.options = options;
  2925. }
  2926. FontFaceObject.prototype = {
  2927. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2928. if (!this.data) {
  2929. return null;
  2930. }
  2931. if (this.options.disableFontFace) {
  2932. this.disableFontFace = true;
  2933. return null;
  2934. }
  2935. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2936. if (this.options.fontRegistry) {
  2937. this.options.fontRegistry.registerFont(this);
  2938. }
  2939. return nativeFontFace;
  2940. },
  2941. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2942. if (!this.data) {
  2943. return null;
  2944. }
  2945. if (this.options.disableFontFace) {
  2946. this.disableFontFace = true;
  2947. return null;
  2948. }
  2949. var data = bytesToString(new Uint8Array(this.data));
  2950. var fontName = this.loadedName;
  2951. // Add the font-face rule to the document
  2952. var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');';
  2953. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2954. if (this.options.fontRegistry) {
  2955. this.options.fontRegistry.registerFont(this, url);
  2956. }
  2957. return rule;
  2958. },
  2959. getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) {
  2960. if (!(character in this.compiledGlyphs)) {
  2961. var cmds = objs.get(this.loadedName + '_path_' + character);
  2962. var current, i, len;
  2963. // If we can, compile cmds into JS for MAXIMUM SPEED
  2964. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2965. var args, js = '';
  2966. for (i = 0, len = cmds.length; i < len; i++) {
  2967. current = cmds[i];
  2968. if (current.args !== undefined) {
  2969. args = current.args.join(',');
  2970. } else {
  2971. args = '';
  2972. }
  2973. js += 'c.' + current.cmd + '(' + args + ');\n';
  2974. }
  2975. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2976. } else {
  2977. // But fall back on using Function.prototype.apply() if we're
  2978. // blocked from using eval() for whatever reason (like CSP policies)
  2979. this.compiledGlyphs[character] = function (c, size) {
  2980. for (i = 0, len = cmds.length; i < len; i++) {
  2981. current = cmds[i];
  2982. if (current.cmd === 'scale') {
  2983. current.args = [
  2984. size,
  2985. -size
  2986. ];
  2987. }
  2988. c[current.cmd].apply(c, current.args);
  2989. }
  2990. };
  2991. }
  2992. }
  2993. return this.compiledGlyphs[character];
  2994. }
  2995. };
  2996. return FontFaceObject;
  2997. }();
  2998. exports.FontFaceObject = FontFaceObject;
  2999. exports.FontLoader = FontLoader;
  3000. }));
  3001. (function (root, factory) {
  3002. factory(root.pdfjsDisplayMetadata = {}, root.pdfjsSharedUtil);
  3003. }(this, function (exports, sharedUtil) {
  3004. var error = sharedUtil.error;
  3005. function fixMetadata(meta) {
  3006. return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
  3007. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
  3008. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  3009. });
  3010. var chars = '';
  3011. for (var i = 0; i < bytes.length; i += 2) {
  3012. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  3013. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  3014. }
  3015. return '>' + chars;
  3016. });
  3017. }
  3018. function Metadata(meta) {
  3019. if (typeof meta === 'string') {
  3020. // Ghostscript produces invalid metadata
  3021. meta = fixMetadata(meta);
  3022. var parser = new DOMParser();
  3023. meta = parser.parseFromString(meta, 'application/xml');
  3024. } else if (!(meta instanceof Document)) {
  3025. error('Metadata: Invalid metadata object');
  3026. }
  3027. this.metaDocument = meta;
  3028. this.metadata = Object.create(null);
  3029. this.parse();
  3030. }
  3031. Metadata.prototype = {
  3032. parse: function Metadata_parse() {
  3033. var doc = this.metaDocument;
  3034. var rdf = doc.documentElement;
  3035. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3036. // Wrapped in <xmpmeta>
  3037. rdf = rdf.firstChild;
  3038. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3039. rdf = rdf.nextSibling;
  3040. }
  3041. }
  3042. var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
  3043. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3044. return;
  3045. }
  3046. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3047. for (i = 0, length = children.length; i < length; i++) {
  3048. desc = children[i];
  3049. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3050. continue;
  3051. }
  3052. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3053. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3054. entry = desc.childNodes[ii];
  3055. name = entry.nodeName.toLowerCase();
  3056. this.metadata[name] = entry.textContent.trim();
  3057. }
  3058. }
  3059. }
  3060. },
  3061. get: function Metadata_get(name) {
  3062. return this.metadata[name] || null;
  3063. },
  3064. has: function Metadata_has(name) {
  3065. return typeof this.metadata[name] !== 'undefined';
  3066. }
  3067. };
  3068. exports.Metadata = Metadata;
  3069. }));
  3070. (function (root, factory) {
  3071. factory(root.pdfjsDisplaySVG = {}, root.pdfjsSharedUtil);
  3072. }(this, function (exports, sharedUtil) {
  3073. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3074. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3075. var ImageKind = sharedUtil.ImageKind;
  3076. var OPS = sharedUtil.OPS;
  3077. var Util = sharedUtil.Util;
  3078. var isNum = sharedUtil.isNum;
  3079. var isArray = sharedUtil.isArray;
  3080. var warn = sharedUtil.warn;
  3081. var createObjectURL = sharedUtil.createObjectURL;
  3082. var SVG_DEFAULTS = {
  3083. fontStyle: 'normal',
  3084. fontWeight: 'normal',
  3085. fillColor: '#000000'
  3086. };
  3087. var convertImgDataToPng = function convertImgDataToPngClosure() {
  3088. var PNG_HEADER = new Uint8Array([
  3089. 0x89,
  3090. 0x50,
  3091. 0x4e,
  3092. 0x47,
  3093. 0x0d,
  3094. 0x0a,
  3095. 0x1a,
  3096. 0x0a
  3097. ]);
  3098. var CHUNK_WRAPPER_SIZE = 12;
  3099. var crcTable = new Int32Array(256);
  3100. for (var i = 0; i < 256; i++) {
  3101. var c = i;
  3102. for (var h = 0; h < 8; h++) {
  3103. if (c & 1) {
  3104. c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
  3105. } else {
  3106. c = c >> 1 & 0x7fffffff;
  3107. }
  3108. }
  3109. crcTable[i] = c;
  3110. }
  3111. function crc32(data, start, end) {
  3112. var crc = -1;
  3113. for (var i = start; i < end; i++) {
  3114. var a = (crc ^ data[i]) & 0xff;
  3115. var b = crcTable[a];
  3116. crc = crc >>> 8 ^ b;
  3117. }
  3118. return crc ^ -1;
  3119. }
  3120. function writePngChunk(type, body, data, offset) {
  3121. var p = offset;
  3122. var len = body.length;
  3123. data[p] = len >> 24 & 0xff;
  3124. data[p + 1] = len >> 16 & 0xff;
  3125. data[p + 2] = len >> 8 & 0xff;
  3126. data[p + 3] = len & 0xff;
  3127. p += 4;
  3128. data[p] = type.charCodeAt(0) & 0xff;
  3129. data[p + 1] = type.charCodeAt(1) & 0xff;
  3130. data[p + 2] = type.charCodeAt(2) & 0xff;
  3131. data[p + 3] = type.charCodeAt(3) & 0xff;
  3132. p += 4;
  3133. data.set(body, p);
  3134. p += body.length;
  3135. var crc = crc32(data, offset + 4, p);
  3136. data[p] = crc >> 24 & 0xff;
  3137. data[p + 1] = crc >> 16 & 0xff;
  3138. data[p + 2] = crc >> 8 & 0xff;
  3139. data[p + 3] = crc & 0xff;
  3140. }
  3141. function adler32(data, start, end) {
  3142. var a = 1;
  3143. var b = 0;
  3144. for (var i = start; i < end; ++i) {
  3145. a = (a + (data[i] & 0xff)) % 65521;
  3146. b = (b + a) % 65521;
  3147. }
  3148. return b << 16 | a;
  3149. }
  3150. function encode(imgData, kind, forceDataSchema) {
  3151. var width = imgData.width;
  3152. var height = imgData.height;
  3153. var bitDepth, colorType, lineSize;
  3154. var bytes = imgData.data;
  3155. switch (kind) {
  3156. case ImageKind.GRAYSCALE_1BPP:
  3157. colorType = 0;
  3158. bitDepth = 1;
  3159. lineSize = width + 7 >> 3;
  3160. break;
  3161. case ImageKind.RGB_24BPP:
  3162. colorType = 2;
  3163. bitDepth = 8;
  3164. lineSize = width * 3;
  3165. break;
  3166. case ImageKind.RGBA_32BPP:
  3167. colorType = 6;
  3168. bitDepth = 8;
  3169. lineSize = width * 4;
  3170. break;
  3171. default:
  3172. throw new Error('invalid format');
  3173. }
  3174. // prefix every row with predictor 0
  3175. var literals = new Uint8Array((1 + lineSize) * height);
  3176. var offsetLiterals = 0, offsetBytes = 0;
  3177. var y, i;
  3178. for (y = 0; y < height; ++y) {
  3179. literals[offsetLiterals++] = 0;
  3180. // no prediction
  3181. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  3182. offsetBytes += lineSize;
  3183. offsetLiterals += lineSize;
  3184. }
  3185. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3186. // inverting for B/W
  3187. offsetLiterals = 0;
  3188. for (y = 0; y < height; y++) {
  3189. offsetLiterals++;
  3190. // skipping predictor
  3191. for (i = 0; i < lineSize; i++) {
  3192. literals[offsetLiterals++] ^= 0xFF;
  3193. }
  3194. }
  3195. }
  3196. var ihdr = new Uint8Array([
  3197. width >> 24 & 0xff,
  3198. width >> 16 & 0xff,
  3199. width >> 8 & 0xff,
  3200. width & 0xff,
  3201. height >> 24 & 0xff,
  3202. height >> 16 & 0xff,
  3203. height >> 8 & 0xff,
  3204. height & 0xff,
  3205. bitDepth,
  3206. // bit depth
  3207. colorType,
  3208. // color type
  3209. 0x00,
  3210. // compression method
  3211. 0x00,
  3212. // filter method
  3213. 0x00
  3214. ]);
  3215. // interlace method
  3216. var len = literals.length;
  3217. var maxBlockLength = 0xFFFF;
  3218. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3219. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3220. var pi = 0;
  3221. idat[pi++] = 0x78;
  3222. // compression method and flags
  3223. idat[pi++] = 0x9c;
  3224. // flags
  3225. var pos = 0;
  3226. while (len > maxBlockLength) {
  3227. // writing non-final DEFLATE blocks type 0 and length of 65535
  3228. idat[pi++] = 0x00;
  3229. idat[pi++] = 0xff;
  3230. idat[pi++] = 0xff;
  3231. idat[pi++] = 0x00;
  3232. idat[pi++] = 0x00;
  3233. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3234. pi += maxBlockLength;
  3235. pos += maxBlockLength;
  3236. len -= maxBlockLength;
  3237. }
  3238. // writing non-final DEFLATE blocks type 0
  3239. idat[pi++] = 0x01;
  3240. idat[pi++] = len & 0xff;
  3241. idat[pi++] = len >> 8 & 0xff;
  3242. idat[pi++] = ~len & 0xffff & 0xff;
  3243. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3244. idat.set(literals.subarray(pos), pi);
  3245. pi += literals.length - pos;
  3246. var adler = adler32(literals, 0, literals.length);
  3247. // checksum
  3248. idat[pi++] = adler >> 24 & 0xff;
  3249. idat[pi++] = adler >> 16 & 0xff;
  3250. idat[pi++] = adler >> 8 & 0xff;
  3251. idat[pi++] = adler & 0xff;
  3252. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3253. var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  3254. var data = new Uint8Array(pngLength);
  3255. var offset = 0;
  3256. data.set(PNG_HEADER, offset);
  3257. offset += PNG_HEADER.length;
  3258. writePngChunk('IHDR', ihdr, data, offset);
  3259. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3260. writePngChunk('IDATA', idat, data, offset);
  3261. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3262. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3263. return createObjectURL(data, 'image/png', forceDataSchema);
  3264. }
  3265. return function convertImgDataToPng(imgData, forceDataSchema) {
  3266. var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
  3267. return encode(imgData, kind, forceDataSchema);
  3268. };
  3269. }();
  3270. var SVGExtraState = function SVGExtraStateClosure() {
  3271. function SVGExtraState() {
  3272. this.fontSizeScale = 1;
  3273. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3274. this.fontSize = 0;
  3275. this.textMatrix = IDENTITY_MATRIX;
  3276. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3277. this.leading = 0;
  3278. // Current point (in user coordinates)
  3279. this.x = 0;
  3280. this.y = 0;
  3281. // Start of text line (in text coordinates)
  3282. this.lineX = 0;
  3283. this.lineY = 0;
  3284. // Character and word spacing
  3285. this.charSpacing = 0;
  3286. this.wordSpacing = 0;
  3287. this.textHScale = 1;
  3288. this.textRise = 0;
  3289. // Default foreground and background colors
  3290. this.fillColor = SVG_DEFAULTS.fillColor;
  3291. this.strokeColor = '#000000';
  3292. this.fillAlpha = 1;
  3293. this.strokeAlpha = 1;
  3294. this.lineWidth = 1;
  3295. this.lineJoin = '';
  3296. this.lineCap = '';
  3297. this.miterLimit = 0;
  3298. this.dashArray = [];
  3299. this.dashPhase = 0;
  3300. this.dependencies = [];
  3301. // Clipping
  3302. this.activeClipUrl = null;
  3303. this.clipGroup = null;
  3304. this.maskId = '';
  3305. }
  3306. SVGExtraState.prototype = {
  3307. clone: function SVGExtraState_clone() {
  3308. return Object.create(this);
  3309. },
  3310. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3311. this.x = x;
  3312. this.y = y;
  3313. }
  3314. };
  3315. return SVGExtraState;
  3316. }();
  3317. var SVGGraphics = function SVGGraphicsClosure() {
  3318. function opListToTree(opList) {
  3319. var opTree = [];
  3320. var tmp = [];
  3321. var opListLen = opList.length;
  3322. for (var x = 0; x < opListLen; x++) {
  3323. if (opList[x].fn === 'save') {
  3324. opTree.push({
  3325. 'fnId': 92,
  3326. 'fn': 'group',
  3327. 'items': []
  3328. });
  3329. tmp.push(opTree);
  3330. opTree = opTree[opTree.length - 1].items;
  3331. continue;
  3332. }
  3333. if (opList[x].fn === 'restore') {
  3334. opTree = tmp.pop();
  3335. } else {
  3336. opTree.push(opList[x]);
  3337. }
  3338. }
  3339. return opTree;
  3340. }
  3341. /**
  3342. * Formats float number.
  3343. * @param value {number} number to format.
  3344. * @returns {string}
  3345. */
  3346. function pf(value) {
  3347. if (value === (value | 0)) {
  3348. // integer number
  3349. return value.toString();
  3350. }
  3351. var s = value.toFixed(10);
  3352. var i = s.length - 1;
  3353. if (s[i] !== '0') {
  3354. return s;
  3355. }
  3356. // removing trailing zeros
  3357. do {
  3358. i--;
  3359. } while (s[i] === '0');
  3360. return s.substr(0, s[i] === '.' ? i : i + 1);
  3361. }
  3362. /**
  3363. * Formats transform matrix. The standard rotation, scale and translate
  3364. * matrices are replaced by their shorter forms, and for identity matrix
  3365. * returns empty string to save the memory.
  3366. * @param m {Array} matrix to format.
  3367. * @returns {string}
  3368. */
  3369. function pm(m) {
  3370. if (m[4] === 0 && m[5] === 0) {
  3371. if (m[1] === 0 && m[2] === 0) {
  3372. if (m[0] === 1 && m[3] === 1) {
  3373. return '';
  3374. }
  3375. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3376. }
  3377. if (m[0] === m[3] && m[1] === -m[2]) {
  3378. var a = Math.acos(m[0]) * 180 / Math.PI;
  3379. return 'rotate(' + pf(a) + ')';
  3380. }
  3381. } else {
  3382. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3383. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3384. }
  3385. }
  3386. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3387. }
  3388. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3389. this.current = new SVGExtraState();
  3390. this.transformMatrix = IDENTITY_MATRIX;
  3391. // Graphics state matrix
  3392. this.transformStack = [];
  3393. this.extraStack = [];
  3394. this.commonObjs = commonObjs;
  3395. this.objs = objs;
  3396. this.pendingEOFill = false;
  3397. this.embedFonts = false;
  3398. this.embeddedFonts = Object.create(null);
  3399. this.cssStyle = null;
  3400. this.forceDataSchema = !!forceDataSchema;
  3401. }
  3402. var NS = 'http://www.w3.org/2000/svg';
  3403. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3404. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3405. var LINE_CAP_STYLES = [
  3406. 'butt',
  3407. 'round',
  3408. 'square'
  3409. ];
  3410. var LINE_JOIN_STYLES = [
  3411. 'miter',
  3412. 'round',
  3413. 'bevel'
  3414. ];
  3415. var clipCount = 0;
  3416. var maskCount = 0;
  3417. SVGGraphics.prototype = {
  3418. save: function SVGGraphics_save() {
  3419. this.transformStack.push(this.transformMatrix);
  3420. var old = this.current;
  3421. this.extraStack.push(old);
  3422. this.current = old.clone();
  3423. },
  3424. restore: function SVGGraphics_restore() {
  3425. this.transformMatrix = this.transformStack.pop();
  3426. this.current = this.extraStack.pop();
  3427. this.tgrp = null;
  3428. },
  3429. group: function SVGGraphics_group(items) {
  3430. this.save();
  3431. this.executeOpTree(items);
  3432. this.restore();
  3433. },
  3434. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3435. var fnArray = operatorList.fnArray;
  3436. var fnArrayLen = fnArray.length;
  3437. var argsArray = operatorList.argsArray;
  3438. var self = this;
  3439. for (var i = 0; i < fnArrayLen; i++) {
  3440. if (OPS.dependency === fnArray[i]) {
  3441. var deps = argsArray[i];
  3442. for (var n = 0, nn = deps.length; n < nn; n++) {
  3443. var obj = deps[n];
  3444. var common = obj.substring(0, 2) === 'g_';
  3445. var promise;
  3446. if (common) {
  3447. promise = new Promise(function (resolve) {
  3448. self.commonObjs.get(obj, resolve);
  3449. });
  3450. } else {
  3451. promise = new Promise(function (resolve) {
  3452. self.objs.get(obj, resolve);
  3453. });
  3454. }
  3455. this.current.dependencies.push(promise);
  3456. }
  3457. }
  3458. }
  3459. return Promise.all(this.current.dependencies);
  3460. },
  3461. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3462. var transformMatrix = [
  3463. a,
  3464. b,
  3465. c,
  3466. d,
  3467. e,
  3468. f
  3469. ];
  3470. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3471. this.tgrp = null;
  3472. },
  3473. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3474. this.viewport = viewport;
  3475. var svgElement = this._initialize(viewport);
  3476. return this.loadDependencies(operatorList).then(function () {
  3477. this.transformMatrix = IDENTITY_MATRIX;
  3478. var opTree = this.convertOpList(operatorList);
  3479. this.executeOpTree(opTree);
  3480. return svgElement;
  3481. }.bind(this));
  3482. },
  3483. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3484. var argsArray = operatorList.argsArray;
  3485. var fnArray = operatorList.fnArray;
  3486. var fnArrayLen = fnArray.length;
  3487. var REVOPS = [];
  3488. var opList = [];
  3489. for (var op in OPS) {
  3490. REVOPS[OPS[op]] = op;
  3491. }
  3492. for (var x = 0; x < fnArrayLen; x++) {
  3493. var fnId = fnArray[x];
  3494. opList.push({
  3495. 'fnId': fnId,
  3496. 'fn': REVOPS[fnId],
  3497. 'args': argsArray[x]
  3498. });
  3499. }
  3500. return opListToTree(opList);
  3501. },
  3502. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3503. var opTreeLen = opTree.length;
  3504. for (var x = 0; x < opTreeLen; x++) {
  3505. var fn = opTree[x].fn;
  3506. var fnId = opTree[x].fnId;
  3507. var args = opTree[x].args;
  3508. switch (fnId | 0) {
  3509. case OPS.beginText:
  3510. this.beginText();
  3511. break;
  3512. case OPS.setLeading:
  3513. this.setLeading(args);
  3514. break;
  3515. case OPS.setLeadingMoveText:
  3516. this.setLeadingMoveText(args[0], args[1]);
  3517. break;
  3518. case OPS.setFont:
  3519. this.setFont(args);
  3520. break;
  3521. case OPS.showText:
  3522. this.showText(args[0]);
  3523. break;
  3524. case OPS.showSpacedText:
  3525. this.showText(args[0]);
  3526. break;
  3527. case OPS.endText:
  3528. this.endText();
  3529. break;
  3530. case OPS.moveText:
  3531. this.moveText(args[0], args[1]);
  3532. break;
  3533. case OPS.setCharSpacing:
  3534. this.setCharSpacing(args[0]);
  3535. break;
  3536. case OPS.setWordSpacing:
  3537. this.setWordSpacing(args[0]);
  3538. break;
  3539. case OPS.setHScale:
  3540. this.setHScale(args[0]);
  3541. break;
  3542. case OPS.setTextMatrix:
  3543. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3544. break;
  3545. case OPS.setLineWidth:
  3546. this.setLineWidth(args[0]);
  3547. break;
  3548. case OPS.setLineJoin:
  3549. this.setLineJoin(args[0]);
  3550. break;
  3551. case OPS.setLineCap:
  3552. this.setLineCap(args[0]);
  3553. break;
  3554. case OPS.setMiterLimit:
  3555. this.setMiterLimit(args[0]);
  3556. break;
  3557. case OPS.setFillRGBColor:
  3558. this.setFillRGBColor(args[0], args[1], args[2]);
  3559. break;
  3560. case OPS.setStrokeRGBColor:
  3561. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3562. break;
  3563. case OPS.setDash:
  3564. this.setDash(args[0], args[1]);
  3565. break;
  3566. case OPS.setGState:
  3567. this.setGState(args[0]);
  3568. break;
  3569. case OPS.fill:
  3570. this.fill();
  3571. break;
  3572. case OPS.eoFill:
  3573. this.eoFill();
  3574. break;
  3575. case OPS.stroke:
  3576. this.stroke();
  3577. break;
  3578. case OPS.fillStroke:
  3579. this.fillStroke();
  3580. break;
  3581. case OPS.eoFillStroke:
  3582. this.eoFillStroke();
  3583. break;
  3584. case OPS.clip:
  3585. this.clip('nonzero');
  3586. break;
  3587. case OPS.eoClip:
  3588. this.clip('evenodd');
  3589. break;
  3590. case OPS.paintSolidColorImageMask:
  3591. this.paintSolidColorImageMask();
  3592. break;
  3593. case OPS.paintJpegXObject:
  3594. this.paintJpegXObject(args[0], args[1], args[2]);
  3595. break;
  3596. case OPS.paintImageXObject:
  3597. this.paintImageXObject(args[0]);
  3598. break;
  3599. case OPS.paintInlineImageXObject:
  3600. this.paintInlineImageXObject(args[0]);
  3601. break;
  3602. case OPS.paintImageMaskXObject:
  3603. this.paintImageMaskXObject(args[0]);
  3604. break;
  3605. case OPS.paintFormXObjectBegin:
  3606. this.paintFormXObjectBegin(args[0], args[1]);
  3607. break;
  3608. case OPS.paintFormXObjectEnd:
  3609. this.paintFormXObjectEnd();
  3610. break;
  3611. case OPS.closePath:
  3612. this.closePath();
  3613. break;
  3614. case OPS.closeStroke:
  3615. this.closeStroke();
  3616. break;
  3617. case OPS.closeFillStroke:
  3618. this.closeFillStroke();
  3619. break;
  3620. case OPS.nextLine:
  3621. this.nextLine();
  3622. break;
  3623. case OPS.transform:
  3624. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3625. break;
  3626. case OPS.constructPath:
  3627. this.constructPath(args[0], args[1]);
  3628. break;
  3629. case OPS.endPath:
  3630. this.endPath();
  3631. break;
  3632. case 92:
  3633. this.group(opTree[x].items);
  3634. break;
  3635. default:
  3636. warn('Unimplemented operator ' + fn);
  3637. break;
  3638. }
  3639. }
  3640. },
  3641. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3642. this.current.wordSpacing = wordSpacing;
  3643. },
  3644. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3645. this.current.charSpacing = charSpacing;
  3646. },
  3647. nextLine: function SVGGraphics_nextLine() {
  3648. this.moveText(0, this.current.leading);
  3649. },
  3650. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3651. var current = this.current;
  3652. this.current.textMatrix = this.current.lineMatrix = [
  3653. a,
  3654. b,
  3655. c,
  3656. d,
  3657. e,
  3658. f
  3659. ];
  3660. this.current.x = this.current.lineX = 0;
  3661. this.current.y = this.current.lineY = 0;
  3662. current.xcoords = [];
  3663. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3664. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3665. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3666. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3667. current.txtElement = document.createElementNS(NS, 'svg:text');
  3668. current.txtElement.appendChild(current.tspan);
  3669. },
  3670. beginText: function SVGGraphics_beginText() {
  3671. this.current.x = this.current.lineX = 0;
  3672. this.current.y = this.current.lineY = 0;
  3673. this.current.textMatrix = IDENTITY_MATRIX;
  3674. this.current.lineMatrix = IDENTITY_MATRIX;
  3675. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3676. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3677. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3678. this.current.xcoords = [];
  3679. },
  3680. moveText: function SVGGraphics_moveText(x, y) {
  3681. var current = this.current;
  3682. this.current.x = this.current.lineX += x;
  3683. this.current.y = this.current.lineY += y;
  3684. current.xcoords = [];
  3685. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3686. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3687. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3688. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3689. },
  3690. showText: function SVGGraphics_showText(glyphs) {
  3691. var current = this.current;
  3692. var font = current.font;
  3693. var fontSize = current.fontSize;
  3694. if (fontSize === 0) {
  3695. return;
  3696. }
  3697. var charSpacing = current.charSpacing;
  3698. var wordSpacing = current.wordSpacing;
  3699. var fontDirection = current.fontDirection;
  3700. var textHScale = current.textHScale * fontDirection;
  3701. var glyphsLength = glyphs.length;
  3702. var vertical = font.vertical;
  3703. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3704. var x = 0, i;
  3705. for (i = 0; i < glyphsLength; ++i) {
  3706. var glyph = glyphs[i];
  3707. if (glyph === null) {
  3708. // word break
  3709. x += fontDirection * wordSpacing;
  3710. continue;
  3711. } else if (isNum(glyph)) {
  3712. x += -glyph * fontSize * 0.001;
  3713. continue;
  3714. }
  3715. current.xcoords.push(current.x + x * textHScale);
  3716. var width = glyph.width;
  3717. var character = glyph.fontChar;
  3718. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3719. x += charWidth;
  3720. current.tspan.textContent += character;
  3721. }
  3722. if (vertical) {
  3723. current.y -= x * textHScale;
  3724. } else {
  3725. current.x += x * textHScale;
  3726. }
  3727. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3728. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3729. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3730. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3731. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3732. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3733. }
  3734. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3735. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3736. }
  3737. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3738. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3739. }
  3740. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3741. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3742. current.txtElement.appendChild(current.tspan);
  3743. current.txtgrp.appendChild(current.txtElement);
  3744. this._ensureTransformGroup().appendChild(current.txtElement);
  3745. },
  3746. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3747. this.setLeading(-y);
  3748. this.moveText(x, y);
  3749. },
  3750. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3751. if (!this.cssStyle) {
  3752. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3753. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3754. this.defs.appendChild(this.cssStyle);
  3755. }
  3756. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3757. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3758. },
  3759. setFont: function SVGGraphics_setFont(details) {
  3760. var current = this.current;
  3761. var fontObj = this.commonObjs.get(details[0]);
  3762. var size = details[1];
  3763. this.current.font = fontObj;
  3764. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3765. this.addFontStyle(fontObj);
  3766. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3767. }
  3768. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3769. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3770. var italic = fontObj.italic ? 'italic' : 'normal';
  3771. if (size < 0) {
  3772. size = -size;
  3773. current.fontDirection = -1;
  3774. } else {
  3775. current.fontDirection = 1;
  3776. }
  3777. current.fontSize = size;
  3778. current.fontFamily = fontObj.loadedName;
  3779. current.fontWeight = bold;
  3780. current.fontStyle = italic;
  3781. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3782. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3783. current.xcoords = [];
  3784. },
  3785. endText: function SVGGraphics_endText() {
  3786. },
  3787. // Path properties
  3788. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3789. this.current.lineWidth = width;
  3790. },
  3791. setLineCap: function SVGGraphics_setLineCap(style) {
  3792. this.current.lineCap = LINE_CAP_STYLES[style];
  3793. },
  3794. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3795. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3796. },
  3797. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3798. this.current.miterLimit = limit;
  3799. },
  3800. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3801. var color = Util.makeCssRgb(r, g, b);
  3802. this.current.strokeColor = color;
  3803. },
  3804. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3805. var color = Util.makeCssRgb(r, g, b);
  3806. this.current.fillColor = color;
  3807. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3808. this.current.xcoords = [];
  3809. },
  3810. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3811. this.current.dashArray = dashArray;
  3812. this.current.dashPhase = dashPhase;
  3813. },
  3814. constructPath: function SVGGraphics_constructPath(ops, args) {
  3815. var current = this.current;
  3816. var x = current.x, y = current.y;
  3817. current.path = document.createElementNS(NS, 'svg:path');
  3818. var d = [];
  3819. var opLength = ops.length;
  3820. for (var i = 0, j = 0; i < opLength; i++) {
  3821. switch (ops[i] | 0) {
  3822. case OPS.rectangle:
  3823. x = args[j++];
  3824. y = args[j++];
  3825. var width = args[j++];
  3826. var height = args[j++];
  3827. var xw = x + width;
  3828. var yh = y + height;
  3829. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3830. break;
  3831. case OPS.moveTo:
  3832. x = args[j++];
  3833. y = args[j++];
  3834. d.push('M', pf(x), pf(y));
  3835. break;
  3836. case OPS.lineTo:
  3837. x = args[j++];
  3838. y = args[j++];
  3839. d.push('L', pf(x), pf(y));
  3840. break;
  3841. case OPS.curveTo:
  3842. x = args[j + 4];
  3843. y = args[j + 5];
  3844. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3845. j += 6;
  3846. break;
  3847. case OPS.curveTo2:
  3848. x = args[j + 2];
  3849. y = args[j + 3];
  3850. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3851. j += 4;
  3852. break;
  3853. case OPS.curveTo3:
  3854. x = args[j + 2];
  3855. y = args[j + 3];
  3856. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3857. j += 4;
  3858. break;
  3859. case OPS.closePath:
  3860. d.push('Z');
  3861. break;
  3862. }
  3863. }
  3864. current.path.setAttributeNS(null, 'd', d.join(' '));
  3865. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3866. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3867. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3868. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3869. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3870. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3871. current.path.setAttributeNS(null, 'fill', 'none');
  3872. this._ensureTransformGroup().appendChild(current.path);
  3873. // Saving a reference in current.element so that it can be addressed
  3874. // in 'fill' and 'stroke'
  3875. current.element = current.path;
  3876. current.setCurrentPoint(x, y);
  3877. },
  3878. endPath: function SVGGraphics_endPath() {
  3879. },
  3880. clip: function SVGGraphics_clip(type) {
  3881. var current = this.current;
  3882. // Add current path to clipping path
  3883. var clipId = 'clippath' + clipCount;
  3884. clipCount++;
  3885. var clipPath = document.createElementNS(NS, 'svg:clipPath');
  3886. clipPath.setAttributeNS(null, 'id', clipId);
  3887. clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3888. var clipElement = current.element.cloneNode();
  3889. if (type === 'evenodd') {
  3890. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3891. } else {
  3892. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3893. }
  3894. clipPath.appendChild(clipElement);
  3895. this.defs.appendChild(clipPath);
  3896. if (current.activeClipUrl) {
  3897. // The previous clipping group content can go out of order -- resetting
  3898. // cached clipGroup's.
  3899. current.clipGroup = null;
  3900. this.extraStack.forEach(function (prev) {
  3901. prev.clipGroup = null;
  3902. });
  3903. }
  3904. current.activeClipUrl = 'url(#' + clipId + ')';
  3905. this.tgrp = null;
  3906. },
  3907. closePath: function SVGGraphics_closePath() {
  3908. var current = this.current;
  3909. var d = current.path.getAttributeNS(null, 'd');
  3910. d += 'Z';
  3911. current.path.setAttributeNS(null, 'd', d);
  3912. },
  3913. setLeading: function SVGGraphics_setLeading(leading) {
  3914. this.current.leading = -leading;
  3915. },
  3916. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3917. this.current.textRise = textRise;
  3918. },
  3919. setHScale: function SVGGraphics_setHScale(scale) {
  3920. this.current.textHScale = scale / 100;
  3921. },
  3922. setGState: function SVGGraphics_setGState(states) {
  3923. for (var i = 0, ii = states.length; i < ii; i++) {
  3924. var state = states[i];
  3925. var key = state[0];
  3926. var value = state[1];
  3927. switch (key) {
  3928. case 'LW':
  3929. this.setLineWidth(value);
  3930. break;
  3931. case 'LC':
  3932. this.setLineCap(value);
  3933. break;
  3934. case 'LJ':
  3935. this.setLineJoin(value);
  3936. break;
  3937. case 'ML':
  3938. this.setMiterLimit(value);
  3939. break;
  3940. case 'D':
  3941. this.setDash(value[0], value[1]);
  3942. break;
  3943. case 'Font':
  3944. this.setFont(value);
  3945. break;
  3946. default:
  3947. warn('Unimplemented graphic state ' + key);
  3948. break;
  3949. }
  3950. }
  3951. },
  3952. fill: function SVGGraphics_fill() {
  3953. var current = this.current;
  3954. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3955. },
  3956. stroke: function SVGGraphics_stroke() {
  3957. var current = this.current;
  3958. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3959. current.element.setAttributeNS(null, 'fill', 'none');
  3960. },
  3961. eoFill: function SVGGraphics_eoFill() {
  3962. var current = this.current;
  3963. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3964. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3965. },
  3966. fillStroke: function SVGGraphics_fillStroke() {
  3967. // Order is important since stroke wants fill to be none.
  3968. // First stroke, then if fill needed, it will be overwritten.
  3969. this.stroke();
  3970. this.fill();
  3971. },
  3972. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3973. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3974. this.fillStroke();
  3975. },
  3976. closeStroke: function SVGGraphics_closeStroke() {
  3977. this.closePath();
  3978. this.stroke();
  3979. },
  3980. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3981. this.closePath();
  3982. this.fillStroke();
  3983. },
  3984. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  3985. var current = this.current;
  3986. var rect = document.createElementNS(NS, 'svg:rect');
  3987. rect.setAttributeNS(null, 'x', '0');
  3988. rect.setAttributeNS(null, 'y', '0');
  3989. rect.setAttributeNS(null, 'width', '1px');
  3990. rect.setAttributeNS(null, 'height', '1px');
  3991. rect.setAttributeNS(null, 'fill', current.fillColor);
  3992. this._ensureTransformGroup().appendChild(rect);
  3993. },
  3994. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3995. var imgObj = this.objs.get(objId);
  3996. var imgEl = document.createElementNS(NS, 'svg:image');
  3997. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3998. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3999. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  4000. imgEl.setAttributeNS(null, 'x', '0');
  4001. imgEl.setAttributeNS(null, 'y', pf(-h));
  4002. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  4003. this._ensureTransformGroup().appendChild(imgEl);
  4004. },
  4005. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  4006. var imgData = this.objs.get(objId);
  4007. if (!imgData) {
  4008. warn('Dependent image isn\'t ready yet');
  4009. return;
  4010. }
  4011. this.paintInlineImageXObject(imgData);
  4012. },
  4013. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  4014. var width = imgData.width;
  4015. var height = imgData.height;
  4016. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  4017. var cliprect = document.createElementNS(NS, 'svg:rect');
  4018. cliprect.setAttributeNS(null, 'x', '0');
  4019. cliprect.setAttributeNS(null, 'y', '0');
  4020. cliprect.setAttributeNS(null, 'width', pf(width));
  4021. cliprect.setAttributeNS(null, 'height', pf(height));
  4022. this.current.element = cliprect;
  4023. this.clip('nonzero');
  4024. var imgEl = document.createElementNS(NS, 'svg:image');
  4025. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4026. imgEl.setAttributeNS(null, 'x', '0');
  4027. imgEl.setAttributeNS(null, 'y', pf(-height));
  4028. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4029. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4030. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  4031. if (mask) {
  4032. mask.appendChild(imgEl);
  4033. } else {
  4034. this._ensureTransformGroup().appendChild(imgEl);
  4035. }
  4036. },
  4037. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  4038. var current = this.current;
  4039. var width = imgData.width;
  4040. var height = imgData.height;
  4041. var fillColor = current.fillColor;
  4042. current.maskId = 'mask' + maskCount++;
  4043. var mask = document.createElementNS(NS, 'svg:mask');
  4044. mask.setAttributeNS(null, 'id', current.maskId);
  4045. var rect = document.createElementNS(NS, 'svg:rect');
  4046. rect.setAttributeNS(null, 'x', '0');
  4047. rect.setAttributeNS(null, 'y', '0');
  4048. rect.setAttributeNS(null, 'width', pf(width));
  4049. rect.setAttributeNS(null, 'height', pf(height));
  4050. rect.setAttributeNS(null, 'fill', fillColor);
  4051. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  4052. this.defs.appendChild(mask);
  4053. this._ensureTransformGroup().appendChild(rect);
  4054. this.paintInlineImageXObject(imgData, mask);
  4055. },
  4056. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4057. if (isArray(matrix) && matrix.length === 6) {
  4058. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  4059. }
  4060. if (isArray(bbox) && bbox.length === 4) {
  4061. var width = bbox[2] - bbox[0];
  4062. var height = bbox[3] - bbox[1];
  4063. var cliprect = document.createElementNS(NS, 'svg:rect');
  4064. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4065. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4066. cliprect.setAttributeNS(null, 'width', pf(width));
  4067. cliprect.setAttributeNS(null, 'height', pf(height));
  4068. this.current.element = cliprect;
  4069. this.clip('nonzero');
  4070. this.endPath();
  4071. }
  4072. },
  4073. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  4074. },
  4075. /**
  4076. * @private
  4077. */
  4078. _initialize: function SVGGraphics_initialize(viewport) {
  4079. // Create the SVG element.
  4080. var svg = document.createElementNS(NS, 'svg:svg');
  4081. svg.setAttributeNS(null, 'version', '1.1');
  4082. svg.setAttributeNS(null, 'width', viewport.width + 'px');
  4083. svg.setAttributeNS(null, 'height', viewport.height + 'px');
  4084. svg.setAttributeNS(null, 'viewBox', '0 0 ' + viewport.width + ' ' + viewport.height);
  4085. // Create the definitions element.
  4086. var definitions = document.createElementNS(NS, 'svg:defs');
  4087. svg.appendChild(definitions);
  4088. this.defs = definitions;
  4089. // Create the root group element, which acts a container for all other
  4090. // groups and applies the viewport transform.
  4091. var rootGroup = document.createElementNS(NS, 'svg:g');
  4092. rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform));
  4093. svg.appendChild(rootGroup);
  4094. // For the construction of the SVG image we are only interested in the
  4095. // root group, so we expose it as the entry point of the SVG image for
  4096. // the other code in this class.
  4097. this.svg = rootGroup;
  4098. return svg;
  4099. },
  4100. /**
  4101. * @private
  4102. */
  4103. _ensureClipGroup: function SVGGraphics_ensureClipGroup() {
  4104. if (!this.current.clipGroup) {
  4105. var clipGroup = document.createElementNS(NS, 'svg:g');
  4106. clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl);
  4107. this.svg.appendChild(clipGroup);
  4108. this.current.clipGroup = clipGroup;
  4109. }
  4110. return this.current.clipGroup;
  4111. },
  4112. /**
  4113. * @private
  4114. */
  4115. _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() {
  4116. if (!this.tgrp) {
  4117. this.tgrp = document.createElementNS(NS, 'svg:g');
  4118. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4119. if (this.current.activeClipUrl) {
  4120. this._ensureClipGroup().appendChild(this.tgrp);
  4121. } else {
  4122. this.svg.appendChild(this.tgrp);
  4123. }
  4124. }
  4125. return this.tgrp;
  4126. }
  4127. };
  4128. return SVGGraphics;
  4129. }();
  4130. exports.SVGGraphics = SVGGraphics;
  4131. }));
  4132. (function (root, factory) {
  4133. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4134. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4135. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  4136. var AnnotationType = sharedUtil.AnnotationType;
  4137. var Util = sharedUtil.Util;
  4138. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  4139. var LinkTarget = displayDOMUtils.LinkTarget;
  4140. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  4141. var warn = sharedUtil.warn;
  4142. var CustomStyle = displayDOMUtils.CustomStyle;
  4143. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4144. /**
  4145. * @typedef {Object} AnnotationElementParameters
  4146. * @property {Object} data
  4147. * @property {HTMLDivElement} layer
  4148. * @property {PDFPage} page
  4149. * @property {PageViewport} viewport
  4150. * @property {IPDFLinkService} linkService
  4151. * @property {DownloadManager} downloadManager
  4152. * @property {string} imageResourcesPath
  4153. * @property {boolean} renderInteractiveForms
  4154. */
  4155. /**
  4156. * @class
  4157. * @alias AnnotationElementFactory
  4158. */
  4159. function AnnotationElementFactory() {
  4160. }
  4161. AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */
  4162. {
  4163. /**
  4164. * @param {AnnotationElementParameters} parameters
  4165. * @returns {AnnotationElement}
  4166. */
  4167. create: function AnnotationElementFactory_create(parameters) {
  4168. var subtype = parameters.data.annotationType;
  4169. switch (subtype) {
  4170. case AnnotationType.LINK:
  4171. return new LinkAnnotationElement(parameters);
  4172. case AnnotationType.TEXT:
  4173. return new TextAnnotationElement(parameters);
  4174. case AnnotationType.WIDGET:
  4175. var fieldType = parameters.data.fieldType;
  4176. switch (fieldType) {
  4177. case 'Tx':
  4178. return new TextWidgetAnnotationElement(parameters);
  4179. case 'Ch':
  4180. return new ChoiceWidgetAnnotationElement(parameters);
  4181. }
  4182. return new WidgetAnnotationElement(parameters);
  4183. case AnnotationType.POPUP:
  4184. return new PopupAnnotationElement(parameters);
  4185. case AnnotationType.HIGHLIGHT:
  4186. return new HighlightAnnotationElement(parameters);
  4187. case AnnotationType.UNDERLINE:
  4188. return new UnderlineAnnotationElement(parameters);
  4189. case AnnotationType.SQUIGGLY:
  4190. return new SquigglyAnnotationElement(parameters);
  4191. case AnnotationType.STRIKEOUT:
  4192. return new StrikeOutAnnotationElement(parameters);
  4193. case AnnotationType.FILEATTACHMENT:
  4194. return new FileAttachmentAnnotationElement(parameters);
  4195. default:
  4196. return new AnnotationElement(parameters);
  4197. }
  4198. }
  4199. };
  4200. /**
  4201. * @class
  4202. * @alias AnnotationElement
  4203. */
  4204. var AnnotationElement = function AnnotationElementClosure() {
  4205. function AnnotationElement(parameters, isRenderable) {
  4206. this.isRenderable = isRenderable || false;
  4207. this.data = parameters.data;
  4208. this.layer = parameters.layer;
  4209. this.page = parameters.page;
  4210. this.viewport = parameters.viewport;
  4211. this.linkService = parameters.linkService;
  4212. this.downloadManager = parameters.downloadManager;
  4213. this.imageResourcesPath = parameters.imageResourcesPath;
  4214. this.renderInteractiveForms = parameters.renderInteractiveForms;
  4215. if (isRenderable) {
  4216. this.container = this._createContainer();
  4217. }
  4218. }
  4219. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */
  4220. {
  4221. /**
  4222. * Create an empty container for the annotation's HTML element.
  4223. *
  4224. * @private
  4225. * @memberof AnnotationElement
  4226. * @returns {HTMLSectionElement}
  4227. */
  4228. _createContainer: function AnnotationElement_createContainer() {
  4229. var data = this.data, page = this.page, viewport = this.viewport;
  4230. var container = document.createElement('section');
  4231. var width = data.rect[2] - data.rect[0];
  4232. var height = data.rect[3] - data.rect[1];
  4233. container.setAttribute('data-annotation-id', data.id);
  4234. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4235. // position on subsequent calls to `_createContainer` (see issue 6804).
  4236. var rect = Util.normalizeRect([
  4237. data.rect[0],
  4238. page.view[3] - data.rect[1] + page.view[1],
  4239. data.rect[2],
  4240. page.view[3] - data.rect[3] + page.view[1]
  4241. ]);
  4242. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  4243. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  4244. if (data.borderStyle.width > 0) {
  4245. container.style.borderWidth = data.borderStyle.width + 'px';
  4246. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4247. // Underline styles only have a bottom border, so we do not need
  4248. // to adjust for all borders. This yields a similar result as
  4249. // Adobe Acrobat/Reader.
  4250. width = width - 2 * data.borderStyle.width;
  4251. height = height - 2 * data.borderStyle.width;
  4252. }
  4253. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4254. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4255. if (horizontalRadius > 0 || verticalRadius > 0) {
  4256. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4257. CustomStyle.setProp('borderRadius', container, radius);
  4258. }
  4259. switch (data.borderStyle.style) {
  4260. case AnnotationBorderStyleType.SOLID:
  4261. container.style.borderStyle = 'solid';
  4262. break;
  4263. case AnnotationBorderStyleType.DASHED:
  4264. container.style.borderStyle = 'dashed';
  4265. break;
  4266. case AnnotationBorderStyleType.BEVELED:
  4267. warn('Unimplemented border style: beveled');
  4268. break;
  4269. case AnnotationBorderStyleType.INSET:
  4270. warn('Unimplemented border style: inset');
  4271. break;
  4272. case AnnotationBorderStyleType.UNDERLINE:
  4273. container.style.borderBottomStyle = 'solid';
  4274. break;
  4275. default:
  4276. break;
  4277. }
  4278. if (data.color) {
  4279. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  4280. } else {
  4281. // Transparent (invisible) border, so do not draw it at all.
  4282. container.style.borderWidth = 0;
  4283. }
  4284. }
  4285. container.style.left = rect[0] + 'px';
  4286. container.style.top = rect[1] + 'px';
  4287. container.style.width = width + 'px';
  4288. container.style.height = height + 'px';
  4289. return container;
  4290. },
  4291. /**
  4292. * Create a popup for the annotation's HTML element. This is used for
  4293. * annotations that do not have a Popup entry in the dictionary, but
  4294. * are of a type that works with popups (such as Highlight annotations).
  4295. *
  4296. * @private
  4297. * @param {HTMLSectionElement} container
  4298. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4299. * @param {Object} data
  4300. * @memberof AnnotationElement
  4301. */
  4302. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  4303. // If no trigger element is specified, create it.
  4304. if (!trigger) {
  4305. trigger = document.createElement('div');
  4306. trigger.style.height = container.style.height;
  4307. trigger.style.width = container.style.width;
  4308. container.appendChild(trigger);
  4309. }
  4310. var popupElement = new PopupElement({
  4311. container: container,
  4312. trigger: trigger,
  4313. color: data.color,
  4314. title: data.title,
  4315. contents: data.contents,
  4316. hideWrapper: true
  4317. });
  4318. var popup = popupElement.render();
  4319. // Position the popup next to the annotation's container.
  4320. popup.style.left = container.style.width;
  4321. container.appendChild(popup);
  4322. },
  4323. /**
  4324. * Render the annotation's HTML element in the empty container.
  4325. *
  4326. * @public
  4327. * @memberof AnnotationElement
  4328. */
  4329. render: function AnnotationElement_render() {
  4330. throw new Error('Abstract method AnnotationElement.render called');
  4331. }
  4332. };
  4333. return AnnotationElement;
  4334. }();
  4335. /**
  4336. * @class
  4337. * @alias LinkAnnotationElement
  4338. */
  4339. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  4340. function LinkAnnotationElement(parameters) {
  4341. AnnotationElement.call(this, parameters, true);
  4342. }
  4343. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4344. /**
  4345. * Render the link annotation's HTML element in the empty container.
  4346. *
  4347. * @public
  4348. * @memberof LinkAnnotationElement
  4349. * @returns {HTMLSectionElement}
  4350. */
  4351. render: function LinkAnnotationElement_render() {
  4352. this.container.className = 'linkAnnotation';
  4353. var link = document.createElement('a');
  4354. addLinkAttributes(link, {
  4355. url: this.data.url,
  4356. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  4357. });
  4358. if (!this.data.url) {
  4359. if (this.data.action) {
  4360. this._bindNamedAction(link, this.data.action);
  4361. } else {
  4362. this._bindLink(link, this.data.dest);
  4363. }
  4364. }
  4365. this.container.appendChild(link);
  4366. return this.container;
  4367. },
  4368. /**
  4369. * Bind internal links to the link element.
  4370. *
  4371. * @private
  4372. * @param {Object} link
  4373. * @param {Object} destination
  4374. * @memberof LinkAnnotationElement
  4375. */
  4376. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4377. var self = this;
  4378. link.href = this.linkService.getDestinationHash(destination);
  4379. link.onclick = function () {
  4380. if (destination) {
  4381. self.linkService.navigateTo(destination);
  4382. }
  4383. return false;
  4384. };
  4385. if (destination) {
  4386. link.className = 'internalLink';
  4387. }
  4388. },
  4389. /**
  4390. * Bind named actions to the link element.
  4391. *
  4392. * @private
  4393. * @param {Object} link
  4394. * @param {Object} action
  4395. * @memberof LinkAnnotationElement
  4396. */
  4397. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  4398. var self = this;
  4399. link.href = this.linkService.getAnchorUrl('');
  4400. link.onclick = function () {
  4401. self.linkService.executeNamedAction(action);
  4402. return false;
  4403. };
  4404. link.className = 'internalLink';
  4405. }
  4406. });
  4407. return LinkAnnotationElement;
  4408. }();
  4409. /**
  4410. * @class
  4411. * @alias TextAnnotationElement
  4412. */
  4413. var TextAnnotationElement = function TextAnnotationElementClosure() {
  4414. function TextAnnotationElement(parameters) {
  4415. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4416. AnnotationElement.call(this, parameters, isRenderable);
  4417. }
  4418. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4419. /**
  4420. * Render the text annotation's HTML element in the empty container.
  4421. *
  4422. * @public
  4423. * @memberof TextAnnotationElement
  4424. * @returns {HTMLSectionElement}
  4425. */
  4426. render: function TextAnnotationElement_render() {
  4427. this.container.className = 'textAnnotation';
  4428. var image = document.createElement('img');
  4429. image.style.height = this.container.style.height;
  4430. image.style.width = this.container.style.width;
  4431. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  4432. image.alt = '[{{type}} Annotation]';
  4433. image.dataset.l10nId = 'text_annotation_type';
  4434. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  4435. if (!this.data.hasPopup) {
  4436. this._createPopup(this.container, image, this.data);
  4437. }
  4438. this.container.appendChild(image);
  4439. return this.container;
  4440. }
  4441. });
  4442. return TextAnnotationElement;
  4443. }();
  4444. /**
  4445. * @class
  4446. * @alias WidgetAnnotationElement
  4447. */
  4448. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4449. function WidgetAnnotationElement(parameters, isRenderable) {
  4450. AnnotationElement.call(this, parameters, isRenderable);
  4451. }
  4452. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4453. /**
  4454. * Render the widget annotation's HTML element in the empty container.
  4455. *
  4456. * @public
  4457. * @memberof WidgetAnnotationElement
  4458. * @returns {HTMLSectionElement}
  4459. */
  4460. render: function WidgetAnnotationElement_render() {
  4461. // Show only the container for unsupported field types.
  4462. return this.container;
  4463. }
  4464. });
  4465. return WidgetAnnotationElement;
  4466. }();
  4467. /**
  4468. * @class
  4469. * @alias TextWidgetAnnotationElement
  4470. */
  4471. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4472. var TEXT_ALIGNMENT = [
  4473. 'left',
  4474. 'center',
  4475. 'right'
  4476. ];
  4477. function TextWidgetAnnotationElement(parameters) {
  4478. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4479. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4480. }
  4481. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4482. /**
  4483. * Render the text widget annotation's HTML element in the empty container.
  4484. *
  4485. * @public
  4486. * @memberof TextWidgetAnnotationElement
  4487. * @returns {HTMLSectionElement}
  4488. */
  4489. render: function TextWidgetAnnotationElement_render() {
  4490. this.container.className = 'textWidgetAnnotation';
  4491. var element = null;
  4492. if (this.renderInteractiveForms) {
  4493. // NOTE: We cannot set the values using `element.value` below, since it
  4494. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4495. // from parsing the elements correctly for the reference tests.
  4496. if (this.data.multiLine) {
  4497. element = document.createElement('textarea');
  4498. element.textContent = this.data.fieldValue;
  4499. } else {
  4500. element = document.createElement('input');
  4501. element.type = 'text';
  4502. element.setAttribute('value', this.data.fieldValue);
  4503. }
  4504. element.disabled = this.data.readOnly;
  4505. if (this.data.maxLen !== null) {
  4506. element.maxLength = this.data.maxLen;
  4507. }
  4508. if (this.data.comb) {
  4509. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4510. var combWidth = fieldWidth / this.data.maxLen;
  4511. element.classList.add('comb');
  4512. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4513. }
  4514. } else {
  4515. element = document.createElement('div');
  4516. element.textContent = this.data.fieldValue;
  4517. element.style.verticalAlign = 'middle';
  4518. element.style.display = 'table-cell';
  4519. var font = null;
  4520. if (this.data.fontRefName) {
  4521. font = this.page.commonObjs.getData(this.data.fontRefName);
  4522. }
  4523. this._setTextStyle(element, font);
  4524. }
  4525. if (this.data.textAlignment !== null) {
  4526. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4527. }
  4528. this.container.appendChild(element);
  4529. return this.container;
  4530. },
  4531. /**
  4532. * Apply text styles to the text in the element.
  4533. *
  4534. * @private
  4535. * @param {HTMLDivElement} element
  4536. * @param {Object} font
  4537. * @memberof TextWidgetAnnotationElement
  4538. */
  4539. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4540. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4541. var style = element.style;
  4542. style.fontSize = this.data.fontSize + 'px';
  4543. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4544. if (!font) {
  4545. return;
  4546. }
  4547. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4548. style.fontStyle = font.italic ? 'italic' : 'normal';
  4549. // Use a reasonable default font if the font doesn't specify a fallback.
  4550. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4551. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4552. style.fontFamily = fontFamily + fallbackName;
  4553. }
  4554. });
  4555. return TextWidgetAnnotationElement;
  4556. }();
  4557. /**
  4558. * @class
  4559. * @alias ChoiceWidgetAnnotationElement
  4560. */
  4561. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4562. function ChoiceWidgetAnnotationElement(parameters) {
  4563. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4564. }
  4565. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4566. /**
  4567. * Render the choice widget annotation's HTML element in the empty
  4568. * container.
  4569. *
  4570. * @public
  4571. * @memberof ChoiceWidgetAnnotationElement
  4572. * @returns {HTMLSectionElement}
  4573. */
  4574. render: function ChoiceWidgetAnnotationElement_render() {
  4575. this.container.className = 'choiceWidgetAnnotation';
  4576. var selectElement = document.createElement('select');
  4577. selectElement.disabled = this.data.readOnly;
  4578. if (!this.data.combo) {
  4579. // List boxes have a size and (optionally) multiple selection.
  4580. selectElement.size = this.data.options.length;
  4581. if (this.data.multiSelect) {
  4582. selectElement.multiple = true;
  4583. }
  4584. }
  4585. // Insert the options into the choice field.
  4586. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4587. var option = this.data.options[i];
  4588. var optionElement = document.createElement('option');
  4589. optionElement.textContent = option.displayValue;
  4590. optionElement.value = option.exportValue;
  4591. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4592. optionElement.setAttribute('selected', true);
  4593. }
  4594. selectElement.appendChild(optionElement);
  4595. }
  4596. this.container.appendChild(selectElement);
  4597. return this.container;
  4598. }
  4599. });
  4600. return ChoiceWidgetAnnotationElement;
  4601. }();
  4602. /**
  4603. * @class
  4604. * @alias PopupAnnotationElement
  4605. */
  4606. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4607. function PopupAnnotationElement(parameters) {
  4608. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4609. AnnotationElement.call(this, parameters, isRenderable);
  4610. }
  4611. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4612. /**
  4613. * Render the popup annotation's HTML element in the empty container.
  4614. *
  4615. * @public
  4616. * @memberof PopupAnnotationElement
  4617. * @returns {HTMLSectionElement}
  4618. */
  4619. render: function PopupAnnotationElement_render() {
  4620. this.container.className = 'popupAnnotation';
  4621. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4622. var parentElement = this.layer.querySelector(selector);
  4623. if (!parentElement) {
  4624. return this.container;
  4625. }
  4626. var popup = new PopupElement({
  4627. container: this.container,
  4628. trigger: parentElement,
  4629. color: this.data.color,
  4630. title: this.data.title,
  4631. contents: this.data.contents
  4632. });
  4633. // Position the popup next to the parent annotation's container.
  4634. // PDF viewers ignore a popup annotation's rectangle.
  4635. var parentLeft = parseFloat(parentElement.style.left);
  4636. var parentWidth = parseFloat(parentElement.style.width);
  4637. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4638. this.container.style.left = parentLeft + parentWidth + 'px';
  4639. this.container.appendChild(popup.render());
  4640. return this.container;
  4641. }
  4642. });
  4643. return PopupAnnotationElement;
  4644. }();
  4645. /**
  4646. * @class
  4647. * @alias PopupElement
  4648. */
  4649. var PopupElement = function PopupElementClosure() {
  4650. var BACKGROUND_ENLIGHT = 0.7;
  4651. function PopupElement(parameters) {
  4652. this.container = parameters.container;
  4653. this.trigger = parameters.trigger;
  4654. this.color = parameters.color;
  4655. this.title = parameters.title;
  4656. this.contents = parameters.contents;
  4657. this.hideWrapper = parameters.hideWrapper || false;
  4658. this.pinned = false;
  4659. }
  4660. PopupElement.prototype = /** @lends PopupElement.prototype */
  4661. {
  4662. /**
  4663. * Render the popup's HTML element.
  4664. *
  4665. * @public
  4666. * @memberof PopupElement
  4667. * @returns {HTMLSectionElement}
  4668. */
  4669. render: function PopupElement_render() {
  4670. var wrapper = document.createElement('div');
  4671. wrapper.className = 'popupWrapper';
  4672. // For Popup annotations we hide the entire section because it contains
  4673. // only the popup. However, for Text annotations without a separate Popup
  4674. // annotation, we cannot hide the entire container as the image would
  4675. // disappear too. In that special case, hiding the wrapper suffices.
  4676. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4677. this.hideElement.setAttribute('hidden', true);
  4678. var popup = document.createElement('div');
  4679. popup.className = 'popup';
  4680. var color = this.color;
  4681. if (color) {
  4682. // Enlighten the color.
  4683. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4684. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4685. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4686. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4687. }
  4688. var contents = this._formatContents(this.contents);
  4689. var title = document.createElement('h1');
  4690. title.textContent = this.title;
  4691. // Attach the event listeners to the trigger element.
  4692. this.trigger.addEventListener('click', this._toggle.bind(this));
  4693. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4694. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4695. popup.addEventListener('click', this._hide.bind(this, true));
  4696. popup.appendChild(title);
  4697. popup.appendChild(contents);
  4698. wrapper.appendChild(popup);
  4699. return wrapper;
  4700. },
  4701. /**
  4702. * Format the contents of the popup by adding newlines where necessary.
  4703. *
  4704. * @private
  4705. * @param {string} contents
  4706. * @memberof PopupElement
  4707. * @returns {HTMLParagraphElement}
  4708. */
  4709. _formatContents: function PopupElement_formatContents(contents) {
  4710. var p = document.createElement('p');
  4711. var lines = contents.split(/(?:\r\n?|\n)/);
  4712. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4713. var line = lines[i];
  4714. p.appendChild(document.createTextNode(line));
  4715. if (i < ii - 1) {
  4716. p.appendChild(document.createElement('br'));
  4717. }
  4718. }
  4719. return p;
  4720. },
  4721. /**
  4722. * Toggle the visibility of the popup.
  4723. *
  4724. * @private
  4725. * @memberof PopupElement
  4726. */
  4727. _toggle: function PopupElement_toggle() {
  4728. if (this.pinned) {
  4729. this._hide(true);
  4730. } else {
  4731. this._show(true);
  4732. }
  4733. },
  4734. /**
  4735. * Show the popup.
  4736. *
  4737. * @private
  4738. * @param {boolean} pin
  4739. * @memberof PopupElement
  4740. */
  4741. _show: function PopupElement_show(pin) {
  4742. if (pin) {
  4743. this.pinned = true;
  4744. }
  4745. if (this.hideElement.hasAttribute('hidden')) {
  4746. this.hideElement.removeAttribute('hidden');
  4747. this.container.style.zIndex += 1;
  4748. }
  4749. },
  4750. /**
  4751. * Hide the popup.
  4752. *
  4753. * @private
  4754. * @param {boolean} unpin
  4755. * @memberof PopupElement
  4756. */
  4757. _hide: function PopupElement_hide(unpin) {
  4758. if (unpin) {
  4759. this.pinned = false;
  4760. }
  4761. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4762. this.hideElement.setAttribute('hidden', true);
  4763. this.container.style.zIndex -= 1;
  4764. }
  4765. }
  4766. };
  4767. return PopupElement;
  4768. }();
  4769. /**
  4770. * @class
  4771. * @alias HighlightAnnotationElement
  4772. */
  4773. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4774. function HighlightAnnotationElement(parameters) {
  4775. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4776. AnnotationElement.call(this, parameters, isRenderable);
  4777. }
  4778. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4779. /**
  4780. * Render the highlight annotation's HTML element in the empty container.
  4781. *
  4782. * @public
  4783. * @memberof HighlightAnnotationElement
  4784. * @returns {HTMLSectionElement}
  4785. */
  4786. render: function HighlightAnnotationElement_render() {
  4787. this.container.className = 'highlightAnnotation';
  4788. if (!this.data.hasPopup) {
  4789. this._createPopup(this.container, null, this.data);
  4790. }
  4791. return this.container;
  4792. }
  4793. });
  4794. return HighlightAnnotationElement;
  4795. }();
  4796. /**
  4797. * @class
  4798. * @alias UnderlineAnnotationElement
  4799. */
  4800. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4801. function UnderlineAnnotationElement(parameters) {
  4802. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4803. AnnotationElement.call(this, parameters, isRenderable);
  4804. }
  4805. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4806. /**
  4807. * Render the underline annotation's HTML element in the empty container.
  4808. *
  4809. * @public
  4810. * @memberof UnderlineAnnotationElement
  4811. * @returns {HTMLSectionElement}
  4812. */
  4813. render: function UnderlineAnnotationElement_render() {
  4814. this.container.className = 'underlineAnnotation';
  4815. if (!this.data.hasPopup) {
  4816. this._createPopup(this.container, null, this.data);
  4817. }
  4818. return this.container;
  4819. }
  4820. });
  4821. return UnderlineAnnotationElement;
  4822. }();
  4823. /**
  4824. * @class
  4825. * @alias SquigglyAnnotationElement
  4826. */
  4827. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4828. function SquigglyAnnotationElement(parameters) {
  4829. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4830. AnnotationElement.call(this, parameters, isRenderable);
  4831. }
  4832. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4833. /**
  4834. * Render the squiggly annotation's HTML element in the empty container.
  4835. *
  4836. * @public
  4837. * @memberof SquigglyAnnotationElement
  4838. * @returns {HTMLSectionElement}
  4839. */
  4840. render: function SquigglyAnnotationElement_render() {
  4841. this.container.className = 'squigglyAnnotation';
  4842. if (!this.data.hasPopup) {
  4843. this._createPopup(this.container, null, this.data);
  4844. }
  4845. return this.container;
  4846. }
  4847. });
  4848. return SquigglyAnnotationElement;
  4849. }();
  4850. /**
  4851. * @class
  4852. * @alias StrikeOutAnnotationElement
  4853. */
  4854. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4855. function StrikeOutAnnotationElement(parameters) {
  4856. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4857. AnnotationElement.call(this, parameters, isRenderable);
  4858. }
  4859. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4860. /**
  4861. * Render the strikeout annotation's HTML element in the empty container.
  4862. *
  4863. * @public
  4864. * @memberof StrikeOutAnnotationElement
  4865. * @returns {HTMLSectionElement}
  4866. */
  4867. render: function StrikeOutAnnotationElement_render() {
  4868. this.container.className = 'strikeoutAnnotation';
  4869. if (!this.data.hasPopup) {
  4870. this._createPopup(this.container, null, this.data);
  4871. }
  4872. return this.container;
  4873. }
  4874. });
  4875. return StrikeOutAnnotationElement;
  4876. }();
  4877. /**
  4878. * @class
  4879. * @alias FileAttachmentAnnotationElement
  4880. */
  4881. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4882. function FileAttachmentAnnotationElement(parameters) {
  4883. AnnotationElement.call(this, parameters, true);
  4884. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4885. this.content = parameters.data.file.content;
  4886. }
  4887. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4888. /**
  4889. * Render the file attachment annotation's HTML element in the empty
  4890. * container.
  4891. *
  4892. * @public
  4893. * @memberof FileAttachmentAnnotationElement
  4894. * @returns {HTMLSectionElement}
  4895. */
  4896. render: function FileAttachmentAnnotationElement_render() {
  4897. this.container.className = 'fileAttachmentAnnotation';
  4898. var trigger = document.createElement('div');
  4899. trigger.style.height = this.container.style.height;
  4900. trigger.style.width = this.container.style.width;
  4901. trigger.addEventListener('dblclick', this._download.bind(this));
  4902. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4903. this._createPopup(this.container, trigger, this.data);
  4904. }
  4905. this.container.appendChild(trigger);
  4906. return this.container;
  4907. },
  4908. /**
  4909. * Download the file attachment associated with this annotation.
  4910. *
  4911. * @private
  4912. * @memberof FileAttachmentAnnotationElement
  4913. */
  4914. _download: function FileAttachmentAnnotationElement_download() {
  4915. if (!this.downloadManager) {
  4916. warn('Download cannot be started due to unavailable download manager');
  4917. return;
  4918. }
  4919. this.downloadManager.downloadData(this.content, this.filename, '');
  4920. }
  4921. });
  4922. return FileAttachmentAnnotationElement;
  4923. }();
  4924. /**
  4925. * @typedef {Object} AnnotationLayerParameters
  4926. * @property {PageViewport} viewport
  4927. * @property {HTMLDivElement} div
  4928. * @property {Array} annotations
  4929. * @property {PDFPage} page
  4930. * @property {IPDFLinkService} linkService
  4931. * @property {string} imageResourcesPath
  4932. * @property {boolean} renderInteractiveForms
  4933. */
  4934. /**
  4935. * @class
  4936. * @alias AnnotationLayer
  4937. */
  4938. var AnnotationLayer = function AnnotationLayerClosure() {
  4939. return {
  4940. /**
  4941. * Render a new annotation layer with all annotation elements.
  4942. *
  4943. * @public
  4944. * @param {AnnotationLayerParameters} parameters
  4945. * @memberof AnnotationLayer
  4946. */
  4947. render: function AnnotationLayer_render(parameters) {
  4948. var annotationElementFactory = new AnnotationElementFactory();
  4949. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4950. var data = parameters.annotations[i];
  4951. if (!data) {
  4952. continue;
  4953. }
  4954. var properties = {
  4955. data: data,
  4956. layer: parameters.div,
  4957. page: parameters.page,
  4958. viewport: parameters.viewport,
  4959. linkService: parameters.linkService,
  4960. downloadManager: parameters.downloadManager,
  4961. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4962. renderInteractiveForms: parameters.renderInteractiveForms || false
  4963. };
  4964. var element = annotationElementFactory.create(properties);
  4965. if (element.isRenderable) {
  4966. parameters.div.appendChild(element.render());
  4967. }
  4968. }
  4969. },
  4970. /**
  4971. * Update the annotation elements on existing annotation layer.
  4972. *
  4973. * @public
  4974. * @param {AnnotationLayerParameters} parameters
  4975. * @memberof AnnotationLayer
  4976. */
  4977. update: function AnnotationLayer_update(parameters) {
  4978. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4979. var data = parameters.annotations[i];
  4980. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4981. if (element) {
  4982. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4983. }
  4984. }
  4985. parameters.div.removeAttribute('hidden');
  4986. }
  4987. };
  4988. }();
  4989. exports.AnnotationLayer = AnnotationLayer;
  4990. }));
  4991. (function (root, factory) {
  4992. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4993. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4994. var Util = sharedUtil.Util;
  4995. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4996. var CustomStyle = displayDOMUtils.CustomStyle;
  4997. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4998. /**
  4999. * Text layer render parameters.
  5000. *
  5001. * @typedef {Object} TextLayerRenderParameters
  5002. * @property {TextContent} textContent - Text content to render (the object is
  5003. * returned by the page's getTextContent() method).
  5004. * @property {HTMLElement} container - HTML element that will contain text runs.
  5005. * @property {PageViewport} viewport - The target viewport to properly
  5006. * layout the text runs.
  5007. * @property {Array} textDivs - (optional) HTML elements that are correspond
  5008. * the text items of the textContent input. This is output and shall be
  5009. * initially be set to empty array.
  5010. * @property {number} timeout - (optional) Delay in milliseconds before
  5011. * rendering of the text runs occurs.
  5012. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  5013. * text selection enhancement.
  5014. */
  5015. var renderTextLayer = function renderTextLayerClosure() {
  5016. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  5017. var NonWhitespaceRegexp = /\S/;
  5018. function isAllWhitespace(str) {
  5019. return !NonWhitespaceRegexp.test(str);
  5020. }
  5021. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  5022. // creating many intermediate strings when building their 'style' properties.
  5023. var styleBuf = [
  5024. 'left: ',
  5025. 0,
  5026. 'px; top: ',
  5027. 0,
  5028. 'px; font-size: ',
  5029. 0,
  5030. 'px; font-family: ',
  5031. '',
  5032. ';'
  5033. ];
  5034. function appendText(task, geom, styles) {
  5035. // Initialize all used properties to keep the caches monomorphic.
  5036. var textDiv = document.createElement('div');
  5037. var textDivProperties = {
  5038. style: null,
  5039. angle: 0,
  5040. canvasWidth: 0,
  5041. isWhitespace: false,
  5042. originalTransform: null,
  5043. paddingBottom: 0,
  5044. paddingLeft: 0,
  5045. paddingRight: 0,
  5046. paddingTop: 0,
  5047. scale: 1
  5048. };
  5049. task._textDivs.push(textDiv);
  5050. if (isAllWhitespace(geom.str)) {
  5051. textDivProperties.isWhitespace = true;
  5052. task._textDivProperties.set(textDiv, textDivProperties);
  5053. return;
  5054. }
  5055. var tx = Util.transform(task._viewport.transform, geom.transform);
  5056. var angle = Math.atan2(tx[1], tx[0]);
  5057. var style = styles[geom.fontName];
  5058. if (style.vertical) {
  5059. angle += Math.PI / 2;
  5060. }
  5061. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  5062. var fontAscent = fontHeight;
  5063. if (style.ascent) {
  5064. fontAscent = style.ascent * fontAscent;
  5065. } else if (style.descent) {
  5066. fontAscent = (1 + style.descent) * fontAscent;
  5067. }
  5068. var left;
  5069. var top;
  5070. if (angle === 0) {
  5071. left = tx[4];
  5072. top = tx[5] - fontAscent;
  5073. } else {
  5074. left = tx[4] + fontAscent * Math.sin(angle);
  5075. top = tx[5] - fontAscent * Math.cos(angle);
  5076. }
  5077. styleBuf[1] = left;
  5078. styleBuf[3] = top;
  5079. styleBuf[5] = fontHeight;
  5080. styleBuf[7] = style.fontFamily;
  5081. textDivProperties.style = styleBuf.join('');
  5082. textDiv.setAttribute('style', textDivProperties.style);
  5083. textDiv.textContent = geom.str;
  5084. // |fontName| is only used by the Font Inspector. This test will succeed
  5085. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  5086. // not worth the effort to do a more accurate test. We only use `dataset`
  5087. // here to make the font name available for the debugger.
  5088. if (getDefaultSetting('pdfBug')) {
  5089. textDiv.dataset.fontName = geom.fontName;
  5090. }
  5091. if (angle !== 0) {
  5092. textDivProperties.angle = angle * (180 / Math.PI);
  5093. }
  5094. // We don't bother scaling single-char text divs, because it has very
  5095. // little effect on text highlighting. This makes scrolling on docs with
  5096. // lots of such divs a lot faster.
  5097. if (geom.str.length > 1) {
  5098. if (style.vertical) {
  5099. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  5100. } else {
  5101. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  5102. }
  5103. }
  5104. task._textDivProperties.set(textDiv, textDivProperties);
  5105. if (task._enhanceTextSelection) {
  5106. var angleCos = 1, angleSin = 0;
  5107. if (angle !== 0) {
  5108. angleCos = Math.cos(angle);
  5109. angleSin = Math.sin(angle);
  5110. }
  5111. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  5112. var divHeight = fontHeight;
  5113. var m, b;
  5114. if (angle !== 0) {
  5115. m = [
  5116. angleCos,
  5117. angleSin,
  5118. -angleSin,
  5119. angleCos,
  5120. left,
  5121. top
  5122. ];
  5123. b = Util.getAxialAlignedBoundingBox([
  5124. 0,
  5125. 0,
  5126. divWidth,
  5127. divHeight
  5128. ], m);
  5129. } else {
  5130. b = [
  5131. left,
  5132. top,
  5133. left + divWidth,
  5134. top + divHeight
  5135. ];
  5136. }
  5137. task._bounds.push({
  5138. left: b[0],
  5139. top: b[1],
  5140. right: b[2],
  5141. bottom: b[3],
  5142. div: textDiv,
  5143. size: [
  5144. divWidth,
  5145. divHeight
  5146. ],
  5147. m: m
  5148. });
  5149. }
  5150. }
  5151. function render(task) {
  5152. if (task._canceled) {
  5153. return;
  5154. }
  5155. var textLayerFrag = task._container;
  5156. var textDivs = task._textDivs;
  5157. var capability = task._capability;
  5158. var textDivsLength = textDivs.length;
  5159. // No point in rendering many divs as it would make the browser
  5160. // unusable even after the divs are rendered.
  5161. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  5162. task._renderingDone = true;
  5163. capability.resolve();
  5164. return;
  5165. }
  5166. var canvas = document.createElement('canvas');
  5167. canvas.mozOpaque = true;
  5168. var ctx = canvas.getContext('2d', { alpha: false });
  5169. var lastFontSize;
  5170. var lastFontFamily;
  5171. for (var i = 0; i < textDivsLength; i++) {
  5172. var textDiv = textDivs[i];
  5173. var textDivProperties = task._textDivProperties.get(textDiv);
  5174. if (textDivProperties.isWhitespace) {
  5175. continue;
  5176. }
  5177. var fontSize = textDiv.style.fontSize;
  5178. var fontFamily = textDiv.style.fontFamily;
  5179. // Only build font string and set to context if different from last.
  5180. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  5181. ctx.font = fontSize + ' ' + fontFamily;
  5182. lastFontSize = fontSize;
  5183. lastFontFamily = fontFamily;
  5184. }
  5185. var width = ctx.measureText(textDiv.textContent).width;
  5186. textLayerFrag.appendChild(textDiv);
  5187. var transform = '';
  5188. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  5189. textDivProperties.scale = textDivProperties.canvasWidth / width;
  5190. transform = 'scaleX(' + textDivProperties.scale + ')';
  5191. }
  5192. if (textDivProperties.angle !== 0) {
  5193. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  5194. }
  5195. if (transform !== '') {
  5196. textDivProperties.originalTransform = transform;
  5197. CustomStyle.setProp('transform', textDiv, transform);
  5198. }
  5199. task._textDivProperties.set(textDiv, textDivProperties);
  5200. }
  5201. task._renderingDone = true;
  5202. capability.resolve();
  5203. }
  5204. function expand(task) {
  5205. var bounds = task._bounds;
  5206. var viewport = task._viewport;
  5207. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  5208. for (var i = 0; i < expanded.length; i++) {
  5209. var div = bounds[i].div;
  5210. var divProperties = task._textDivProperties.get(div);
  5211. if (divProperties.angle === 0) {
  5212. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  5213. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  5214. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  5215. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  5216. task._textDivProperties.set(div, divProperties);
  5217. continue;
  5218. }
  5219. // Box is rotated -- trying to find padding so rotated div will not
  5220. // exceed its expanded bounds.
  5221. var e = expanded[i], b = bounds[i];
  5222. var m = b.m, c = m[0], s = m[1];
  5223. // Finding intersections with expanded box.
  5224. var points = [
  5225. [
  5226. 0,
  5227. 0
  5228. ],
  5229. [
  5230. 0,
  5231. b.size[1]
  5232. ],
  5233. [
  5234. b.size[0],
  5235. 0
  5236. ],
  5237. b.size
  5238. ];
  5239. var ts = new Float64Array(64);
  5240. points.forEach(function (p, i) {
  5241. var t = Util.applyTransform(p, m);
  5242. ts[i + 0] = c && (e.left - t[0]) / c;
  5243. ts[i + 4] = s && (e.top - t[1]) / s;
  5244. ts[i + 8] = c && (e.right - t[0]) / c;
  5245. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5246. ts[i + 16] = s && (e.left - t[0]) / -s;
  5247. ts[i + 20] = c && (e.top - t[1]) / c;
  5248. ts[i + 24] = s && (e.right - t[0]) / -s;
  5249. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5250. ts[i + 32] = c && (e.left - t[0]) / -c;
  5251. ts[i + 36] = s && (e.top - t[1]) / -s;
  5252. ts[i + 40] = c && (e.right - t[0]) / -c;
  5253. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5254. ts[i + 48] = s && (e.left - t[0]) / s;
  5255. ts[i + 52] = c && (e.top - t[1]) / -c;
  5256. ts[i + 56] = s && (e.right - t[0]) / s;
  5257. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5258. });
  5259. var findPositiveMin = function (ts, offset, count) {
  5260. var result = 0;
  5261. for (var i = 0; i < count; i++) {
  5262. var t = ts[offset++];
  5263. if (t > 0) {
  5264. result = result ? Math.min(t, result) : t;
  5265. }
  5266. }
  5267. return result;
  5268. };
  5269. // Not based on math, but to simplify calculations, using cos and sin
  5270. // absolute values to not exceed the box (it can but insignificantly).
  5271. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5272. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5273. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5274. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5275. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5276. task._textDivProperties.set(div, divProperties);
  5277. }
  5278. }
  5279. function expandBounds(width, height, boxes) {
  5280. var bounds = boxes.map(function (box, i) {
  5281. return {
  5282. x1: box.left,
  5283. y1: box.top,
  5284. x2: box.right,
  5285. y2: box.bottom,
  5286. index: i,
  5287. x1New: undefined,
  5288. x2New: undefined
  5289. };
  5290. });
  5291. expandBoundsLTR(width, bounds);
  5292. var expanded = new Array(boxes.length);
  5293. bounds.forEach(function (b) {
  5294. var i = b.index;
  5295. expanded[i] = {
  5296. left: b.x1New,
  5297. top: 0,
  5298. right: b.x2New,
  5299. bottom: 0
  5300. };
  5301. });
  5302. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5303. // array and objects.
  5304. boxes.map(function (box, i) {
  5305. var e = expanded[i], b = bounds[i];
  5306. b.x1 = box.top;
  5307. b.y1 = width - e.right;
  5308. b.x2 = box.bottom;
  5309. b.y2 = width - e.left;
  5310. b.index = i;
  5311. b.x1New = undefined;
  5312. b.x2New = undefined;
  5313. });
  5314. expandBoundsLTR(height, bounds);
  5315. bounds.forEach(function (b) {
  5316. var i = b.index;
  5317. expanded[i].top = b.x1New;
  5318. expanded[i].bottom = b.x2New;
  5319. });
  5320. return expanded;
  5321. }
  5322. function expandBoundsLTR(width, bounds) {
  5323. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5324. bounds.sort(function (a, b) {
  5325. return a.x1 - b.x1 || a.index - b.index;
  5326. });
  5327. // First we see on the horizon is a fake boundary.
  5328. var fakeBoundary = {
  5329. x1: -Infinity,
  5330. y1: -Infinity,
  5331. x2: 0,
  5332. y2: Infinity,
  5333. index: -1,
  5334. x1New: 0,
  5335. x2New: 0
  5336. };
  5337. var horizon = [{
  5338. start: -Infinity,
  5339. end: Infinity,
  5340. boundary: fakeBoundary
  5341. }];
  5342. bounds.forEach(function (boundary) {
  5343. // Searching for the affected part of horizon.
  5344. // TODO red-black tree or simple binary search
  5345. var i = 0;
  5346. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5347. i++;
  5348. }
  5349. var j = horizon.length - 1;
  5350. while (j >= 0 && horizon[j].start >= boundary.y2) {
  5351. j--;
  5352. }
  5353. var horizonPart, affectedBoundary;
  5354. var q, k, maxXNew = -Infinity;
  5355. for (q = i; q <= j; q++) {
  5356. horizonPart = horizon[q];
  5357. affectedBoundary = horizonPart.boundary;
  5358. var xNew;
  5359. if (affectedBoundary.x2 > boundary.x1) {
  5360. // In the middle of the previous element, new x shall be at the
  5361. // boundary start. Extending if further if the affected bondary
  5362. // placed on top of the current one.
  5363. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  5364. } else if (affectedBoundary.x2New === undefined) {
  5365. // We have some space in between, new x in middle will be a fair
  5366. // choice.
  5367. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5368. } else {
  5369. // Affected boundary has x2new set, using it as new x.
  5370. xNew = affectedBoundary.x2New;
  5371. }
  5372. if (xNew > maxXNew) {
  5373. maxXNew = xNew;
  5374. }
  5375. }
  5376. // Set new x1 for current boundary.
  5377. boundary.x1New = maxXNew;
  5378. // Adjusts new x2 for the affected boundaries.
  5379. for (q = i; q <= j; q++) {
  5380. horizonPart = horizon[q];
  5381. affectedBoundary = horizonPart.boundary;
  5382. if (affectedBoundary.x2New === undefined) {
  5383. // Was not set yet, choosing new x if possible.
  5384. if (affectedBoundary.x2 > boundary.x1) {
  5385. // Current and affected boundaries intersect. If affected boundary
  5386. // is placed on top of the current, shrinking the affected.
  5387. if (affectedBoundary.index > boundary.index) {
  5388. affectedBoundary.x2New = affectedBoundary.x2;
  5389. }
  5390. } else {
  5391. affectedBoundary.x2New = maxXNew;
  5392. }
  5393. } else if (affectedBoundary.x2New > maxXNew) {
  5394. // Affected boundary is touching new x, pushing it back.
  5395. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5396. }
  5397. }
  5398. // Fixing the horizon.
  5399. var changedHorizon = [], lastBoundary = null;
  5400. for (q = i; q <= j; q++) {
  5401. horizonPart = horizon[q];
  5402. affectedBoundary = horizonPart.boundary;
  5403. // Checking which boundary will be visible.
  5404. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  5405. if (lastBoundary === useBoundary) {
  5406. // Merging with previous.
  5407. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5408. } else {
  5409. changedHorizon.push({
  5410. start: horizonPart.start,
  5411. end: horizonPart.end,
  5412. boundary: useBoundary
  5413. });
  5414. lastBoundary = useBoundary;
  5415. }
  5416. }
  5417. if (horizon[i].start < boundary.y1) {
  5418. changedHorizon[0].start = boundary.y1;
  5419. changedHorizon.unshift({
  5420. start: horizon[i].start,
  5421. end: boundary.y1,
  5422. boundary: horizon[i].boundary
  5423. });
  5424. }
  5425. if (boundary.y2 < horizon[j].end) {
  5426. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5427. changedHorizon.push({
  5428. start: boundary.y2,
  5429. end: horizon[j].end,
  5430. boundary: horizon[j].boundary
  5431. });
  5432. }
  5433. // Set x2 new of boundary that is no longer visible (see overlapping case
  5434. // above).
  5435. // TODO more efficient, e.g. via reference counting.
  5436. for (q = i; q <= j; q++) {
  5437. horizonPart = horizon[q];
  5438. affectedBoundary = horizonPart.boundary;
  5439. if (affectedBoundary.x2New !== undefined) {
  5440. continue;
  5441. }
  5442. var used = false;
  5443. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  5444. used = horizon[k].boundary === affectedBoundary;
  5445. }
  5446. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  5447. used = horizon[k].boundary === affectedBoundary;
  5448. }
  5449. for (k = 0; !used && k < changedHorizon.length; k++) {
  5450. used = changedHorizon[k].boundary === affectedBoundary;
  5451. }
  5452. if (!used) {
  5453. affectedBoundary.x2New = maxXNew;
  5454. }
  5455. }
  5456. Array.prototype.splice.apply(horizon, [
  5457. i,
  5458. j - i + 1
  5459. ].concat(changedHorizon));
  5460. });
  5461. // Set new x2 for all unset boundaries.
  5462. horizon.forEach(function (horizonPart) {
  5463. var affectedBoundary = horizonPart.boundary;
  5464. if (affectedBoundary.x2New === undefined) {
  5465. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5466. }
  5467. });
  5468. }
  5469. /**
  5470. * Text layer rendering task.
  5471. *
  5472. * @param {TextContent} textContent
  5473. * @param {HTMLElement} container
  5474. * @param {PageViewport} viewport
  5475. * @param {Array} textDivs
  5476. * @param {boolean} enhanceTextSelection
  5477. * @private
  5478. */
  5479. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  5480. this._textContent = textContent;
  5481. this._container = container;
  5482. this._viewport = viewport;
  5483. this._textDivs = textDivs || [];
  5484. this._textDivProperties = new WeakMap();
  5485. this._renderingDone = false;
  5486. this._canceled = false;
  5487. this._capability = createPromiseCapability();
  5488. this._renderTimer = null;
  5489. this._bounds = [];
  5490. this._enhanceTextSelection = !!enhanceTextSelection;
  5491. }
  5492. TextLayerRenderTask.prototype = {
  5493. get promise() {
  5494. return this._capability.promise;
  5495. },
  5496. cancel: function TextLayer_cancel() {
  5497. this._canceled = true;
  5498. if (this._renderTimer !== null) {
  5499. clearTimeout(this._renderTimer);
  5500. this._renderTimer = null;
  5501. }
  5502. this._capability.reject('canceled');
  5503. },
  5504. _render: function TextLayer_render(timeout) {
  5505. var textItems = this._textContent.items;
  5506. var textStyles = this._textContent.styles;
  5507. for (var i = 0, len = textItems.length; i < len; i++) {
  5508. appendText(this, textItems[i], textStyles);
  5509. }
  5510. if (!timeout) {
  5511. // Render right away
  5512. render(this);
  5513. } else {
  5514. // Schedule
  5515. var self = this;
  5516. this._renderTimer = setTimeout(function () {
  5517. render(self);
  5518. self._renderTimer = null;
  5519. }, timeout);
  5520. }
  5521. },
  5522. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5523. if (!this._enhanceTextSelection || !this._renderingDone) {
  5524. return;
  5525. }
  5526. if (this._bounds !== null) {
  5527. expand(this);
  5528. this._bounds = null;
  5529. }
  5530. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5531. var div = this._textDivs[i];
  5532. var divProperties = this._textDivProperties.get(div);
  5533. if (divProperties.isWhitespace) {
  5534. continue;
  5535. }
  5536. if (expandDivs) {
  5537. var transform = '', padding = '';
  5538. if (divProperties.scale !== 1) {
  5539. transform = 'scaleX(' + divProperties.scale + ')';
  5540. }
  5541. if (divProperties.angle !== 0) {
  5542. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5543. }
  5544. if (divProperties.paddingLeft !== 0) {
  5545. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  5546. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  5547. }
  5548. if (divProperties.paddingTop !== 0) {
  5549. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5550. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  5551. }
  5552. if (divProperties.paddingRight !== 0) {
  5553. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  5554. }
  5555. if (divProperties.paddingBottom !== 0) {
  5556. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  5557. }
  5558. if (padding !== '') {
  5559. div.setAttribute('style', divProperties.style + padding);
  5560. }
  5561. if (transform !== '') {
  5562. CustomStyle.setProp('transform', div, transform);
  5563. }
  5564. } else {
  5565. div.style.padding = 0;
  5566. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  5567. }
  5568. }
  5569. }
  5570. };
  5571. /**
  5572. * Starts rendering of the text layer.
  5573. *
  5574. * @param {TextLayerRenderParameters} renderParameters
  5575. * @returns {TextLayerRenderTask}
  5576. */
  5577. function renderTextLayer(renderParameters) {
  5578. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  5579. task._render(renderParameters.timeout);
  5580. return task;
  5581. }
  5582. return renderTextLayer;
  5583. }();
  5584. exports.renderTextLayer = renderTextLayer;
  5585. }));
  5586. (function (root, factory) {
  5587. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  5588. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5589. var shadow = sharedUtil.shadow;
  5590. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5591. var WebGLUtils = function WebGLUtilsClosure() {
  5592. function loadShader(gl, code, shaderType) {
  5593. var shader = gl.createShader(shaderType);
  5594. gl.shaderSource(shader, code);
  5595. gl.compileShader(shader);
  5596. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5597. if (!compiled) {
  5598. var errorMsg = gl.getShaderInfoLog(shader);
  5599. throw new Error('Error during shader compilation: ' + errorMsg);
  5600. }
  5601. return shader;
  5602. }
  5603. function createVertexShader(gl, code) {
  5604. return loadShader(gl, code, gl.VERTEX_SHADER);
  5605. }
  5606. function createFragmentShader(gl, code) {
  5607. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5608. }
  5609. function createProgram(gl, shaders) {
  5610. var program = gl.createProgram();
  5611. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5612. gl.attachShader(program, shaders[i]);
  5613. }
  5614. gl.linkProgram(program);
  5615. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5616. if (!linked) {
  5617. var errorMsg = gl.getProgramInfoLog(program);
  5618. throw new Error('Error during program linking: ' + errorMsg);
  5619. }
  5620. return program;
  5621. }
  5622. function createTexture(gl, image, textureId) {
  5623. gl.activeTexture(textureId);
  5624. var texture = gl.createTexture();
  5625. gl.bindTexture(gl.TEXTURE_2D, texture);
  5626. // Set the parameters so we can render any size image.
  5627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5631. // Upload the image into the texture.
  5632. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5633. return texture;
  5634. }
  5635. var currentGL, currentCanvas;
  5636. function generateGL() {
  5637. if (currentGL) {
  5638. return;
  5639. }
  5640. currentCanvas = document.createElement('canvas');
  5641. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  5642. }
  5643. var smaskVertexShaderCode = '\
  5644. attribute vec2 a_position; \
  5645. attribute vec2 a_texCoord; \
  5646. \
  5647. uniform vec2 u_resolution; \
  5648. \
  5649. varying vec2 v_texCoord; \
  5650. \
  5651. void main() { \
  5652. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5653. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5654. \
  5655. v_texCoord = a_texCoord; \
  5656. } ';
  5657. var smaskFragmentShaderCode = '\
  5658. precision mediump float; \
  5659. \
  5660. uniform vec4 u_backdrop; \
  5661. uniform int u_subtype; \
  5662. uniform sampler2D u_image; \
  5663. uniform sampler2D u_mask; \
  5664. \
  5665. varying vec2 v_texCoord; \
  5666. \
  5667. void main() { \
  5668. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5669. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5670. if (u_backdrop.a > 0.0) { \
  5671. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5672. u_backdrop.rgb * (1.0 - maskColor.a); \
  5673. } \
  5674. float lum; \
  5675. if (u_subtype == 0) { \
  5676. lum = maskColor.a; \
  5677. } else { \
  5678. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5679. maskColor.b * 0.11; \
  5680. } \
  5681. imageColor.a *= lum; \
  5682. imageColor.rgb *= imageColor.a; \
  5683. gl_FragColor = imageColor; \
  5684. } ';
  5685. var smaskCache = null;
  5686. function initSmaskGL() {
  5687. var canvas, gl;
  5688. generateGL();
  5689. canvas = currentCanvas;
  5690. currentCanvas = null;
  5691. gl = currentGL;
  5692. currentGL = null;
  5693. // setup a GLSL program
  5694. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5695. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5696. var program = createProgram(gl, [
  5697. vertexShader,
  5698. fragmentShader
  5699. ]);
  5700. gl.useProgram(program);
  5701. var cache = {};
  5702. cache.gl = gl;
  5703. cache.canvas = canvas;
  5704. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5705. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5706. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5707. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5708. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5709. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5710. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5711. // provide texture coordinates for the rectangle.
  5712. var texCoordBuffer = gl.createBuffer();
  5713. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5714. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5715. 0.0,
  5716. 0.0,
  5717. 1.0,
  5718. 0.0,
  5719. 0.0,
  5720. 1.0,
  5721. 0.0,
  5722. 1.0,
  5723. 1.0,
  5724. 0.0,
  5725. 1.0,
  5726. 1.0
  5727. ]), gl.STATIC_DRAW);
  5728. gl.enableVertexAttribArray(texCoordLocation);
  5729. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5730. gl.uniform1i(texLayerLocation, 0);
  5731. gl.uniform1i(texMaskLocation, 1);
  5732. smaskCache = cache;
  5733. }
  5734. function composeSMask(layer, mask, properties) {
  5735. var width = layer.width, height = layer.height;
  5736. if (!smaskCache) {
  5737. initSmaskGL();
  5738. }
  5739. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5740. canvas.width = width;
  5741. canvas.height = height;
  5742. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5743. gl.uniform2f(cache.resolutionLocation, width, height);
  5744. if (properties.backdrop) {
  5745. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5746. } else {
  5747. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5748. }
  5749. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5750. // Create a textures
  5751. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5752. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5753. // Create a buffer and put a single clipspace rectangle in
  5754. // it (2 triangles)
  5755. var buffer = gl.createBuffer();
  5756. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5757. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5758. 0,
  5759. 0,
  5760. width,
  5761. 0,
  5762. 0,
  5763. height,
  5764. 0,
  5765. height,
  5766. width,
  5767. 0,
  5768. width,
  5769. height
  5770. ]), gl.STATIC_DRAW);
  5771. gl.enableVertexAttribArray(cache.positionLocation);
  5772. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5773. // draw
  5774. gl.clearColor(0, 0, 0, 0);
  5775. gl.enable(gl.BLEND);
  5776. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5777. gl.clear(gl.COLOR_BUFFER_BIT);
  5778. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5779. gl.flush();
  5780. gl.deleteTexture(texture);
  5781. gl.deleteTexture(maskTexture);
  5782. gl.deleteBuffer(buffer);
  5783. return canvas;
  5784. }
  5785. var figuresVertexShaderCode = '\
  5786. attribute vec2 a_position; \
  5787. attribute vec3 a_color; \
  5788. \
  5789. uniform vec2 u_resolution; \
  5790. uniform vec2 u_scale; \
  5791. uniform vec2 u_offset; \
  5792. \
  5793. varying vec4 v_color; \
  5794. \
  5795. void main() { \
  5796. vec2 position = (a_position + u_offset) * u_scale; \
  5797. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5798. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5799. \
  5800. v_color = vec4(a_color / 255.0, 1.0); \
  5801. } ';
  5802. var figuresFragmentShaderCode = '\
  5803. precision mediump float; \
  5804. \
  5805. varying vec4 v_color; \
  5806. \
  5807. void main() { \
  5808. gl_FragColor = v_color; \
  5809. } ';
  5810. var figuresCache = null;
  5811. function initFiguresGL() {
  5812. var canvas, gl;
  5813. generateGL();
  5814. canvas = currentCanvas;
  5815. currentCanvas = null;
  5816. gl = currentGL;
  5817. currentGL = null;
  5818. // setup a GLSL program
  5819. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5820. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5821. var program = createProgram(gl, [
  5822. vertexShader,
  5823. fragmentShader
  5824. ]);
  5825. gl.useProgram(program);
  5826. var cache = {};
  5827. cache.gl = gl;
  5828. cache.canvas = canvas;
  5829. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5830. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5831. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5832. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5833. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5834. figuresCache = cache;
  5835. }
  5836. function drawFigures(width, height, backgroundColor, figures, context) {
  5837. if (!figuresCache) {
  5838. initFiguresGL();
  5839. }
  5840. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5841. canvas.width = width;
  5842. canvas.height = height;
  5843. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5844. gl.uniform2f(cache.resolutionLocation, width, height);
  5845. // count triangle points
  5846. var count = 0;
  5847. var i, ii, rows;
  5848. for (i = 0, ii = figures.length; i < ii; i++) {
  5849. switch (figures[i].type) {
  5850. case 'lattice':
  5851. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5852. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5853. break;
  5854. case 'triangles':
  5855. count += figures[i].coords.length;
  5856. break;
  5857. }
  5858. }
  5859. // transfer data
  5860. var coords = new Float32Array(count * 2);
  5861. var colors = new Uint8Array(count * 3);
  5862. var coordsMap = context.coords, colorsMap = context.colors;
  5863. var pIndex = 0, cIndex = 0;
  5864. for (i = 0, ii = figures.length; i < ii; i++) {
  5865. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5866. switch (figure.type) {
  5867. case 'lattice':
  5868. var cols = figure.verticesPerRow;
  5869. rows = ps.length / cols | 0;
  5870. for (var row = 1; row < rows; row++) {
  5871. var offset = row * cols + 1;
  5872. for (var col = 1; col < cols; col++, offset++) {
  5873. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5874. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5875. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5876. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5877. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5878. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5879. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5880. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5881. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5882. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5883. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5884. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5885. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5886. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5887. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5888. coords[pIndex + 6] = coords[pIndex + 2];
  5889. coords[pIndex + 7] = coords[pIndex + 3];
  5890. coords[pIndex + 8] = coords[pIndex + 4];
  5891. coords[pIndex + 9] = coords[pIndex + 5];
  5892. coords[pIndex + 10] = coordsMap[ps[offset]];
  5893. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5894. colors[cIndex + 9] = colors[cIndex + 3];
  5895. colors[cIndex + 10] = colors[cIndex + 4];
  5896. colors[cIndex + 11] = colors[cIndex + 5];
  5897. colors[cIndex + 12] = colors[cIndex + 6];
  5898. colors[cIndex + 13] = colors[cIndex + 7];
  5899. colors[cIndex + 14] = colors[cIndex + 8];
  5900. colors[cIndex + 15] = colorsMap[cs[offset]];
  5901. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5902. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5903. pIndex += 12;
  5904. cIndex += 18;
  5905. }
  5906. }
  5907. break;
  5908. case 'triangles':
  5909. for (var j = 0, jj = ps.length; j < jj; j++) {
  5910. coords[pIndex] = coordsMap[ps[j]];
  5911. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5912. colors[cIndex] = colorsMap[cs[j]];
  5913. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5914. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5915. pIndex += 2;
  5916. cIndex += 3;
  5917. }
  5918. break;
  5919. }
  5920. }
  5921. // draw
  5922. if (backgroundColor) {
  5923. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5924. } else {
  5925. gl.clearColor(0, 0, 0, 0);
  5926. }
  5927. gl.clear(gl.COLOR_BUFFER_BIT);
  5928. var coordsBuffer = gl.createBuffer();
  5929. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5930. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5931. gl.enableVertexAttribArray(cache.positionLocation);
  5932. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5933. var colorsBuffer = gl.createBuffer();
  5934. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5935. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5936. gl.enableVertexAttribArray(cache.colorLocation);
  5937. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5938. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5939. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5940. gl.drawArrays(gl.TRIANGLES, 0, count);
  5941. gl.flush();
  5942. gl.deleteBuffer(coordsBuffer);
  5943. gl.deleteBuffer(colorsBuffer);
  5944. return canvas;
  5945. }
  5946. function cleanup() {
  5947. if (smaskCache && smaskCache.canvas) {
  5948. smaskCache.canvas.width = 0;
  5949. smaskCache.canvas.height = 0;
  5950. }
  5951. if (figuresCache && figuresCache.canvas) {
  5952. figuresCache.canvas.width = 0;
  5953. figuresCache.canvas.height = 0;
  5954. }
  5955. smaskCache = null;
  5956. figuresCache = null;
  5957. }
  5958. return {
  5959. get isEnabled() {
  5960. if (getDefaultSetting('disableWebGL')) {
  5961. return false;
  5962. }
  5963. var enabled = false;
  5964. try {
  5965. generateGL();
  5966. enabled = !!currentGL;
  5967. } catch (e) {
  5968. }
  5969. return shadow(this, 'isEnabled', enabled);
  5970. },
  5971. composeSMask: composeSMask,
  5972. drawFigures: drawFigures,
  5973. clear: cleanup
  5974. };
  5975. }();
  5976. exports.WebGLUtils = WebGLUtils;
  5977. }));
  5978. (function (root, factory) {
  5979. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5980. }(this, function (exports, sharedUtil, displayWebGL) {
  5981. var Util = sharedUtil.Util;
  5982. var info = sharedUtil.info;
  5983. var isArray = sharedUtil.isArray;
  5984. var error = sharedUtil.error;
  5985. var WebGLUtils = displayWebGL.WebGLUtils;
  5986. var ShadingIRs = {};
  5987. ShadingIRs.RadialAxial = {
  5988. fromIR: function RadialAxial_fromIR(raw) {
  5989. var type = raw[1];
  5990. var colorStops = raw[2];
  5991. var p0 = raw[3];
  5992. var p1 = raw[4];
  5993. var r0 = raw[5];
  5994. var r1 = raw[6];
  5995. return {
  5996. type: 'Pattern',
  5997. getPattern: function RadialAxial_getPattern(ctx) {
  5998. var grad;
  5999. if (type === 'axial') {
  6000. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  6001. } else if (type === 'radial') {
  6002. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  6003. }
  6004. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  6005. var c = colorStops[i];
  6006. grad.addColorStop(c[0], c[1]);
  6007. }
  6008. return grad;
  6009. }
  6010. };
  6011. }
  6012. };
  6013. var createMeshCanvas = function createMeshCanvasClosure() {
  6014. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  6015. // Very basic Gouraud-shaded triangle rasterization algorithm.
  6016. var coords = context.coords, colors = context.colors;
  6017. var bytes = data.data, rowSize = data.width * 4;
  6018. var tmp;
  6019. if (coords[p1 + 1] > coords[p2 + 1]) {
  6020. tmp = p1;
  6021. p1 = p2;
  6022. p2 = tmp;
  6023. tmp = c1;
  6024. c1 = c2;
  6025. c2 = tmp;
  6026. }
  6027. if (coords[p2 + 1] > coords[p3 + 1]) {
  6028. tmp = p2;
  6029. p2 = p3;
  6030. p3 = tmp;
  6031. tmp = c2;
  6032. c2 = c3;
  6033. c3 = tmp;
  6034. }
  6035. if (coords[p1 + 1] > coords[p2 + 1]) {
  6036. tmp = p1;
  6037. p1 = p2;
  6038. p2 = tmp;
  6039. tmp = c1;
  6040. c1 = c2;
  6041. c2 = tmp;
  6042. }
  6043. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6044. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6045. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6046. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6047. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6048. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6049. if (y1 >= y3) {
  6050. return;
  6051. }
  6052. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  6053. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  6054. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  6055. var minY = Math.round(y1), maxY = Math.round(y3);
  6056. var xa, car, cag, cab;
  6057. var xb, cbr, cbg, cbb;
  6058. var k;
  6059. for (var y = minY; y <= maxY; y++) {
  6060. if (y < y2) {
  6061. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  6062. xa = x1 - (x1 - x2) * k;
  6063. car = c1r - (c1r - c2r) * k;
  6064. cag = c1g - (c1g - c2g) * k;
  6065. cab = c1b - (c1b - c2b) * k;
  6066. } else {
  6067. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  6068. xa = x2 - (x2 - x3) * k;
  6069. car = c2r - (c2r - c3r) * k;
  6070. cag = c2g - (c2g - c3g) * k;
  6071. cab = c2b - (c2b - c3b) * k;
  6072. }
  6073. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  6074. xb = x1 - (x1 - x3) * k;
  6075. cbr = c1r - (c1r - c3r) * k;
  6076. cbg = c1g - (c1g - c3g) * k;
  6077. cbb = c1b - (c1b - c3b) * k;
  6078. var x1_ = Math.round(Math.min(xa, xb));
  6079. var x2_ = Math.round(Math.max(xa, xb));
  6080. var j = rowSize * y + x1_ * 4;
  6081. for (var x = x1_; x <= x2_; x++) {
  6082. k = (xa - x) / (xa - xb);
  6083. k = k < 0 ? 0 : k > 1 ? 1 : k;
  6084. bytes[j++] = car - (car - cbr) * k | 0;
  6085. bytes[j++] = cag - (cag - cbg) * k | 0;
  6086. bytes[j++] = cab - (cab - cbb) * k | 0;
  6087. bytes[j++] = 255;
  6088. }
  6089. }
  6090. }
  6091. function drawFigure(data, figure, context) {
  6092. var ps = figure.coords;
  6093. var cs = figure.colors;
  6094. var i, ii;
  6095. switch (figure.type) {
  6096. case 'lattice':
  6097. var verticesPerRow = figure.verticesPerRow;
  6098. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  6099. var cols = verticesPerRow - 1;
  6100. for (i = 0; i < rows; i++) {
  6101. var q = i * verticesPerRow;
  6102. for (var j = 0; j < cols; j++, q++) {
  6103. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6104. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6105. }
  6106. }
  6107. break;
  6108. case 'triangles':
  6109. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6110. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6111. }
  6112. break;
  6113. default:
  6114. error('illigal figure');
  6115. break;
  6116. }
  6117. }
  6118. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  6119. // we will increase scale on some weird factor to let antialiasing take
  6120. // care of "rough" edges
  6121. var EXPECTED_SCALE = 1.1;
  6122. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6123. var MAX_PATTERN_SIZE = 3000;
  6124. // 10in @ 300dpi shall be enough
  6125. // We need to keep transparent border around our pattern for fill():
  6126. // createPattern with 'no-repeat' will bleed edges across entire area.
  6127. var BORDER_SIZE = 2;
  6128. var offsetX = Math.floor(bounds[0]);
  6129. var offsetY = Math.floor(bounds[1]);
  6130. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  6131. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  6132. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6133. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6134. var scaleX = boundsWidth / width;
  6135. var scaleY = boundsHeight / height;
  6136. var context = {
  6137. coords: coords,
  6138. colors: colors,
  6139. offsetX: -offsetX,
  6140. offsetY: -offsetY,
  6141. scaleX: 1 / scaleX,
  6142. scaleY: 1 / scaleY
  6143. };
  6144. var paddedWidth = width + BORDER_SIZE * 2;
  6145. var paddedHeight = height + BORDER_SIZE * 2;
  6146. var canvas, tmpCanvas, i, ii;
  6147. if (WebGLUtils.isEnabled) {
  6148. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  6149. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  6150. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6151. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  6152. canvas = tmpCanvas.canvas;
  6153. } else {
  6154. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6155. var tmpCtx = tmpCanvas.context;
  6156. var data = tmpCtx.createImageData(width, height);
  6157. if (backgroundColor) {
  6158. var bytes = data.data;
  6159. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  6160. bytes[i] = backgroundColor[0];
  6161. bytes[i + 1] = backgroundColor[1];
  6162. bytes[i + 2] = backgroundColor[2];
  6163. bytes[i + 3] = 255;
  6164. }
  6165. }
  6166. for (i = 0; i < figures.length; i++) {
  6167. drawFigure(data, figures[i], context);
  6168. }
  6169. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6170. canvas = tmpCanvas.canvas;
  6171. }
  6172. return {
  6173. canvas: canvas,
  6174. offsetX: offsetX - BORDER_SIZE * scaleX,
  6175. offsetY: offsetY - BORDER_SIZE * scaleY,
  6176. scaleX: scaleX,
  6177. scaleY: scaleY
  6178. };
  6179. }
  6180. return createMeshCanvas;
  6181. }();
  6182. ShadingIRs.Mesh = {
  6183. fromIR: function Mesh_fromIR(raw) {
  6184. //var type = raw[1];
  6185. var coords = raw[2];
  6186. var colors = raw[3];
  6187. var figures = raw[4];
  6188. var bounds = raw[5];
  6189. var matrix = raw[6];
  6190. //var bbox = raw[7];
  6191. var background = raw[8];
  6192. return {
  6193. type: 'Pattern',
  6194. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  6195. var scale;
  6196. if (shadingFill) {
  6197. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6198. } else {
  6199. // Obtain scale from matrix and current transformation matrix.
  6200. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6201. if (matrix) {
  6202. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  6203. scale = [
  6204. scale[0] * matrixScale[0],
  6205. scale[1] * matrixScale[1]
  6206. ];
  6207. }
  6208. }
  6209. // Rasterizing on the main thread since sending/queue large canvases
  6210. // might cause OOM.
  6211. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  6212. if (!shadingFill) {
  6213. ctx.setTransform.apply(ctx, owner.baseTransform);
  6214. if (matrix) {
  6215. ctx.transform.apply(ctx, matrix);
  6216. }
  6217. }
  6218. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6219. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6220. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  6221. }
  6222. };
  6223. }
  6224. };
  6225. ShadingIRs.Dummy = {
  6226. fromIR: function Dummy_fromIR() {
  6227. return {
  6228. type: 'Pattern',
  6229. getPattern: function Dummy_fromIR_getPattern() {
  6230. return 'hotpink';
  6231. }
  6232. };
  6233. }
  6234. };
  6235. function getShadingPatternFromIR(raw) {
  6236. var shadingIR = ShadingIRs[raw[0]];
  6237. if (!shadingIR) {
  6238. error('Unknown IR type: ' + raw[0]);
  6239. }
  6240. return shadingIR.fromIR(raw);
  6241. }
  6242. var TilingPattern = function TilingPatternClosure() {
  6243. var PaintType = {
  6244. COLORED: 1,
  6245. UNCOLORED: 2
  6246. };
  6247. var MAX_PATTERN_SIZE = 3000;
  6248. // 10in @ 300dpi shall be enough
  6249. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6250. this.operatorList = IR[2];
  6251. this.matrix = IR[3] || [
  6252. 1,
  6253. 0,
  6254. 0,
  6255. 1,
  6256. 0,
  6257. 0
  6258. ];
  6259. this.bbox = IR[4];
  6260. this.xstep = IR[5];
  6261. this.ystep = IR[6];
  6262. this.paintType = IR[7];
  6263. this.tilingType = IR[8];
  6264. this.color = color;
  6265. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6266. this.baseTransform = baseTransform;
  6267. this.type = 'Pattern';
  6268. this.ctx = ctx;
  6269. }
  6270. TilingPattern.prototype = {
  6271. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6272. var operatorList = this.operatorList;
  6273. var bbox = this.bbox;
  6274. var xstep = this.xstep;
  6275. var ystep = this.ystep;
  6276. var paintType = this.paintType;
  6277. var tilingType = this.tilingType;
  6278. var color = this.color;
  6279. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6280. info('TilingType: ' + tilingType);
  6281. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6282. var topLeft = [
  6283. x0,
  6284. y0
  6285. ];
  6286. // we want the canvas to be as large as the step size
  6287. var botRight = [
  6288. x0 + xstep,
  6289. y0 + ystep
  6290. ];
  6291. var width = botRight[0] - topLeft[0];
  6292. var height = botRight[1] - topLeft[1];
  6293. // Obtain scale from matrix and current transformation matrix.
  6294. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6295. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6296. var combinedScale = [
  6297. matrixScale[0] * curMatrixScale[0],
  6298. matrixScale[1] * curMatrixScale[1]
  6299. ];
  6300. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6301. // Use width and height values that are as close as possible to the end
  6302. // result when the pattern is used. Too low value makes the pattern look
  6303. // blurry. Too large value makes it look too crispy.
  6304. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  6305. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  6306. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  6307. var tmpCtx = tmpCanvas.context;
  6308. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6309. graphics.groupLevel = owner.groupLevel;
  6310. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6311. this.setScale(width, height, xstep, ystep);
  6312. this.transformToScale(graphics);
  6313. // transform coordinates to pattern space
  6314. var tmpTranslate = [
  6315. 1,
  6316. 0,
  6317. 0,
  6318. 1,
  6319. -topLeft[0],
  6320. -topLeft[1]
  6321. ];
  6322. graphics.transform.apply(graphics, tmpTranslate);
  6323. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6324. graphics.executeOperatorList(operatorList);
  6325. return tmpCanvas.canvas;
  6326. },
  6327. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6328. this.scale = [
  6329. width / xstep,
  6330. height / ystep
  6331. ];
  6332. },
  6333. transformToScale: function TilingPattern_transformToScale(graphics) {
  6334. var scale = this.scale;
  6335. var tmpScale = [
  6336. scale[0],
  6337. 0,
  6338. 0,
  6339. scale[1],
  6340. 0,
  6341. 0
  6342. ];
  6343. graphics.transform.apply(graphics, tmpScale);
  6344. },
  6345. scaleToContext: function TilingPattern_scaleToContext() {
  6346. var scale = this.scale;
  6347. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6348. },
  6349. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6350. if (bbox && isArray(bbox) && bbox.length === 4) {
  6351. var bboxWidth = x1 - x0;
  6352. var bboxHeight = y1 - y0;
  6353. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6354. graphics.clip();
  6355. graphics.endPath();
  6356. }
  6357. },
  6358. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  6359. switch (paintType) {
  6360. case PaintType.COLORED:
  6361. var ctx = this.ctx;
  6362. context.fillStyle = ctx.fillStyle;
  6363. context.strokeStyle = ctx.strokeStyle;
  6364. break;
  6365. case PaintType.UNCOLORED:
  6366. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6367. context.fillStyle = cssColor;
  6368. context.strokeStyle = cssColor;
  6369. break;
  6370. default:
  6371. error('Unsupported paint type: ' + paintType);
  6372. }
  6373. },
  6374. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6375. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6376. ctx = this.ctx;
  6377. ctx.setTransform.apply(ctx, this.baseTransform);
  6378. ctx.transform.apply(ctx, this.matrix);
  6379. this.scaleToContext();
  6380. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6381. }
  6382. };
  6383. return TilingPattern;
  6384. }();
  6385. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6386. exports.TilingPattern = TilingPattern;
  6387. }));
  6388. (function (root, factory) {
  6389. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  6390. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  6391. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6392. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6393. var ImageKind = sharedUtil.ImageKind;
  6394. var OPS = sharedUtil.OPS;
  6395. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6396. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6397. var Util = sharedUtil.Util;
  6398. var assert = sharedUtil.assert;
  6399. var info = sharedUtil.info;
  6400. var isNum = sharedUtil.isNum;
  6401. var isArray = sharedUtil.isArray;
  6402. var isLittleEndian = sharedUtil.isLittleEndian;
  6403. var error = sharedUtil.error;
  6404. var shadow = sharedUtil.shadow;
  6405. var warn = sharedUtil.warn;
  6406. var TilingPattern = displayPatternHelper.TilingPattern;
  6407. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6408. var WebGLUtils = displayWebGL.WebGLUtils;
  6409. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6410. // <canvas> contexts store most of the state we need natively.
  6411. // However, PDF needs a bit more state, which we store here.
  6412. // Minimal font size that would be used during canvas fillText operations.
  6413. var MIN_FONT_SIZE = 16;
  6414. // Maximum font size that would be used during canvas fillText operations.
  6415. var MAX_FONT_SIZE = 100;
  6416. var MAX_GROUP_SIZE = 4096;
  6417. // Heuristic value used when enforcing minimum line widths.
  6418. var MIN_WIDTH_FACTOR = 0.65;
  6419. var COMPILE_TYPE3_GLYPHS = true;
  6420. var MAX_SIZE_TO_COMPILE = 1000;
  6421. var FULL_CHUNK_HEIGHT = 16;
  6422. var HasCanvasTypedArraysCached = {
  6423. get value() {
  6424. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6425. }
  6426. };
  6427. var IsLittleEndianCached = {
  6428. get value() {
  6429. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6430. }
  6431. };
  6432. function createScratchCanvas(width, height) {
  6433. var canvas = document.createElement('canvas');
  6434. canvas.width = width;
  6435. canvas.height = height;
  6436. return canvas;
  6437. }
  6438. function addContextCurrentTransform(ctx) {
  6439. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6440. if (!ctx.mozCurrentTransform) {
  6441. ctx._originalSave = ctx.save;
  6442. ctx._originalRestore = ctx.restore;
  6443. ctx._originalRotate = ctx.rotate;
  6444. ctx._originalScale = ctx.scale;
  6445. ctx._originalTranslate = ctx.translate;
  6446. ctx._originalTransform = ctx.transform;
  6447. ctx._originalSetTransform = ctx.setTransform;
  6448. ctx._transformMatrix = ctx._transformMatrix || [
  6449. 1,
  6450. 0,
  6451. 0,
  6452. 1,
  6453. 0,
  6454. 0
  6455. ];
  6456. ctx._transformStack = [];
  6457. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6458. get: function getCurrentTransform() {
  6459. return this._transformMatrix;
  6460. }
  6461. });
  6462. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6463. get: function getCurrentTransformInverse() {
  6464. // Calculation done using WolframAlpha:
  6465. // http://www.wolframalpha.com/input/?
  6466. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6467. var m = this._transformMatrix;
  6468. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6469. var ad_bc = a * d - b * c;
  6470. var bc_ad = b * c - a * d;
  6471. return [
  6472. d / ad_bc,
  6473. b / bc_ad,
  6474. c / bc_ad,
  6475. a / ad_bc,
  6476. (d * e - c * f) / bc_ad,
  6477. (b * e - a * f) / ad_bc
  6478. ];
  6479. }
  6480. });
  6481. ctx.save = function ctxSave() {
  6482. var old = this._transformMatrix;
  6483. this._transformStack.push(old);
  6484. this._transformMatrix = old.slice(0, 6);
  6485. this._originalSave();
  6486. };
  6487. ctx.restore = function ctxRestore() {
  6488. var prev = this._transformStack.pop();
  6489. if (prev) {
  6490. this._transformMatrix = prev;
  6491. this._originalRestore();
  6492. }
  6493. };
  6494. ctx.translate = function ctxTranslate(x, y) {
  6495. var m = this._transformMatrix;
  6496. m[4] = m[0] * x + m[2] * y + m[4];
  6497. m[5] = m[1] * x + m[3] * y + m[5];
  6498. this._originalTranslate(x, y);
  6499. };
  6500. ctx.scale = function ctxScale(x, y) {
  6501. var m = this._transformMatrix;
  6502. m[0] = m[0] * x;
  6503. m[1] = m[1] * x;
  6504. m[2] = m[2] * y;
  6505. m[3] = m[3] * y;
  6506. this._originalScale(x, y);
  6507. };
  6508. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6509. var m = this._transformMatrix;
  6510. this._transformMatrix = [
  6511. m[0] * a + m[2] * b,
  6512. m[1] * a + m[3] * b,
  6513. m[0] * c + m[2] * d,
  6514. m[1] * c + m[3] * d,
  6515. m[0] * e + m[2] * f + m[4],
  6516. m[1] * e + m[3] * f + m[5]
  6517. ];
  6518. ctx._originalTransform(a, b, c, d, e, f);
  6519. };
  6520. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6521. this._transformMatrix = [
  6522. a,
  6523. b,
  6524. c,
  6525. d,
  6526. e,
  6527. f
  6528. ];
  6529. ctx._originalSetTransform(a, b, c, d, e, f);
  6530. };
  6531. ctx.rotate = function ctxRotate(angle) {
  6532. var cosValue = Math.cos(angle);
  6533. var sinValue = Math.sin(angle);
  6534. var m = this._transformMatrix;
  6535. this._transformMatrix = [
  6536. m[0] * cosValue + m[2] * sinValue,
  6537. m[1] * cosValue + m[3] * sinValue,
  6538. m[0] * -sinValue + m[2] * cosValue,
  6539. m[1] * -sinValue + m[3] * cosValue,
  6540. m[4],
  6541. m[5]
  6542. ];
  6543. this._originalRotate(angle);
  6544. };
  6545. }
  6546. }
  6547. var CachedCanvases = function CachedCanvasesClosure() {
  6548. function CachedCanvases() {
  6549. this.cache = Object.create(null);
  6550. }
  6551. CachedCanvases.prototype = {
  6552. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  6553. var canvasEntry;
  6554. if (this.cache[id] !== undefined) {
  6555. canvasEntry = this.cache[id];
  6556. canvasEntry.canvas.width = width;
  6557. canvasEntry.canvas.height = height;
  6558. // reset canvas transform for emulated mozCurrentTransform, if needed
  6559. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6560. } else {
  6561. var canvas = createScratchCanvas(width, height);
  6562. var ctx = canvas.getContext('2d');
  6563. if (trackTransform) {
  6564. addContextCurrentTransform(ctx);
  6565. }
  6566. this.cache[id] = canvasEntry = {
  6567. canvas: canvas,
  6568. context: ctx
  6569. };
  6570. }
  6571. return canvasEntry;
  6572. },
  6573. clear: function () {
  6574. for (var id in this.cache) {
  6575. var canvasEntry = this.cache[id];
  6576. // Zeroing the width and height causes Firefox to release graphics
  6577. // resources immediately, which can greatly reduce memory consumption.
  6578. canvasEntry.canvas.width = 0;
  6579. canvasEntry.canvas.height = 0;
  6580. delete this.cache[id];
  6581. }
  6582. }
  6583. };
  6584. return CachedCanvases;
  6585. }();
  6586. function compileType3Glyph(imgData) {
  6587. var POINT_TO_PROCESS_LIMIT = 1000;
  6588. var width = imgData.width, height = imgData.height;
  6589. var i, j, j0, width1 = width + 1;
  6590. var points = new Uint8Array(width1 * (height + 1));
  6591. var POINT_TYPES = new Uint8Array([
  6592. 0,
  6593. 2,
  6594. 4,
  6595. 0,
  6596. 1,
  6597. 0,
  6598. 5,
  6599. 4,
  6600. 8,
  6601. 10,
  6602. 0,
  6603. 8,
  6604. 0,
  6605. 2,
  6606. 1,
  6607. 0
  6608. ]);
  6609. // decodes bit-packed mask data
  6610. var lineSize = width + 7 & ~7, data0 = imgData.data;
  6611. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6612. for (i = 0, ii = data0.length; i < ii; i++) {
  6613. var mask = 128, elem = data0[i];
  6614. while (mask > 0) {
  6615. data[pos++] = elem & mask ? 0 : 255;
  6616. mask >>= 1;
  6617. }
  6618. }
  6619. // finding iteresting points: every point is located between mask pixels,
  6620. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6621. // will have flags assigned based on neighboring mask pixels:
  6622. // 4 | 8
  6623. // --P--
  6624. // 2 | 1
  6625. // We are interested only in points with the flags:
  6626. // - outside corners: 1, 2, 4, 8;
  6627. // - inside corners: 7, 11, 13, 14;
  6628. // - and, intersections: 5, 10.
  6629. var count = 0;
  6630. pos = 0;
  6631. if (data[pos] !== 0) {
  6632. points[0] = 1;
  6633. ++count;
  6634. }
  6635. for (j = 1; j < width; j++) {
  6636. if (data[pos] !== data[pos + 1]) {
  6637. points[j] = data[pos] ? 2 : 1;
  6638. ++count;
  6639. }
  6640. pos++;
  6641. }
  6642. if (data[pos] !== 0) {
  6643. points[j] = 2;
  6644. ++count;
  6645. }
  6646. for (i = 1; i < height; i++) {
  6647. pos = i * lineSize;
  6648. j0 = i * width1;
  6649. if (data[pos - lineSize] !== data[pos]) {
  6650. points[j0] = data[pos] ? 1 : 8;
  6651. ++count;
  6652. }
  6653. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6654. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6655. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6656. for (j = 1; j < width; j++) {
  6657. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6658. if (POINT_TYPES[sum]) {
  6659. points[j0 + j] = POINT_TYPES[sum];
  6660. ++count;
  6661. }
  6662. pos++;
  6663. }
  6664. if (data[pos - lineSize] !== data[pos]) {
  6665. points[j0 + j] = data[pos] ? 2 : 4;
  6666. ++count;
  6667. }
  6668. if (count > POINT_TO_PROCESS_LIMIT) {
  6669. return null;
  6670. }
  6671. }
  6672. pos = lineSize * (height - 1);
  6673. j0 = i * width1;
  6674. if (data[pos] !== 0) {
  6675. points[j0] = 8;
  6676. ++count;
  6677. }
  6678. for (j = 1; j < width; j++) {
  6679. if (data[pos] !== data[pos + 1]) {
  6680. points[j0 + j] = data[pos] ? 4 : 8;
  6681. ++count;
  6682. }
  6683. pos++;
  6684. }
  6685. if (data[pos] !== 0) {
  6686. points[j0 + j] = 4;
  6687. ++count;
  6688. }
  6689. if (count > POINT_TO_PROCESS_LIMIT) {
  6690. return null;
  6691. }
  6692. // building outlines
  6693. var steps = new Int32Array([
  6694. 0,
  6695. width1,
  6696. -1,
  6697. 0,
  6698. -width1,
  6699. 0,
  6700. 0,
  6701. 0,
  6702. 1
  6703. ]);
  6704. var outlines = [];
  6705. for (i = 0; count && i <= height; i++) {
  6706. var p = i * width1;
  6707. var end = p + width;
  6708. while (p < end && !points[p]) {
  6709. p++;
  6710. }
  6711. if (p === end) {
  6712. continue;
  6713. }
  6714. var coords = [
  6715. p % width1,
  6716. i
  6717. ];
  6718. var type = points[p], p0 = p, pp;
  6719. do {
  6720. var step = steps[type];
  6721. do {
  6722. p += step;
  6723. } while (!points[p]);
  6724. pp = points[p];
  6725. if (pp !== 5 && pp !== 10) {
  6726. // set new direction
  6727. type = pp;
  6728. // delete mark
  6729. points[p] = 0;
  6730. } else {
  6731. // type is 5 or 10, ie, a crossing
  6732. // set new direction
  6733. type = pp & 0x33 * type >> 4;
  6734. // set new type for "future hit"
  6735. points[p] &= type >> 2 | type << 2;
  6736. }
  6737. coords.push(p % width1);
  6738. coords.push(p / width1 | 0);
  6739. --count;
  6740. } while (p0 !== p);
  6741. outlines.push(coords);
  6742. --i;
  6743. }
  6744. var drawOutline = function (c) {
  6745. c.save();
  6746. // the path shall be painted in [0..1]x[0..1] space
  6747. c.scale(1 / width, -1 / height);
  6748. c.translate(0, -height);
  6749. c.beginPath();
  6750. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6751. var o = outlines[i];
  6752. c.moveTo(o[0], o[1]);
  6753. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6754. c.lineTo(o[j], o[j + 1]);
  6755. }
  6756. }
  6757. c.fill();
  6758. c.beginPath();
  6759. c.restore();
  6760. };
  6761. return drawOutline;
  6762. }
  6763. var CanvasExtraState = function CanvasExtraStateClosure() {
  6764. function CanvasExtraState(old) {
  6765. // Are soft masks and alpha values shapes or opacities?
  6766. this.alphaIsShape = false;
  6767. this.fontSize = 0;
  6768. this.fontSizeScale = 1;
  6769. this.textMatrix = IDENTITY_MATRIX;
  6770. this.textMatrixScale = 1;
  6771. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6772. this.leading = 0;
  6773. // Current point (in user coordinates)
  6774. this.x = 0;
  6775. this.y = 0;
  6776. // Start of text line (in text coordinates)
  6777. this.lineX = 0;
  6778. this.lineY = 0;
  6779. // Character and word spacing
  6780. this.charSpacing = 0;
  6781. this.wordSpacing = 0;
  6782. this.textHScale = 1;
  6783. this.textRenderingMode = TextRenderingMode.FILL;
  6784. this.textRise = 0;
  6785. // Default fore and background colors
  6786. this.fillColor = '#000000';
  6787. this.strokeColor = '#000000';
  6788. this.patternFill = false;
  6789. // Note: fill alpha applies to all non-stroking operations
  6790. this.fillAlpha = 1;
  6791. this.strokeAlpha = 1;
  6792. this.lineWidth = 1;
  6793. this.activeSMask = null;
  6794. this.resumeSMaskCtx = null;
  6795. // nonclonable field (see the save method below)
  6796. this.old = old;
  6797. }
  6798. CanvasExtraState.prototype = {
  6799. clone: function CanvasExtraState_clone() {
  6800. return Object.create(this);
  6801. },
  6802. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6803. this.x = x;
  6804. this.y = y;
  6805. }
  6806. };
  6807. return CanvasExtraState;
  6808. }();
  6809. var CanvasGraphics = function CanvasGraphicsClosure() {
  6810. // Defines the time the executeOperatorList is going to be executing
  6811. // before it stops and shedules a continue of execution.
  6812. var EXECUTION_TIME = 15;
  6813. // Defines the number of steps before checking the execution time
  6814. var EXECUTION_STEPS = 10;
  6815. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6816. this.ctx = canvasCtx;
  6817. this.current = new CanvasExtraState();
  6818. this.stateStack = [];
  6819. this.pendingClip = null;
  6820. this.pendingEOFill = false;
  6821. this.res = null;
  6822. this.xobjs = null;
  6823. this.commonObjs = commonObjs;
  6824. this.objs = objs;
  6825. this.imageLayer = imageLayer;
  6826. this.groupStack = [];
  6827. this.processingType3 = null;
  6828. // Patterns are painted relative to the initial page/form transform, see pdf
  6829. // spec 8.7.2 NOTE 1.
  6830. this.baseTransform = null;
  6831. this.baseTransformStack = [];
  6832. this.groupLevel = 0;
  6833. this.smaskStack = [];
  6834. this.smaskCounter = 0;
  6835. this.tempSMask = null;
  6836. this.cachedCanvases = new CachedCanvases();
  6837. if (canvasCtx) {
  6838. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6839. // the transformation must already be set in canvasCtx._transformMatrix.
  6840. addContextCurrentTransform(canvasCtx);
  6841. }
  6842. this.cachedGetSinglePixelWidth = null;
  6843. }
  6844. function putBinaryImageData(ctx, imgData) {
  6845. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6846. ctx.putImageData(imgData, 0, 0);
  6847. return;
  6848. }
  6849. // Put the image data to the canvas in chunks, rather than putting the
  6850. // whole image at once. This saves JS memory, because the ImageData object
  6851. // is smaller. It also possibly saves C++ memory within the implementation
  6852. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6853. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6854. // because too many putImageData() calls will slow things down.
  6855. //
  6856. // Note: as written, if the last chunk is partial, the putImageData() call
  6857. // will (conceptually) put pixels past the bounds of the canvas. But
  6858. // that's ok; any such pixels are ignored.
  6859. var height = imgData.height, width = imgData.width;
  6860. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6861. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6862. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6863. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6864. var srcPos = 0, destPos;
  6865. var src = imgData.data;
  6866. var dest = chunkImgData.data;
  6867. var i, j, thisChunkHeight, elemsInThisChunk;
  6868. // There are multiple forms in which the pixel data can be passed, and
  6869. // imgData.kind tells us which one this is.
  6870. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6871. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6872. var srcLength = src.byteLength;
  6873. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6874. var dest32DataLength = dest32.length;
  6875. var fullSrcDiff = width + 7 >> 3;
  6876. var white = 0xFFFFFFFF;
  6877. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6878. for (i = 0; i < totalChunks; i++) {
  6879. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6880. destPos = 0;
  6881. for (j = 0; j < thisChunkHeight; j++) {
  6882. var srcDiff = srcLength - srcPos;
  6883. var k = 0;
  6884. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6885. var kEndUnrolled = kEnd & ~7;
  6886. var mask = 0;
  6887. var srcByte = 0;
  6888. for (; k < kEndUnrolled; k += 8) {
  6889. srcByte = src[srcPos++];
  6890. dest32[destPos++] = srcByte & 128 ? white : black;
  6891. dest32[destPos++] = srcByte & 64 ? white : black;
  6892. dest32[destPos++] = srcByte & 32 ? white : black;
  6893. dest32[destPos++] = srcByte & 16 ? white : black;
  6894. dest32[destPos++] = srcByte & 8 ? white : black;
  6895. dest32[destPos++] = srcByte & 4 ? white : black;
  6896. dest32[destPos++] = srcByte & 2 ? white : black;
  6897. dest32[destPos++] = srcByte & 1 ? white : black;
  6898. }
  6899. for (; k < kEnd; k++) {
  6900. if (mask === 0) {
  6901. srcByte = src[srcPos++];
  6902. mask = 128;
  6903. }
  6904. dest32[destPos++] = srcByte & mask ? white : black;
  6905. mask >>= 1;
  6906. }
  6907. }
  6908. // We ran out of input. Make all remaining pixels transparent.
  6909. while (destPos < dest32DataLength) {
  6910. dest32[destPos++] = 0;
  6911. }
  6912. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6913. }
  6914. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6915. // RGBA, 32-bits per pixel.
  6916. j = 0;
  6917. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6918. for (i = 0; i < fullChunks; i++) {
  6919. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6920. srcPos += elemsInThisChunk;
  6921. ctx.putImageData(chunkImgData, 0, j);
  6922. j += FULL_CHUNK_HEIGHT;
  6923. }
  6924. if (i < totalChunks) {
  6925. elemsInThisChunk = width * partialChunkHeight * 4;
  6926. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6927. ctx.putImageData(chunkImgData, 0, j);
  6928. }
  6929. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6930. // RGB, 24-bits per pixel.
  6931. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6932. elemsInThisChunk = width * thisChunkHeight;
  6933. for (i = 0; i < totalChunks; i++) {
  6934. if (i >= fullChunks) {
  6935. thisChunkHeight = partialChunkHeight;
  6936. elemsInThisChunk = width * thisChunkHeight;
  6937. }
  6938. destPos = 0;
  6939. for (j = elemsInThisChunk; j--;) {
  6940. dest[destPos++] = src[srcPos++];
  6941. dest[destPos++] = src[srcPos++];
  6942. dest[destPos++] = src[srcPos++];
  6943. dest[destPos++] = 255;
  6944. }
  6945. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6946. }
  6947. } else {
  6948. error('bad image kind: ' + imgData.kind);
  6949. }
  6950. }
  6951. function putBinaryImageMask(ctx, imgData) {
  6952. var height = imgData.height, width = imgData.width;
  6953. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6954. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6955. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6956. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6957. var srcPos = 0;
  6958. var src = imgData.data;
  6959. var dest = chunkImgData.data;
  6960. for (var i = 0; i < totalChunks; i++) {
  6961. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6962. // Expand the mask so it can be used by the canvas. Any required
  6963. // inversion has already been handled.
  6964. var destPos = 3;
  6965. // alpha component offset
  6966. for (var j = 0; j < thisChunkHeight; j++) {
  6967. var mask = 0;
  6968. for (var k = 0; k < width; k++) {
  6969. if (!mask) {
  6970. var elem = src[srcPos++];
  6971. mask = 128;
  6972. }
  6973. dest[destPos] = elem & mask ? 0 : 255;
  6974. destPos += 4;
  6975. mask >>= 1;
  6976. }
  6977. }
  6978. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6979. }
  6980. }
  6981. function copyCtxState(sourceCtx, destCtx) {
  6982. var properties = [
  6983. 'strokeStyle',
  6984. 'fillStyle',
  6985. 'fillRule',
  6986. 'globalAlpha',
  6987. 'lineWidth',
  6988. 'lineCap',
  6989. 'lineJoin',
  6990. 'miterLimit',
  6991. 'globalCompositeOperation',
  6992. 'font'
  6993. ];
  6994. for (var i = 0, ii = properties.length; i < ii; i++) {
  6995. var property = properties[i];
  6996. if (sourceCtx[property] !== undefined) {
  6997. destCtx[property] = sourceCtx[property];
  6998. }
  6999. }
  7000. if (sourceCtx.setLineDash !== undefined) {
  7001. destCtx.setLineDash(sourceCtx.getLineDash());
  7002. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  7003. }
  7004. }
  7005. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  7006. var length = bytes.length;
  7007. for (var i = 3; i < length; i += 4) {
  7008. var alpha = bytes[i];
  7009. if (alpha === 0) {
  7010. bytes[i - 3] = r0;
  7011. bytes[i - 2] = g0;
  7012. bytes[i - 1] = b0;
  7013. } else if (alpha < 255) {
  7014. var alpha_ = 255 - alpha;
  7015. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  7016. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  7017. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  7018. }
  7019. }
  7020. }
  7021. function composeSMaskAlpha(maskData, layerData, transferMap) {
  7022. var length = maskData.length;
  7023. var scale = 1 / 255;
  7024. for (var i = 3; i < length; i += 4) {
  7025. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  7026. layerData[i] = layerData[i] * alpha * scale | 0;
  7027. }
  7028. }
  7029. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  7030. var length = maskData.length;
  7031. for (var i = 3; i < length; i += 4) {
  7032. var y = maskData[i - 3] * 77 + // * 0.3 / 255 * 0x10000
  7033. maskData[i - 2] * 152 + // * 0.59 ....
  7034. maskData[i - 1] * 28;
  7035. // * 0.11 ....
  7036. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  7037. }
  7038. }
  7039. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  7040. var hasBackdrop = !!backdrop;
  7041. var r0 = hasBackdrop ? backdrop[0] : 0;
  7042. var g0 = hasBackdrop ? backdrop[1] : 0;
  7043. var b0 = hasBackdrop ? backdrop[2] : 0;
  7044. var composeFn;
  7045. if (subtype === 'Luminosity') {
  7046. composeFn = composeSMaskLuminosity;
  7047. } else {
  7048. composeFn = composeSMaskAlpha;
  7049. }
  7050. // processing image in chunks to save memory
  7051. var PIXELS_TO_PROCESS = 1048576;
  7052. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  7053. for (var row = 0; row < height; row += chunkSize) {
  7054. var chunkHeight = Math.min(chunkSize, height - row);
  7055. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  7056. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  7057. if (hasBackdrop) {
  7058. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  7059. }
  7060. composeFn(maskData.data, layerData.data, transferMap);
  7061. maskCtx.putImageData(layerData, 0, row);
  7062. }
  7063. }
  7064. function composeSMask(ctx, smask, layerCtx) {
  7065. var mask = smask.canvas;
  7066. var maskCtx = smask.context;
  7067. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  7068. var backdrop = smask.backdrop || null;
  7069. if (!smask.transferMap && WebGLUtils.isEnabled) {
  7070. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  7071. subtype: smask.subtype,
  7072. backdrop: backdrop
  7073. });
  7074. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7075. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  7076. return;
  7077. }
  7078. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  7079. ctx.drawImage(mask, 0, 0);
  7080. }
  7081. var LINE_CAP_STYLES = [
  7082. 'butt',
  7083. 'round',
  7084. 'square'
  7085. ];
  7086. var LINE_JOIN_STYLES = [
  7087. 'miter',
  7088. 'round',
  7089. 'bevel'
  7090. ];
  7091. var NORMAL_CLIP = {};
  7092. var EO_CLIP = {};
  7093. CanvasGraphics.prototype = {
  7094. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  7095. // For pdfs that use blend modes we have to clear the canvas else certain
  7096. // blend modes can look wrong since we'd be blending with a white
  7097. // backdrop. The problem with a transparent backdrop though is we then
  7098. // don't get sub pixel anti aliasing on text, creating temporary
  7099. // transparent canvas when we have blend modes.
  7100. var width = this.ctx.canvas.width;
  7101. var height = this.ctx.canvas.height;
  7102. this.ctx.save();
  7103. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  7104. this.ctx.fillRect(0, 0, width, height);
  7105. this.ctx.restore();
  7106. if (transparency) {
  7107. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  7108. this.compositeCtx = this.ctx;
  7109. this.transparentCanvas = transparentCanvas.canvas;
  7110. this.ctx = transparentCanvas.context;
  7111. this.ctx.save();
  7112. // The transform can be applied before rendering, transferring it to
  7113. // the new canvas.
  7114. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  7115. }
  7116. this.ctx.save();
  7117. if (transform) {
  7118. this.ctx.transform.apply(this.ctx, transform);
  7119. }
  7120. this.ctx.transform.apply(this.ctx, viewport.transform);
  7121. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  7122. if (this.imageLayer) {
  7123. this.imageLayer.beginLayout();
  7124. }
  7125. },
  7126. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7127. var argsArray = operatorList.argsArray;
  7128. var fnArray = operatorList.fnArray;
  7129. var i = executionStartIdx || 0;
  7130. var argsArrayLen = argsArray.length;
  7131. // Sometimes the OperatorList to execute is empty.
  7132. if (argsArrayLen === i) {
  7133. return i;
  7134. }
  7135. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  7136. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7137. var steps = 0;
  7138. var commonObjs = this.commonObjs;
  7139. var objs = this.objs;
  7140. var fnId;
  7141. while (true) {
  7142. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7143. stepper.breakIt(i, continueCallback);
  7144. return i;
  7145. }
  7146. fnId = fnArray[i];
  7147. if (fnId !== OPS.dependency) {
  7148. this[fnId].apply(this, argsArray[i]);
  7149. } else {
  7150. var deps = argsArray[i];
  7151. for (var n = 0, nn = deps.length; n < nn; n++) {
  7152. var depObjId = deps[n];
  7153. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  7154. var objsPool = common ? commonObjs : objs;
  7155. // If the promise isn't resolved yet, add the continueCallback
  7156. // to the promise and bail out.
  7157. if (!objsPool.isResolved(depObjId)) {
  7158. objsPool.get(depObjId, continueCallback);
  7159. return i;
  7160. }
  7161. }
  7162. }
  7163. i++;
  7164. // If the entire operatorList was executed, stop as were done.
  7165. if (i === argsArrayLen) {
  7166. return i;
  7167. }
  7168. // If the execution took longer then a certain amount of time and
  7169. // `continueCallback` is specified, interrupt the execution.
  7170. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7171. if (Date.now() > endTime) {
  7172. continueCallback();
  7173. return i;
  7174. }
  7175. steps = 0;
  7176. }
  7177. }
  7178. },
  7179. // If the operatorList isn't executed completely yet OR the execution
  7180. // time was short enough, do another execution round.
  7181. endDrawing: function CanvasGraphics_endDrawing() {
  7182. // Finishing all opened operations such as SMask group painting.
  7183. if (this.current.activeSMask !== null) {
  7184. this.endSMaskGroup();
  7185. }
  7186. this.ctx.restore();
  7187. if (this.transparentCanvas) {
  7188. this.ctx = this.compositeCtx;
  7189. this.ctx.save();
  7190. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7191. // Avoid apply transform twice
  7192. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7193. this.ctx.restore();
  7194. this.transparentCanvas = null;
  7195. }
  7196. this.cachedCanvases.clear();
  7197. WebGLUtils.clear();
  7198. if (this.imageLayer) {
  7199. this.imageLayer.endLayout();
  7200. }
  7201. },
  7202. // Graphics state
  7203. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  7204. this.current.lineWidth = width;
  7205. this.ctx.lineWidth = width;
  7206. },
  7207. setLineCap: function CanvasGraphics_setLineCap(style) {
  7208. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7209. },
  7210. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  7211. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7212. },
  7213. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  7214. this.ctx.miterLimit = limit;
  7215. },
  7216. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  7217. var ctx = this.ctx;
  7218. if (ctx.setLineDash !== undefined) {
  7219. ctx.setLineDash(dashArray);
  7220. ctx.lineDashOffset = dashPhase;
  7221. }
  7222. },
  7223. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  7224. },
  7225. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  7226. },
  7227. setGState: function CanvasGraphics_setGState(states) {
  7228. for (var i = 0, ii = states.length; i < ii; i++) {
  7229. var state = states[i];
  7230. var key = state[0];
  7231. var value = state[1];
  7232. switch (key) {
  7233. case 'LW':
  7234. this.setLineWidth(value);
  7235. break;
  7236. case 'LC':
  7237. this.setLineCap(value);
  7238. break;
  7239. case 'LJ':
  7240. this.setLineJoin(value);
  7241. break;
  7242. case 'ML':
  7243. this.setMiterLimit(value);
  7244. break;
  7245. case 'D':
  7246. this.setDash(value[0], value[1]);
  7247. break;
  7248. case 'RI':
  7249. this.setRenderingIntent(value);
  7250. break;
  7251. case 'FL':
  7252. this.setFlatness(value);
  7253. break;
  7254. case 'Font':
  7255. this.setFont(value[0], value[1]);
  7256. break;
  7257. case 'CA':
  7258. this.current.strokeAlpha = state[1];
  7259. break;
  7260. case 'ca':
  7261. this.current.fillAlpha = state[1];
  7262. this.ctx.globalAlpha = state[1];
  7263. break;
  7264. case 'BM':
  7265. if (value && value.name && value.name !== 'Normal') {
  7266. var mode = value.name.replace(/([A-Z])/g, function (c) {
  7267. return '-' + c.toLowerCase();
  7268. }).substring(1);
  7269. this.ctx.globalCompositeOperation = mode;
  7270. if (this.ctx.globalCompositeOperation !== mode) {
  7271. warn('globalCompositeOperation "' + mode + '" is not supported');
  7272. }
  7273. } else {
  7274. this.ctx.globalCompositeOperation = 'source-over';
  7275. }
  7276. break;
  7277. case 'SMask':
  7278. if (this.current.activeSMask) {
  7279. // If SMask is currrenly used, it needs to be suspended or
  7280. // finished. Suspend only makes sense when at least one save()
  7281. // was performed and state needs to be reverted on restore().
  7282. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  7283. this.suspendSMaskGroup();
  7284. } else {
  7285. this.endSMaskGroup();
  7286. }
  7287. }
  7288. this.current.activeSMask = value ? this.tempSMask : null;
  7289. if (this.current.activeSMask) {
  7290. this.beginSMaskGroup();
  7291. }
  7292. this.tempSMask = null;
  7293. break;
  7294. }
  7295. }
  7296. },
  7297. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  7298. var activeSMask = this.current.activeSMask;
  7299. var drawnWidth = activeSMask.canvas.width;
  7300. var drawnHeight = activeSMask.canvas.height;
  7301. var cacheId = 'smaskGroupAt' + this.groupLevel;
  7302. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7303. var currentCtx = this.ctx;
  7304. var currentTransform = currentCtx.mozCurrentTransform;
  7305. this.ctx.save();
  7306. var groupCtx = scratchCanvas.context;
  7307. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  7308. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  7309. groupCtx.transform.apply(groupCtx, currentTransform);
  7310. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  7311. copyCtxState(currentCtx, groupCtx);
  7312. this.ctx = groupCtx;
  7313. this.setGState([
  7314. [
  7315. 'BM',
  7316. 'Normal'
  7317. ],
  7318. [
  7319. 'ca',
  7320. 1
  7321. ],
  7322. [
  7323. 'CA',
  7324. 1
  7325. ]
  7326. ]);
  7327. this.groupStack.push(currentCtx);
  7328. this.groupLevel++;
  7329. },
  7330. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7331. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7332. // and future ctx state restored.
  7333. var groupCtx = this.ctx;
  7334. this.groupLevel--;
  7335. this.ctx = this.groupStack.pop();
  7336. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7337. this.ctx.restore();
  7338. this.ctx.save();
  7339. // save is needed since SMask will be resumed.
  7340. copyCtxState(groupCtx, this.ctx);
  7341. // Saving state for resuming.
  7342. this.current.resumeSMaskCtx = groupCtx;
  7343. // Transform was changed in the SMask canvas, reflecting this change on
  7344. // this.ctx.
  7345. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7346. this.ctx.transform.apply(this.ctx, deltaTransform);
  7347. // SMask was composed, the results at the groupCtx can be cleared.
  7348. groupCtx.save();
  7349. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7350. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7351. groupCtx.restore();
  7352. },
  7353. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7354. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7355. // any groupCtx state since restore() command (the only caller) will do
  7356. // that for us. See also beginSMaskGroup.
  7357. var groupCtx = this.current.resumeSMaskCtx;
  7358. var currentCtx = this.ctx;
  7359. this.ctx = groupCtx;
  7360. this.groupStack.push(currentCtx);
  7361. this.groupLevel++;
  7362. },
  7363. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7364. var groupCtx = this.ctx;
  7365. this.groupLevel--;
  7366. this.ctx = this.groupStack.pop();
  7367. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7368. this.ctx.restore();
  7369. copyCtxState(groupCtx, this.ctx);
  7370. // Transform was changed in the SMask canvas, reflecting this change on
  7371. // this.ctx.
  7372. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7373. this.ctx.transform.apply(this.ctx, deltaTransform);
  7374. },
  7375. save: function CanvasGraphics_save() {
  7376. this.ctx.save();
  7377. var old = this.current;
  7378. this.stateStack.push(old);
  7379. this.current = old.clone();
  7380. this.current.resumeSMaskCtx = null;
  7381. },
  7382. restore: function CanvasGraphics_restore() {
  7383. // SMask was suspended, we just need to resume it.
  7384. if (this.current.resumeSMaskCtx) {
  7385. this.resumeSMaskGroup();
  7386. }
  7387. // SMask has to be finished once there is no states that are using the
  7388. // same SMask.
  7389. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  7390. this.endSMaskGroup();
  7391. }
  7392. if (this.stateStack.length !== 0) {
  7393. this.current = this.stateStack.pop();
  7394. this.ctx.restore();
  7395. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7396. this.pendingClip = null;
  7397. this.cachedGetSinglePixelWidth = null;
  7398. }
  7399. },
  7400. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7401. this.ctx.transform(a, b, c, d, e, f);
  7402. this.cachedGetSinglePixelWidth = null;
  7403. },
  7404. // Path
  7405. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7406. var ctx = this.ctx;
  7407. var current = this.current;
  7408. var x = current.x, y = current.y;
  7409. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7410. switch (ops[i] | 0) {
  7411. case OPS.rectangle:
  7412. x = args[j++];
  7413. y = args[j++];
  7414. var width = args[j++];
  7415. var height = args[j++];
  7416. if (width === 0) {
  7417. width = this.getSinglePixelWidth();
  7418. }
  7419. if (height === 0) {
  7420. height = this.getSinglePixelWidth();
  7421. }
  7422. var xw = x + width;
  7423. var yh = y + height;
  7424. this.ctx.moveTo(x, y);
  7425. this.ctx.lineTo(xw, y);
  7426. this.ctx.lineTo(xw, yh);
  7427. this.ctx.lineTo(x, yh);
  7428. this.ctx.lineTo(x, y);
  7429. this.ctx.closePath();
  7430. break;
  7431. case OPS.moveTo:
  7432. x = args[j++];
  7433. y = args[j++];
  7434. ctx.moveTo(x, y);
  7435. break;
  7436. case OPS.lineTo:
  7437. x = args[j++];
  7438. y = args[j++];
  7439. ctx.lineTo(x, y);
  7440. break;
  7441. case OPS.curveTo:
  7442. x = args[j + 4];
  7443. y = args[j + 5];
  7444. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7445. j += 6;
  7446. break;
  7447. case OPS.curveTo2:
  7448. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7449. x = args[j + 2];
  7450. y = args[j + 3];
  7451. j += 4;
  7452. break;
  7453. case OPS.curveTo3:
  7454. x = args[j + 2];
  7455. y = args[j + 3];
  7456. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7457. j += 4;
  7458. break;
  7459. case OPS.closePath:
  7460. ctx.closePath();
  7461. break;
  7462. }
  7463. }
  7464. current.setCurrentPoint(x, y);
  7465. },
  7466. closePath: function CanvasGraphics_closePath() {
  7467. this.ctx.closePath();
  7468. },
  7469. stroke: function CanvasGraphics_stroke(consumePath) {
  7470. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7471. var ctx = this.ctx;
  7472. var strokeColor = this.current.strokeColor;
  7473. // Prevent drawing too thin lines by enforcing a minimum line width.
  7474. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  7475. // For stroke we want to temporarily change the global alpha to the
  7476. // stroking alpha.
  7477. ctx.globalAlpha = this.current.strokeAlpha;
  7478. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  7479. // for patterns, we transform to pattern space, calculate
  7480. // the pattern, call stroke, and restore to user space
  7481. ctx.save();
  7482. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7483. ctx.stroke();
  7484. ctx.restore();
  7485. } else {
  7486. ctx.stroke();
  7487. }
  7488. if (consumePath) {
  7489. this.consumePath();
  7490. }
  7491. // Restore the global alpha to the fill alpha
  7492. ctx.globalAlpha = this.current.fillAlpha;
  7493. },
  7494. closeStroke: function CanvasGraphics_closeStroke() {
  7495. this.closePath();
  7496. this.stroke();
  7497. },
  7498. fill: function CanvasGraphics_fill(consumePath) {
  7499. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7500. var ctx = this.ctx;
  7501. var fillColor = this.current.fillColor;
  7502. var isPatternFill = this.current.patternFill;
  7503. var needRestore = false;
  7504. if (isPatternFill) {
  7505. ctx.save();
  7506. if (this.baseTransform) {
  7507. ctx.setTransform.apply(ctx, this.baseTransform);
  7508. }
  7509. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7510. needRestore = true;
  7511. }
  7512. if (this.pendingEOFill) {
  7513. if (ctx.mozFillRule !== undefined) {
  7514. ctx.mozFillRule = 'evenodd';
  7515. ctx.fill();
  7516. ctx.mozFillRule = 'nonzero';
  7517. } else {
  7518. ctx.fill('evenodd');
  7519. }
  7520. this.pendingEOFill = false;
  7521. } else {
  7522. ctx.fill();
  7523. }
  7524. if (needRestore) {
  7525. ctx.restore();
  7526. }
  7527. if (consumePath) {
  7528. this.consumePath();
  7529. }
  7530. },
  7531. eoFill: function CanvasGraphics_eoFill() {
  7532. this.pendingEOFill = true;
  7533. this.fill();
  7534. },
  7535. fillStroke: function CanvasGraphics_fillStroke() {
  7536. this.fill(false);
  7537. this.stroke(false);
  7538. this.consumePath();
  7539. },
  7540. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7541. this.pendingEOFill = true;
  7542. this.fillStroke();
  7543. },
  7544. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7545. this.closePath();
  7546. this.fillStroke();
  7547. },
  7548. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7549. this.pendingEOFill = true;
  7550. this.closePath();
  7551. this.fillStroke();
  7552. },
  7553. endPath: function CanvasGraphics_endPath() {
  7554. this.consumePath();
  7555. },
  7556. // Clipping
  7557. clip: function CanvasGraphics_clip() {
  7558. this.pendingClip = NORMAL_CLIP;
  7559. },
  7560. eoClip: function CanvasGraphics_eoClip() {
  7561. this.pendingClip = EO_CLIP;
  7562. },
  7563. // Text
  7564. beginText: function CanvasGraphics_beginText() {
  7565. this.current.textMatrix = IDENTITY_MATRIX;
  7566. this.current.textMatrixScale = 1;
  7567. this.current.x = this.current.lineX = 0;
  7568. this.current.y = this.current.lineY = 0;
  7569. },
  7570. endText: function CanvasGraphics_endText() {
  7571. var paths = this.pendingTextPaths;
  7572. var ctx = this.ctx;
  7573. if (paths === undefined) {
  7574. ctx.beginPath();
  7575. return;
  7576. }
  7577. ctx.save();
  7578. ctx.beginPath();
  7579. for (var i = 0; i < paths.length; i++) {
  7580. var path = paths[i];
  7581. ctx.setTransform.apply(ctx, path.transform);
  7582. ctx.translate(path.x, path.y);
  7583. path.addToPath(ctx, path.fontSize);
  7584. }
  7585. ctx.restore();
  7586. ctx.clip();
  7587. ctx.beginPath();
  7588. delete this.pendingTextPaths;
  7589. },
  7590. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7591. this.current.charSpacing = spacing;
  7592. },
  7593. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7594. this.current.wordSpacing = spacing;
  7595. },
  7596. setHScale: function CanvasGraphics_setHScale(scale) {
  7597. this.current.textHScale = scale / 100;
  7598. },
  7599. setLeading: function CanvasGraphics_setLeading(leading) {
  7600. this.current.leading = -leading;
  7601. },
  7602. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7603. var fontObj = this.commonObjs.get(fontRefName);
  7604. var current = this.current;
  7605. if (!fontObj) {
  7606. error('Can\'t find font for ' + fontRefName);
  7607. }
  7608. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  7609. // A valid matrix needs all main diagonal elements to be non-zero
  7610. // This also ensures we bypass FF bugzilla bug #719844.
  7611. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7612. warn('Invalid font matrix for font ' + fontRefName);
  7613. }
  7614. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7615. // and in some docs this can be negative (inverted x-y axes).
  7616. if (size < 0) {
  7617. size = -size;
  7618. current.fontDirection = -1;
  7619. } else {
  7620. current.fontDirection = 1;
  7621. }
  7622. this.current.font = fontObj;
  7623. this.current.fontSize = size;
  7624. if (fontObj.isType3Font) {
  7625. return;
  7626. }
  7627. // we don't need ctx.font for Type3 fonts
  7628. var name = fontObj.loadedName || 'sans-serif';
  7629. var bold = fontObj.black ? fontObj.bold ? '900' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  7630. var italic = fontObj.italic ? 'italic' : 'normal';
  7631. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7632. // Some font backends cannot handle fonts below certain size.
  7633. // Keeping the font at minimal size and using the fontSizeScale to change
  7634. // the current transformation matrix before the fillText/strokeText.
  7635. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7636. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7637. this.current.fontSizeScale = size / browserFontSize;
  7638. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7639. this.ctx.font = rule;
  7640. },
  7641. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7642. this.current.textRenderingMode = mode;
  7643. },
  7644. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7645. this.current.textRise = rise;
  7646. },
  7647. moveText: function CanvasGraphics_moveText(x, y) {
  7648. this.current.x = this.current.lineX += x;
  7649. this.current.y = this.current.lineY += y;
  7650. },
  7651. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7652. this.setLeading(-y);
  7653. this.moveText(x, y);
  7654. },
  7655. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7656. this.current.textMatrix = [
  7657. a,
  7658. b,
  7659. c,
  7660. d,
  7661. e,
  7662. f
  7663. ];
  7664. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7665. this.current.x = this.current.lineX = 0;
  7666. this.current.y = this.current.lineY = 0;
  7667. },
  7668. nextLine: function CanvasGraphics_nextLine() {
  7669. this.moveText(0, this.current.leading);
  7670. },
  7671. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7672. var ctx = this.ctx;
  7673. var current = this.current;
  7674. var font = current.font;
  7675. var textRenderingMode = current.textRenderingMode;
  7676. var fontSize = current.fontSize / current.fontSizeScale;
  7677. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7678. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7679. var addToPath;
  7680. if (font.disableFontFace || isAddToPathSet) {
  7681. addToPath = font.getPathGenerator(this.commonObjs, character);
  7682. }
  7683. if (font.disableFontFace) {
  7684. ctx.save();
  7685. ctx.translate(x, y);
  7686. ctx.beginPath();
  7687. addToPath(ctx, fontSize);
  7688. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7689. ctx.fill();
  7690. }
  7691. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7692. ctx.stroke();
  7693. }
  7694. ctx.restore();
  7695. } else {
  7696. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7697. ctx.fillText(character, x, y);
  7698. }
  7699. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7700. ctx.strokeText(character, x, y);
  7701. }
  7702. }
  7703. if (isAddToPathSet) {
  7704. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7705. paths.push({
  7706. transform: ctx.mozCurrentTransform,
  7707. x: x,
  7708. y: y,
  7709. fontSize: fontSize,
  7710. addToPath: addToPath
  7711. });
  7712. }
  7713. },
  7714. get isFontSubpixelAAEnabled() {
  7715. // Checks if anti-aliasing is enabled when scaled text is painted.
  7716. // On Windows GDI scaled fonts looks bad.
  7717. var ctx = document.createElement('canvas').getContext('2d');
  7718. ctx.scale(1.5, 1);
  7719. ctx.fillText('I', 0, 10);
  7720. var data = ctx.getImageData(0, 0, 10, 10).data;
  7721. var enabled = false;
  7722. for (var i = 3; i < data.length; i += 4) {
  7723. if (data[i] > 0 && data[i] < 255) {
  7724. enabled = true;
  7725. break;
  7726. }
  7727. }
  7728. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7729. },
  7730. showText: function CanvasGraphics_showText(glyphs) {
  7731. var current = this.current;
  7732. var font = current.font;
  7733. if (font.isType3Font) {
  7734. return this.showType3Text(glyphs);
  7735. }
  7736. var fontSize = current.fontSize;
  7737. if (fontSize === 0) {
  7738. return;
  7739. }
  7740. var ctx = this.ctx;
  7741. var fontSizeScale = current.fontSizeScale;
  7742. var charSpacing = current.charSpacing;
  7743. var wordSpacing = current.wordSpacing;
  7744. var fontDirection = current.fontDirection;
  7745. var textHScale = current.textHScale * fontDirection;
  7746. var glyphsLength = glyphs.length;
  7747. var vertical = font.vertical;
  7748. var spacingDir = vertical ? 1 : -1;
  7749. var defaultVMetrics = font.defaultVMetrics;
  7750. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7751. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  7752. ctx.save();
  7753. ctx.transform.apply(ctx, current.textMatrix);
  7754. ctx.translate(current.x, current.y + current.textRise);
  7755. if (current.patternFill) {
  7756. // TODO: Some shading patterns are not applied correctly to text,
  7757. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7758. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7759. }
  7760. if (fontDirection > 0) {
  7761. ctx.scale(textHScale, -1);
  7762. } else {
  7763. ctx.scale(textHScale, 1);
  7764. }
  7765. var lineWidth = current.lineWidth;
  7766. var scale = current.textMatrixScale;
  7767. if (scale === 0 || lineWidth === 0) {
  7768. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7769. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7770. this.cachedGetSinglePixelWidth = null;
  7771. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7772. }
  7773. } else {
  7774. lineWidth /= scale;
  7775. }
  7776. if (fontSizeScale !== 1.0) {
  7777. ctx.scale(fontSizeScale, fontSizeScale);
  7778. lineWidth /= fontSizeScale;
  7779. }
  7780. ctx.lineWidth = lineWidth;
  7781. var x = 0, i;
  7782. for (i = 0; i < glyphsLength; ++i) {
  7783. var glyph = glyphs[i];
  7784. if (isNum(glyph)) {
  7785. x += spacingDir * glyph * fontSize / 1000;
  7786. continue;
  7787. }
  7788. var restoreNeeded = false;
  7789. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7790. var character = glyph.fontChar;
  7791. var accent = glyph.accent;
  7792. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7793. var width = glyph.width;
  7794. if (vertical) {
  7795. var vmetric, vx, vy;
  7796. vmetric = glyph.vmetric || defaultVMetrics;
  7797. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7798. vx = -vx * widthAdvanceScale;
  7799. vy = vmetric[2] * widthAdvanceScale;
  7800. width = vmetric ? -vmetric[0] : width;
  7801. scaledX = vx / fontSizeScale;
  7802. scaledY = (x + vy) / fontSizeScale;
  7803. } else {
  7804. scaledX = x / fontSizeScale;
  7805. scaledY = 0;
  7806. }
  7807. if (font.remeasure && width > 0) {
  7808. // Some standard fonts may not have the exact width: rescale per
  7809. // character if measured width is greater than expected glyph width
  7810. // and subpixel-aa is enabled, otherwise just center the glyph.
  7811. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7812. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7813. var characterScaleX = width / measuredWidth;
  7814. restoreNeeded = true;
  7815. ctx.save();
  7816. ctx.scale(characterScaleX, 1);
  7817. scaledX /= characterScaleX;
  7818. } else if (width !== measuredWidth) {
  7819. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7820. }
  7821. }
  7822. // Only attempt to draw the glyph if it is actually in the embedded font
  7823. // file or if there isn't a font file so the fallback font is shown.
  7824. if (glyph.isInFont || font.missingFile) {
  7825. if (simpleFillText && !accent) {
  7826. // common case
  7827. ctx.fillText(character, scaledX, scaledY);
  7828. } else {
  7829. this.paintChar(character, scaledX, scaledY);
  7830. if (accent) {
  7831. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7832. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7833. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7834. }
  7835. }
  7836. }
  7837. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7838. x += charWidth;
  7839. if (restoreNeeded) {
  7840. ctx.restore();
  7841. }
  7842. }
  7843. if (vertical) {
  7844. current.y -= x * textHScale;
  7845. } else {
  7846. current.x += x * textHScale;
  7847. }
  7848. ctx.restore();
  7849. },
  7850. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7851. // Type3 fonts - each glyph is a "mini-PDF"
  7852. var ctx = this.ctx;
  7853. var current = this.current;
  7854. var font = current.font;
  7855. var fontSize = current.fontSize;
  7856. var fontDirection = current.fontDirection;
  7857. var spacingDir = font.vertical ? 1 : -1;
  7858. var charSpacing = current.charSpacing;
  7859. var wordSpacing = current.wordSpacing;
  7860. var textHScale = current.textHScale * fontDirection;
  7861. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7862. var glyphsLength = glyphs.length;
  7863. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7864. var i, glyph, width, spacingLength;
  7865. if (isTextInvisible || fontSize === 0) {
  7866. return;
  7867. }
  7868. this.cachedGetSinglePixelWidth = null;
  7869. ctx.save();
  7870. ctx.transform.apply(ctx, current.textMatrix);
  7871. ctx.translate(current.x, current.y);
  7872. ctx.scale(textHScale, fontDirection);
  7873. for (i = 0; i < glyphsLength; ++i) {
  7874. glyph = glyphs[i];
  7875. if (isNum(glyph)) {
  7876. spacingLength = spacingDir * glyph * fontSize / 1000;
  7877. this.ctx.translate(spacingLength, 0);
  7878. current.x += spacingLength * textHScale;
  7879. continue;
  7880. }
  7881. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7882. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7883. if (!operatorList) {
  7884. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7885. continue;
  7886. }
  7887. this.processingType3 = glyph;
  7888. this.save();
  7889. ctx.scale(fontSize, fontSize);
  7890. ctx.transform.apply(ctx, fontMatrix);
  7891. this.executeOperatorList(operatorList);
  7892. this.restore();
  7893. var transformed = Util.applyTransform([
  7894. glyph.width,
  7895. 0
  7896. ], fontMatrix);
  7897. width = transformed[0] * fontSize + spacing;
  7898. ctx.translate(width, 0);
  7899. current.x += width * textHScale;
  7900. }
  7901. ctx.restore();
  7902. this.processingType3 = null;
  7903. },
  7904. // Type3 fonts
  7905. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7906. },
  7907. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7908. // TODO According to the spec we're also suppose to ignore any operators
  7909. // that set color or include images while processing this type3 font.
  7910. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7911. this.clip();
  7912. this.endPath();
  7913. },
  7914. // Color
  7915. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7916. var pattern;
  7917. if (IR[0] === 'TilingPattern') {
  7918. var color = IR[1];
  7919. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7920. var self = this;
  7921. var canvasGraphicsFactory = {
  7922. createCanvasGraphics: function (ctx) {
  7923. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7924. }
  7925. };
  7926. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7927. } else {
  7928. pattern = getShadingPatternFromIR(IR);
  7929. }
  7930. return pattern;
  7931. },
  7932. setStrokeColorN: function CanvasGraphics_setStrokeColorN()
  7933. /*...*/
  7934. {
  7935. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7936. },
  7937. setFillColorN: function CanvasGraphics_setFillColorN()
  7938. /*...*/
  7939. {
  7940. this.current.fillColor = this.getColorN_Pattern(arguments);
  7941. this.current.patternFill = true;
  7942. },
  7943. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7944. var color = Util.makeCssRgb(r, g, b);
  7945. this.ctx.strokeStyle = color;
  7946. this.current.strokeColor = color;
  7947. },
  7948. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7949. var color = Util.makeCssRgb(r, g, b);
  7950. this.ctx.fillStyle = color;
  7951. this.current.fillColor = color;
  7952. this.current.patternFill = false;
  7953. },
  7954. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7955. var ctx = this.ctx;
  7956. this.save();
  7957. var pattern = getShadingPatternFromIR(patternIR);
  7958. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7959. var inv = ctx.mozCurrentTransformInverse;
  7960. if (inv) {
  7961. var canvas = ctx.canvas;
  7962. var width = canvas.width;
  7963. var height = canvas.height;
  7964. var bl = Util.applyTransform([
  7965. 0,
  7966. 0
  7967. ], inv);
  7968. var br = Util.applyTransform([
  7969. 0,
  7970. height
  7971. ], inv);
  7972. var ul = Util.applyTransform([
  7973. width,
  7974. 0
  7975. ], inv);
  7976. var ur = Util.applyTransform([
  7977. width,
  7978. height
  7979. ], inv);
  7980. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7981. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7982. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7983. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7984. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7985. } else {
  7986. // HACK to draw the gradient onto an infinite rectangle.
  7987. // PDF gradients are drawn across the entire image while
  7988. // Canvas only allows gradients to be drawn in a rectangle
  7989. // The following bug should allow us to remove this.
  7990. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7991. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7992. }
  7993. this.restore();
  7994. },
  7995. // Images
  7996. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7997. error('Should not call beginInlineImage');
  7998. },
  7999. beginImageData: function CanvasGraphics_beginImageData() {
  8000. error('Should not call beginImageData');
  8001. },
  8002. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  8003. this.save();
  8004. this.baseTransformStack.push(this.baseTransform);
  8005. if (isArray(matrix) && 6 === matrix.length) {
  8006. this.transform.apply(this, matrix);
  8007. }
  8008. this.baseTransform = this.ctx.mozCurrentTransform;
  8009. if (isArray(bbox) && 4 === bbox.length) {
  8010. var width = bbox[2] - bbox[0];
  8011. var height = bbox[3] - bbox[1];
  8012. this.ctx.rect(bbox[0], bbox[1], width, height);
  8013. this.clip();
  8014. this.endPath();
  8015. }
  8016. },
  8017. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  8018. this.restore();
  8019. this.baseTransform = this.baseTransformStack.pop();
  8020. },
  8021. beginGroup: function CanvasGraphics_beginGroup(group) {
  8022. this.save();
  8023. var currentCtx = this.ctx;
  8024. // TODO non-isolated groups - according to Rik at adobe non-isolated
  8025. // group results aren't usually that different and they even have tools
  8026. // that ignore this setting. Notes from Rik on implementing:
  8027. // - When you encounter an transparency group, create a new canvas with
  8028. // the dimensions of the bbox
  8029. // - copy the content from the previous canvas to the new canvas
  8030. // - draw as usual
  8031. // - remove the backdrop alpha:
  8032. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  8033. // value of your transparency group and 'alphaBackdrop' the alpha of the
  8034. // backdrop
  8035. // - remove background color:
  8036. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  8037. if (!group.isolated) {
  8038. info('TODO: Support non-isolated groups.');
  8039. }
  8040. // TODO knockout - supposedly possible with the clever use of compositing
  8041. // modes.
  8042. if (group.knockout) {
  8043. warn('Knockout groups not supported.');
  8044. }
  8045. var currentTransform = currentCtx.mozCurrentTransform;
  8046. if (group.matrix) {
  8047. currentCtx.transform.apply(currentCtx, group.matrix);
  8048. }
  8049. assert(group.bbox, 'Bounding box is required.');
  8050. // Based on the current transform figure out how big the bounding box
  8051. // will actually be.
  8052. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  8053. // Clip the bounding box to the current canvas.
  8054. var canvasBounds = [
  8055. 0,
  8056. 0,
  8057. currentCtx.canvas.width,
  8058. currentCtx.canvas.height
  8059. ];
  8060. bounds = Util.intersect(bounds, canvasBounds) || [
  8061. 0,
  8062. 0,
  8063. 0,
  8064. 0
  8065. ];
  8066. // Use ceil in case we're between sizes so we don't create canvas that is
  8067. // too small and make the canvas at least 1x1 pixels.
  8068. var offsetX = Math.floor(bounds[0]);
  8069. var offsetY = Math.floor(bounds[1]);
  8070. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8071. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8072. var scaleX = 1, scaleY = 1;
  8073. if (drawnWidth > MAX_GROUP_SIZE) {
  8074. scaleX = drawnWidth / MAX_GROUP_SIZE;
  8075. drawnWidth = MAX_GROUP_SIZE;
  8076. }
  8077. if (drawnHeight > MAX_GROUP_SIZE) {
  8078. scaleY = drawnHeight / MAX_GROUP_SIZE;
  8079. drawnHeight = MAX_GROUP_SIZE;
  8080. }
  8081. var cacheId = 'groupAt' + this.groupLevel;
  8082. if (group.smask) {
  8083. // Using two cache entries is case if masks are used one after another.
  8084. cacheId += '_smask_' + this.smaskCounter++ % 2;
  8085. }
  8086. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  8087. var groupCtx = scratchCanvas.context;
  8088. // Since we created a new canvas that is just the size of the bounding box
  8089. // we have to translate the group ctx.
  8090. groupCtx.scale(1 / scaleX, 1 / scaleY);
  8091. groupCtx.translate(-offsetX, -offsetY);
  8092. groupCtx.transform.apply(groupCtx, currentTransform);
  8093. if (group.smask) {
  8094. // Saving state and cached mask to be used in setGState.
  8095. this.smaskStack.push({
  8096. canvas: scratchCanvas.canvas,
  8097. context: groupCtx,
  8098. offsetX: offsetX,
  8099. offsetY: offsetY,
  8100. scaleX: scaleX,
  8101. scaleY: scaleY,
  8102. subtype: group.smask.subtype,
  8103. backdrop: group.smask.backdrop,
  8104. transferMap: group.smask.transferMap || null,
  8105. startTransformInverse: null
  8106. });
  8107. } else
  8108. // used during suspend operation
  8109. {
  8110. // Setup the current ctx so when the group is popped we draw it at the
  8111. // right location.
  8112. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8113. currentCtx.translate(offsetX, offsetY);
  8114. currentCtx.scale(scaleX, scaleY);
  8115. }
  8116. // The transparency group inherits all off the current graphics state
  8117. // except the blend mode, soft mask, and alpha constants.
  8118. copyCtxState(currentCtx, groupCtx);
  8119. this.ctx = groupCtx;
  8120. this.setGState([
  8121. [
  8122. 'BM',
  8123. 'Normal'
  8124. ],
  8125. [
  8126. 'ca',
  8127. 1
  8128. ],
  8129. [
  8130. 'CA',
  8131. 1
  8132. ]
  8133. ]);
  8134. this.groupStack.push(currentCtx);
  8135. this.groupLevel++;
  8136. // Reseting mask state, masks will be applied on restore of the group.
  8137. this.current.activeSMask = null;
  8138. },
  8139. endGroup: function CanvasGraphics_endGroup(group) {
  8140. this.groupLevel--;
  8141. var groupCtx = this.ctx;
  8142. this.ctx = this.groupStack.pop();
  8143. // Turn off image smoothing to avoid sub pixel interpolation which can
  8144. // look kind of blurry for some pdfs.
  8145. if (this.ctx.imageSmoothingEnabled !== undefined) {
  8146. this.ctx.imageSmoothingEnabled = false;
  8147. } else {
  8148. this.ctx.mozImageSmoothingEnabled = false;
  8149. }
  8150. if (group.smask) {
  8151. this.tempSMask = this.smaskStack.pop();
  8152. } else {
  8153. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8154. }
  8155. this.restore();
  8156. },
  8157. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  8158. this.save();
  8159. this.current = new CanvasExtraState();
  8160. if (this.baseTransform) {
  8161. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  8162. }
  8163. },
  8164. endAnnotations: function CanvasGraphics_endAnnotations() {
  8165. this.restore();
  8166. },
  8167. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  8168. this.save();
  8169. if (isArray(rect) && 4 === rect.length) {
  8170. var width = rect[2] - rect[0];
  8171. var height = rect[3] - rect[1];
  8172. this.ctx.rect(rect[0], rect[1], width, height);
  8173. this.clip();
  8174. this.endPath();
  8175. }
  8176. this.transform.apply(this, transform);
  8177. this.transform.apply(this, matrix);
  8178. },
  8179. endAnnotation: function CanvasGraphics_endAnnotation() {
  8180. this.restore();
  8181. },
  8182. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  8183. var domImage = this.objs.get(objId);
  8184. if (!domImage) {
  8185. warn('Dependent image isn\'t ready yet');
  8186. return;
  8187. }
  8188. this.save();
  8189. var ctx = this.ctx;
  8190. // scale the image to the unit square
  8191. ctx.scale(1 / w, -1 / h);
  8192. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  8193. if (this.imageLayer) {
  8194. var currentTransform = ctx.mozCurrentTransformInverse;
  8195. var position = this.getCanvasPosition(0, 0);
  8196. this.imageLayer.appendImage({
  8197. objId: objId,
  8198. left: position[0],
  8199. top: position[1],
  8200. width: w / currentTransform[0],
  8201. height: h / currentTransform[3]
  8202. });
  8203. }
  8204. this.restore();
  8205. },
  8206. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  8207. var ctx = this.ctx;
  8208. var width = img.width, height = img.height;
  8209. var fillColor = this.current.fillColor;
  8210. var isPatternFill = this.current.patternFill;
  8211. var glyph = this.processingType3;
  8212. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  8213. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  8214. glyph.compiled = compileType3Glyph({
  8215. data: img.data,
  8216. width: width,
  8217. height: height
  8218. });
  8219. } else {
  8220. glyph.compiled = null;
  8221. }
  8222. }
  8223. if (glyph && glyph.compiled) {
  8224. glyph.compiled(ctx);
  8225. return;
  8226. }
  8227. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8228. var maskCtx = maskCanvas.context;
  8229. maskCtx.save();
  8230. putBinaryImageMask(maskCtx, img);
  8231. maskCtx.globalCompositeOperation = 'source-in';
  8232. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8233. maskCtx.fillRect(0, 0, width, height);
  8234. maskCtx.restore();
  8235. this.paintInlineImageXObject(maskCanvas.canvas);
  8236. },
  8237. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  8238. var width = imgData.width;
  8239. var height = imgData.height;
  8240. var fillColor = this.current.fillColor;
  8241. var isPatternFill = this.current.patternFill;
  8242. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8243. var maskCtx = maskCanvas.context;
  8244. maskCtx.save();
  8245. putBinaryImageMask(maskCtx, imgData);
  8246. maskCtx.globalCompositeOperation = 'source-in';
  8247. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8248. maskCtx.fillRect(0, 0, width, height);
  8249. maskCtx.restore();
  8250. var ctx = this.ctx;
  8251. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8252. ctx.save();
  8253. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  8254. ctx.scale(1, -1);
  8255. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8256. ctx.restore();
  8257. }
  8258. },
  8259. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  8260. var ctx = this.ctx;
  8261. var fillColor = this.current.fillColor;
  8262. var isPatternFill = this.current.patternFill;
  8263. for (var i = 0, ii = images.length; i < ii; i++) {
  8264. var image = images[i];
  8265. var width = image.width, height = image.height;
  8266. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8267. var maskCtx = maskCanvas.context;
  8268. maskCtx.save();
  8269. putBinaryImageMask(maskCtx, image);
  8270. maskCtx.globalCompositeOperation = 'source-in';
  8271. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8272. maskCtx.fillRect(0, 0, width, height);
  8273. maskCtx.restore();
  8274. ctx.save();
  8275. ctx.transform.apply(ctx, image.transform);
  8276. ctx.scale(1, -1);
  8277. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8278. ctx.restore();
  8279. }
  8280. },
  8281. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  8282. var imgData = this.objs.get(objId);
  8283. if (!imgData) {
  8284. warn('Dependent image isn\'t ready yet');
  8285. return;
  8286. }
  8287. this.paintInlineImageXObject(imgData);
  8288. },
  8289. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8290. var imgData = this.objs.get(objId);
  8291. if (!imgData) {
  8292. warn('Dependent image isn\'t ready yet');
  8293. return;
  8294. }
  8295. var width = imgData.width;
  8296. var height = imgData.height;
  8297. var map = [];
  8298. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8299. map.push({
  8300. transform: [
  8301. scaleX,
  8302. 0,
  8303. 0,
  8304. scaleY,
  8305. positions[i],
  8306. positions[i + 1]
  8307. ],
  8308. x: 0,
  8309. y: 0,
  8310. w: width,
  8311. h: height
  8312. });
  8313. }
  8314. this.paintInlineImageXObjectGroup(imgData, map);
  8315. },
  8316. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  8317. var width = imgData.width;
  8318. var height = imgData.height;
  8319. var ctx = this.ctx;
  8320. this.save();
  8321. // scale the image to the unit square
  8322. ctx.scale(1 / width, -1 / height);
  8323. var currentTransform = ctx.mozCurrentTransformInverse;
  8324. var a = currentTransform[0], b = currentTransform[1];
  8325. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8326. var c = currentTransform[2], d = currentTransform[3];
  8327. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8328. var imgToPaint, tmpCanvas;
  8329. // instanceof HTMLElement does not work in jsdom node.js module
  8330. if (imgData instanceof HTMLElement || !imgData.data) {
  8331. imgToPaint = imgData;
  8332. } else {
  8333. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  8334. var tmpCtx = tmpCanvas.context;
  8335. putBinaryImageData(tmpCtx, imgData);
  8336. imgToPaint = tmpCanvas.canvas;
  8337. }
  8338. var paintWidth = width, paintHeight = height;
  8339. var tmpCanvasId = 'prescale1';
  8340. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8341. // pixels during drawImage operation, painting on the temporary canvas(es)
  8342. // that are twice smaller in size
  8343. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  8344. var newWidth = paintWidth, newHeight = paintHeight;
  8345. if (widthScale > 2 && paintWidth > 1) {
  8346. newWidth = Math.ceil(paintWidth / 2);
  8347. widthScale /= paintWidth / newWidth;
  8348. }
  8349. if (heightScale > 2 && paintHeight > 1) {
  8350. newHeight = Math.ceil(paintHeight / 2);
  8351. heightScale /= paintHeight / newHeight;
  8352. }
  8353. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  8354. tmpCtx = tmpCanvas.context;
  8355. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8356. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  8357. imgToPaint = tmpCanvas.canvas;
  8358. paintWidth = newWidth;
  8359. paintHeight = newHeight;
  8360. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8361. }
  8362. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  8363. if (this.imageLayer) {
  8364. var position = this.getCanvasPosition(0, -height);
  8365. this.imageLayer.appendImage({
  8366. imgData: imgData,
  8367. left: position[0],
  8368. top: position[1],
  8369. width: width / currentTransform[0],
  8370. height: height / currentTransform[3]
  8371. });
  8372. }
  8373. this.restore();
  8374. },
  8375. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8376. var ctx = this.ctx;
  8377. var w = imgData.width;
  8378. var h = imgData.height;
  8379. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8380. var tmpCtx = tmpCanvas.context;
  8381. putBinaryImageData(tmpCtx, imgData);
  8382. for (var i = 0, ii = map.length; i < ii; i++) {
  8383. var entry = map[i];
  8384. ctx.save();
  8385. ctx.transform.apply(ctx, entry.transform);
  8386. ctx.scale(1, -1);
  8387. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8388. if (this.imageLayer) {
  8389. var position = this.getCanvasPosition(entry.x, entry.y);
  8390. this.imageLayer.appendImage({
  8391. imgData: imgData,
  8392. left: position[0],
  8393. top: position[1],
  8394. width: w,
  8395. height: h
  8396. });
  8397. }
  8398. ctx.restore();
  8399. }
  8400. },
  8401. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  8402. this.ctx.fillRect(0, 0, 1, 1);
  8403. },
  8404. paintXObject: function CanvasGraphics_paintXObject() {
  8405. warn('Unsupported \'paintXObject\' command.');
  8406. },
  8407. // Marked content
  8408. markPoint: function CanvasGraphics_markPoint(tag) {
  8409. },
  8410. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8411. },
  8412. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8413. },
  8414. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  8415. },
  8416. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8417. },
  8418. // Compatibility
  8419. beginCompat: function CanvasGraphics_beginCompat() {
  8420. },
  8421. endCompat: function CanvasGraphics_endCompat() {
  8422. },
  8423. // Helper functions
  8424. consumePath: function CanvasGraphics_consumePath() {
  8425. var ctx = this.ctx;
  8426. if (this.pendingClip) {
  8427. if (this.pendingClip === EO_CLIP) {
  8428. if (ctx.mozFillRule !== undefined) {
  8429. ctx.mozFillRule = 'evenodd';
  8430. ctx.clip();
  8431. ctx.mozFillRule = 'nonzero';
  8432. } else {
  8433. ctx.clip('evenodd');
  8434. }
  8435. } else {
  8436. ctx.clip();
  8437. }
  8438. this.pendingClip = null;
  8439. }
  8440. ctx.beginPath();
  8441. },
  8442. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8443. if (this.cachedGetSinglePixelWidth === null) {
  8444. // NOTE: The `save` and `restore` commands used below is a workaround
  8445. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8446. // from intermittently returning incorrect values in Firefox, see:
  8447. // https://github.com/mozilla/pdf.js/issues/7188.
  8448. this.ctx.save();
  8449. var inverse = this.ctx.mozCurrentTransformInverse;
  8450. this.ctx.restore();
  8451. // max of the current horizontal and vertical scale
  8452. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  8453. }
  8454. return this.cachedGetSinglePixelWidth;
  8455. },
  8456. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8457. var transform = this.ctx.mozCurrentTransform;
  8458. return [
  8459. transform[0] * x + transform[2] * y + transform[4],
  8460. transform[1] * x + transform[3] * y + transform[5]
  8461. ];
  8462. }
  8463. };
  8464. for (var op in OPS) {
  8465. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8466. }
  8467. return CanvasGraphics;
  8468. }();
  8469. exports.CanvasGraphics = CanvasGraphics;
  8470. exports.createScratchCanvas = createScratchCanvas;
  8471. }));
  8472. (function (root, factory) {
  8473. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8474. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  8475. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8476. var MessageHandler = sharedUtil.MessageHandler;
  8477. var MissingPDFException = sharedUtil.MissingPDFException;
  8478. var PageViewport = sharedUtil.PageViewport;
  8479. var PasswordResponses = sharedUtil.PasswordResponses;
  8480. var PasswordException = sharedUtil.PasswordException;
  8481. var StatTimer = sharedUtil.StatTimer;
  8482. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8483. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8484. var Util = sharedUtil.Util;
  8485. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8486. var error = sharedUtil.error;
  8487. var deprecated = sharedUtil.deprecated;
  8488. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8489. var info = sharedUtil.info;
  8490. var isInt = sharedUtil.isInt;
  8491. var isArray = sharedUtil.isArray;
  8492. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8493. var isSameOrigin = sharedUtil.isSameOrigin;
  8494. var loadJpegStream = sharedUtil.loadJpegStream;
  8495. var stringToBytes = sharedUtil.stringToBytes;
  8496. var globalScope = sharedUtil.globalScope;
  8497. var warn = sharedUtil.warn;
  8498. var FontFaceObject = displayFontLoader.FontFaceObject;
  8499. var FontLoader = displayFontLoader.FontLoader;
  8500. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8501. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8502. var Metadata = displayMetadata.Metadata;
  8503. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8504. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  8505. // 2^16 = 65536
  8506. var isWorkerDisabled = false;
  8507. var workerSrc;
  8508. var isPostMessageTransfersDisabled = false;
  8509. var fakeWorkerFilesLoader = null;
  8510. var useRequireEnsure = false;
  8511. // For GENERIC build we need add support of different fake file loaders
  8512. // for different frameworks.
  8513. if (typeof window === 'undefined') {
  8514. // node.js - disable worker and set require.ensure.
  8515. isWorkerDisabled = true;
  8516. if (typeof require.ensure === 'undefined') {
  8517. require.ensure = require('node-ensure');
  8518. }
  8519. useRequireEnsure = true;
  8520. }
  8521. if (typeof __webpack_require__ !== 'undefined') {
  8522. useRequireEnsure = true;
  8523. }
  8524. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8525. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8526. }
  8527. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8528. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  8529. require.ensure([], function () {
  8530. var worker = require('./pdf.worker.js');
  8531. callback(worker.WorkerMessageHandler);
  8532. });
  8533. } : dynamicLoaderSupported ? function (callback) {
  8534. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8535. callback(worker.WorkerMessageHandler);
  8536. });
  8537. } : null;
  8538. /**
  8539. * Document initialization / loading parameters object.
  8540. *
  8541. * @typedef {Object} DocumentInitParameters
  8542. * @property {string} url - The URL of the PDF.
  8543. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8544. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8545. * use atob() to convert it to a binary string first.
  8546. * @property {Object} httpHeaders - Basic authentication headers.
  8547. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8548. * Access-Control requests should be made using credentials such as cookies
  8549. * or authorization headers. The default is false.
  8550. * @property {string} password - For decrypting password-protected PDFs.
  8551. * @property {TypedArray} initialData - A typed array with the first portion or
  8552. * all of the pdf data. Used by the extension since some data is already
  8553. * loaded before the switch to range requests.
  8554. * @property {number} length - The PDF file length. It's used for progress
  8555. * reports and range requests operations.
  8556. * @property {PDFDataRangeTransport} range
  8557. * @property {number} rangeChunkSize - Optional parameter to specify
  8558. * maximum number of bytes fetched per range request. The default value is
  8559. * 2^16 = 65536.
  8560. * @property {PDFWorker} worker - The worker that will be used for the loading
  8561. * and parsing of the PDF data.
  8562. * @property {string} docBaseUrl - (optional) The base URL of the document,
  8563. * used when attempting to recover valid absolute URLs for annotations, and
  8564. * outline items, that (incorrectly) only specify relative URLs.
  8565. */
  8566. /**
  8567. * @typedef {Object} PDFDocumentStats
  8568. * @property {Array} streamTypes - Used stream types in the document (an item
  8569. * is set to true if specific stream ID was used in the document).
  8570. * @property {Array} fontTypes - Used font type in the document (an item is set
  8571. * to true if specific font ID was used in the document).
  8572. */
  8573. /**
  8574. * This is the main entry point for loading a PDF and interacting with it.
  8575. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8576. * is used, which means it must follow the same origin rules that any XHR does
  8577. * e.g. No cross domain requests without CORS.
  8578. *
  8579. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8580. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8581. * already populated with data or parameter object.
  8582. *
  8583. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8584. * if you want to manually serve range requests for data in the PDF.
  8585. *
  8586. * @param {function} passwordCallback (deprecated) It is used to request a
  8587. * password if wrong or no password was provided. The callback receives two
  8588. * parameters: function that needs to be called with new password and reason
  8589. * (see {PasswordResponses}).
  8590. *
  8591. * @param {function} progressCallback (deprecated) It is used to be able to
  8592. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8593. * a loading bar). The callback receives an {Object} with the properties:
  8594. * {number} loaded and {number} total.
  8595. *
  8596. * @return {PDFDocumentLoadingTask}
  8597. */
  8598. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  8599. var task = new PDFDocumentLoadingTask();
  8600. // Support of the obsolete arguments (for compatibility with API v1.0)
  8601. if (arguments.length > 1) {
  8602. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  8603. }
  8604. if (pdfDataRangeTransport) {
  8605. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8606. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8607. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8608. pdfDataRangeTransport.length = src.length;
  8609. pdfDataRangeTransport.initialData = src.initialData;
  8610. if (!pdfDataRangeTransport.abort) {
  8611. pdfDataRangeTransport.abort = function () {
  8612. };
  8613. }
  8614. }
  8615. src = Object.create(src);
  8616. src.range = pdfDataRangeTransport;
  8617. }
  8618. task.onPassword = passwordCallback || null;
  8619. task.onProgress = progressCallback || null;
  8620. var source;
  8621. if (typeof src === 'string') {
  8622. source = { url: src };
  8623. } else if (isArrayBuffer(src)) {
  8624. source = { data: src };
  8625. } else if (src instanceof PDFDataRangeTransport) {
  8626. source = { range: src };
  8627. } else {
  8628. if (typeof src !== 'object') {
  8629. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  8630. }
  8631. if (!src.url && !src.data && !src.range) {
  8632. error('Invalid parameter object: need either .data, .range or .url');
  8633. }
  8634. source = src;
  8635. }
  8636. var params = {};
  8637. var rangeTransport = null;
  8638. var worker = null;
  8639. for (var key in source) {
  8640. if (key === 'url' && typeof window !== 'undefined') {
  8641. // The full path is required in the 'url' field.
  8642. params[key] = new URL(source[key], window.location).href;
  8643. continue;
  8644. } else if (key === 'range') {
  8645. rangeTransport = source[key];
  8646. continue;
  8647. } else if (key === 'worker') {
  8648. worker = source[key];
  8649. continue;
  8650. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8651. // Converting string or array-like data to Uint8Array.
  8652. var pdfBytes = source[key];
  8653. if (typeof pdfBytes === 'string') {
  8654. params[key] = stringToBytes(pdfBytes);
  8655. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  8656. params[key] = new Uint8Array(pdfBytes);
  8657. } else if (isArrayBuffer(pdfBytes)) {
  8658. params[key] = new Uint8Array(pdfBytes);
  8659. } else {
  8660. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  8661. }
  8662. continue;
  8663. }
  8664. params[key] = source[key];
  8665. }
  8666. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8667. if (!worker) {
  8668. // Worker was not provided -- creating and owning our own.
  8669. worker = new PDFWorker();
  8670. task._worker = worker;
  8671. }
  8672. var docId = task.docId;
  8673. worker.promise.then(function () {
  8674. if (task.destroyed) {
  8675. throw new Error('Loading aborted');
  8676. }
  8677. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  8678. if (task.destroyed) {
  8679. throw new Error('Loading aborted');
  8680. }
  8681. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8682. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8683. task._transport = transport;
  8684. messageHandler.send('Ready', null);
  8685. });
  8686. }).catch(task._capability.reject);
  8687. return task;
  8688. }
  8689. /**
  8690. * Starts fetching of specified PDF document/data.
  8691. * @param {PDFWorker} worker
  8692. * @param {Object} source
  8693. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8694. * @param {string} docId Unique document id, used as MessageHandler id.
  8695. * @returns {Promise} The promise, which is resolved when worker id of
  8696. * MessageHandler is known.
  8697. * @private
  8698. */
  8699. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8700. if (worker.destroyed) {
  8701. return Promise.reject(new Error('Worker was destroyed'));
  8702. }
  8703. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8704. source.disableStream = getDefaultSetting('disableStream');
  8705. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8706. if (pdfDataRangeTransport) {
  8707. source.length = pdfDataRangeTransport.length;
  8708. source.initialData = pdfDataRangeTransport.initialData;
  8709. }
  8710. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8711. docId: docId,
  8712. source: source,
  8713. disableRange: getDefaultSetting('disableRange'),
  8714. maxImageSize: getDefaultSetting('maxImageSize'),
  8715. cMapUrl: getDefaultSetting('cMapUrl'),
  8716. cMapPacked: getDefaultSetting('cMapPacked'),
  8717. disableFontFace: getDefaultSetting('disableFontFace'),
  8718. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8719. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled,
  8720. docBaseUrl: source.docBaseUrl
  8721. }).then(function (workerId) {
  8722. if (worker.destroyed) {
  8723. throw new Error('Worker was destroyed');
  8724. }
  8725. return workerId;
  8726. });
  8727. }
  8728. /**
  8729. * PDF document loading operation.
  8730. * @class
  8731. * @alias PDFDocumentLoadingTask
  8732. */
  8733. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  8734. var nextDocumentId = 0;
  8735. /** @constructs PDFDocumentLoadingTask */
  8736. function PDFDocumentLoadingTask() {
  8737. this._capability = createPromiseCapability();
  8738. this._transport = null;
  8739. this._worker = null;
  8740. /**
  8741. * Unique document loading task id -- used in MessageHandlers.
  8742. * @type {string}
  8743. */
  8744. this.docId = 'd' + nextDocumentId++;
  8745. /**
  8746. * Shows if loading task is destroyed.
  8747. * @type {boolean}
  8748. */
  8749. this.destroyed = false;
  8750. /**
  8751. * Callback to request a password if wrong or no password was provided.
  8752. * The callback receives two parameters: function that needs to be called
  8753. * with new password and reason (see {PasswordResponses}).
  8754. */
  8755. this.onPassword = null;
  8756. /**
  8757. * Callback to be able to monitor the loading progress of the PDF file
  8758. * (necessary to implement e.g. a loading bar). The callback receives
  8759. * an {Object} with the properties: {number} loaded and {number} total.
  8760. */
  8761. this.onProgress = null;
  8762. /**
  8763. * Callback to when unsupported feature is used. The callback receives
  8764. * an {UNSUPPORTED_FEATURES} argument.
  8765. */
  8766. this.onUnsupportedFeature = null;
  8767. }
  8768. PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */
  8769. {
  8770. /**
  8771. * @return {Promise}
  8772. */
  8773. get promise() {
  8774. return this._capability.promise;
  8775. },
  8776. /**
  8777. * Aborts all network requests and destroys worker.
  8778. * @return {Promise} A promise that is resolved after destruction activity
  8779. * is completed.
  8780. */
  8781. destroy: function () {
  8782. this.destroyed = true;
  8783. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  8784. return transportDestroyed.then(function () {
  8785. this._transport = null;
  8786. if (this._worker) {
  8787. this._worker.destroy();
  8788. this._worker = null;
  8789. }
  8790. }.bind(this));
  8791. },
  8792. /**
  8793. * Registers callbacks to indicate the document loading completion.
  8794. *
  8795. * @param {function} onFulfilled The callback for the loading completion.
  8796. * @param {function} onRejected The callback for the loading failure.
  8797. * @return {Promise} A promise that is resolved after the onFulfilled or
  8798. * onRejected callback.
  8799. */
  8800. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8801. return this.promise.then.apply(this.promise, arguments);
  8802. }
  8803. };
  8804. return PDFDocumentLoadingTask;
  8805. }();
  8806. /**
  8807. * Abstract class to support range requests file loading.
  8808. * @class
  8809. * @alias PDFDataRangeTransport
  8810. * @param {number} length
  8811. * @param {Uint8Array} initialData
  8812. */
  8813. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  8814. function PDFDataRangeTransport(length, initialData) {
  8815. this.length = length;
  8816. this.initialData = initialData;
  8817. this._rangeListeners = [];
  8818. this._progressListeners = [];
  8819. this._progressiveReadListeners = [];
  8820. this._readyCapability = createPromiseCapability();
  8821. }
  8822. PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */
  8823. {
  8824. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  8825. this._rangeListeners.push(listener);
  8826. },
  8827. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  8828. this._progressListeners.push(listener);
  8829. },
  8830. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8831. this._progressiveReadListeners.push(listener);
  8832. },
  8833. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8834. var listeners = this._rangeListeners;
  8835. for (var i = 0, n = listeners.length; i < n; ++i) {
  8836. listeners[i](begin, chunk);
  8837. }
  8838. },
  8839. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8840. this._readyCapability.promise.then(function () {
  8841. var listeners = this._progressListeners;
  8842. for (var i = 0, n = listeners.length; i < n; ++i) {
  8843. listeners[i](loaded);
  8844. }
  8845. }.bind(this));
  8846. },
  8847. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  8848. this._readyCapability.promise.then(function () {
  8849. var listeners = this._progressiveReadListeners;
  8850. for (var i = 0, n = listeners.length; i < n; ++i) {
  8851. listeners[i](chunk);
  8852. }
  8853. }.bind(this));
  8854. },
  8855. transportReady: function PDFDataRangeTransport_transportReady() {
  8856. this._readyCapability.resolve();
  8857. },
  8858. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  8859. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8860. },
  8861. abort: function PDFDataRangeTransport_abort() {
  8862. }
  8863. };
  8864. return PDFDataRangeTransport;
  8865. }();
  8866. /**
  8867. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8868. * properties that can be read synchronously.
  8869. * @class
  8870. * @alias PDFDocumentProxy
  8871. */
  8872. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  8873. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8874. this.pdfInfo = pdfInfo;
  8875. this.transport = transport;
  8876. this.loadingTask = loadingTask;
  8877. }
  8878. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */
  8879. {
  8880. /**
  8881. * @return {number} Total number of pages the PDF contains.
  8882. */
  8883. get numPages() {
  8884. return this.pdfInfo.numPages;
  8885. },
  8886. /**
  8887. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8888. * unique.
  8889. */
  8890. get fingerprint() {
  8891. return this.pdfInfo.fingerprint;
  8892. },
  8893. /**
  8894. * @param {number} pageNumber The page number to get. The first page is 1.
  8895. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8896. * object.
  8897. */
  8898. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8899. return this.transport.getPage(pageNumber);
  8900. },
  8901. /**
  8902. * @param {{num: number, gen: number}} ref The page reference. Must have
  8903. * the 'num' and 'gen' properties.
  8904. * @return {Promise} A promise that is resolved with the page index that is
  8905. * associated with the reference.
  8906. */
  8907. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8908. return this.transport.getPageIndex(ref);
  8909. },
  8910. /**
  8911. * @return {Promise} A promise that is resolved with a lookup table for
  8912. * mapping named destinations to reference numbers.
  8913. *
  8914. * This can be slow for large documents: use getDestination instead
  8915. */
  8916. getDestinations: function PDFDocumentProxy_getDestinations() {
  8917. return this.transport.getDestinations();
  8918. },
  8919. /**
  8920. * @param {string} id The named destination to get.
  8921. * @return {Promise} A promise that is resolved with all information
  8922. * of the given named destination.
  8923. */
  8924. getDestination: function PDFDocumentProxy_getDestination(id) {
  8925. return this.transport.getDestination(id);
  8926. },
  8927. /**
  8928. * @return {Promise} A promise that is resolved with:
  8929. * an Array containing the pageLabels that correspond to the pageIndexes,
  8930. * or `null` when no pageLabels are present in the PDF file.
  8931. */
  8932. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8933. return this.transport.getPageLabels();
  8934. },
  8935. /**
  8936. * @return {Promise} A promise that is resolved with a lookup table for
  8937. * mapping named attachments to their content.
  8938. */
  8939. getAttachments: function PDFDocumentProxy_getAttachments() {
  8940. return this.transport.getAttachments();
  8941. },
  8942. /**
  8943. * @return {Promise} A promise that is resolved with an array of all the
  8944. * JavaScript strings in the name tree.
  8945. */
  8946. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8947. return this.transport.getJavaScript();
  8948. },
  8949. /**
  8950. * @return {Promise} A promise that is resolved with an {Array} that is a
  8951. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8952. * [
  8953. * {
  8954. * title: string,
  8955. * bold: boolean,
  8956. * italic: boolean,
  8957. * color: rgb Uint8Array,
  8958. * dest: dest obj,
  8959. * url: string,
  8960. * items: array of more items like this
  8961. * },
  8962. * ...
  8963. * ].
  8964. */
  8965. getOutline: function PDFDocumentProxy_getOutline() {
  8966. return this.transport.getOutline();
  8967. },
  8968. /**
  8969. * @return {Promise} A promise that is resolved with an {Object} that has
  8970. * info and metadata properties. Info is an {Object} filled with anything
  8971. * available in the information dictionary and similarly metadata is a
  8972. * {Metadata} object with information from the metadata section of the PDF.
  8973. */
  8974. getMetadata: function PDFDocumentProxy_getMetadata() {
  8975. return this.transport.getMetadata();
  8976. },
  8977. /**
  8978. * @return {Promise} A promise that is resolved with a TypedArray that has
  8979. * the raw data from the PDF.
  8980. */
  8981. getData: function PDFDocumentProxy_getData() {
  8982. return this.transport.getData();
  8983. },
  8984. /**
  8985. * @return {Promise} A promise that is resolved when the document's data
  8986. * is loaded. It is resolved with an {Object} that contains the length
  8987. * property that indicates size of the PDF data in bytes.
  8988. */
  8989. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8990. return this.transport.downloadInfoCapability.promise;
  8991. },
  8992. /**
  8993. * @return {Promise} A promise this is resolved with current stats about
  8994. * document structures (see {@link PDFDocumentStats}).
  8995. */
  8996. getStats: function PDFDocumentProxy_getStats() {
  8997. return this.transport.getStats();
  8998. },
  8999. /**
  9000. * Cleans up resources allocated by the document, e.g. created @font-face.
  9001. */
  9002. cleanup: function PDFDocumentProxy_cleanup() {
  9003. this.transport.startCleanup();
  9004. },
  9005. /**
  9006. * Destroys current document instance and terminates worker.
  9007. */
  9008. destroy: function PDFDocumentProxy_destroy() {
  9009. return this.loadingTask.destroy();
  9010. }
  9011. };
  9012. return PDFDocumentProxy;
  9013. }();
  9014. /**
  9015. * Page getTextContent parameters.
  9016. *
  9017. * @typedef {Object} getTextContentParameters
  9018. * @property {boolean} normalizeWhitespace - replaces all occurrences of
  9019. * whitespace with standard spaces (0x20). The default value is `false`.
  9020. * @property {boolean} disableCombineTextItems - do not attempt to combine
  9021. * same line {@link TextItem}'s. The default value is `false`.
  9022. */
  9023. /**
  9024. * Page text content.
  9025. *
  9026. * @typedef {Object} TextContent
  9027. * @property {array} items - array of {@link TextItem}
  9028. * @property {Object} styles - {@link TextStyles} objects, indexed by font name.
  9029. */
  9030. /**
  9031. * Page text content part.
  9032. *
  9033. * @typedef {Object} TextItem
  9034. * @property {string} str - text content.
  9035. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  9036. * @property {array} transform - transformation matrix.
  9037. * @property {number} width - width in device space.
  9038. * @property {number} height - height in device space.
  9039. * @property {string} fontName - font name used by pdf.js for converted font.
  9040. */
  9041. /**
  9042. * Text style.
  9043. *
  9044. * @typedef {Object} TextStyle
  9045. * @property {number} ascent - font ascent.
  9046. * @property {number} descent - font descent.
  9047. * @property {boolean} vertical - text is in vertical mode.
  9048. * @property {string} fontFamily - possible font family
  9049. */
  9050. /**
  9051. * Page annotation parameters.
  9052. *
  9053. * @typedef {Object} GetAnnotationsParameters
  9054. * @property {string} intent - Determines the annotations that will be fetched,
  9055. * can be either 'display' (viewable annotations) or 'print'
  9056. * (printable annotations).
  9057. * If the parameter is omitted, all annotations are fetched.
  9058. */
  9059. /**
  9060. * Page render parameters.
  9061. *
  9062. * @typedef {Object} RenderParameters
  9063. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  9064. * @property {PageViewport} viewport - Rendering viewport obtained by
  9065. * calling of PDFPage.getViewport method.
  9066. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  9067. * (default value is 'display').
  9068. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  9069. * interactive form elements are rendered in the display
  9070. * layer. If so, we do not render them on canvas as well.
  9071. * @property {Array} transform - (optional) Additional transform, applied
  9072. * just before viewport transform.
  9073. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  9074. * endLayout and appendImage functions.
  9075. * @property {function} continueCallback - (deprecated) A function that will be
  9076. * called each time the rendering is paused. To continue
  9077. * rendering call the function that is the first argument
  9078. * to the callback.
  9079. */
  9080. /**
  9081. * PDF page operator list.
  9082. *
  9083. * @typedef {Object} PDFOperatorList
  9084. * @property {Array} fnArray - Array containing the operator functions.
  9085. * @property {Array} argsArray - Array containing the arguments of the
  9086. * functions.
  9087. */
  9088. /**
  9089. * Proxy to a PDFPage in the worker thread.
  9090. * @class
  9091. * @alias PDFPageProxy
  9092. */
  9093. var PDFPageProxy = function PDFPageProxyClosure() {
  9094. function PDFPageProxy(pageIndex, pageInfo, transport) {
  9095. this.pageIndex = pageIndex;
  9096. this.pageInfo = pageInfo;
  9097. this.transport = transport;
  9098. this.stats = new StatTimer();
  9099. this.stats.enabled = getDefaultSetting('enableStats');
  9100. this.commonObjs = transport.commonObjs;
  9101. this.objs = new PDFObjects();
  9102. this.cleanupAfterRender = false;
  9103. this.pendingCleanup = false;
  9104. this.intentStates = Object.create(null);
  9105. this.destroyed = false;
  9106. }
  9107. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */
  9108. {
  9109. /**
  9110. * @return {number} Page number of the page. First page is 1.
  9111. */
  9112. get pageNumber() {
  9113. return this.pageIndex + 1;
  9114. },
  9115. /**
  9116. * @return {number} The number of degrees the page is rotated clockwise.
  9117. */
  9118. get rotate() {
  9119. return this.pageInfo.rotate;
  9120. },
  9121. /**
  9122. * @return {Object} The reference that points to this page. It has 'num' and
  9123. * 'gen' properties.
  9124. */
  9125. get ref() {
  9126. return this.pageInfo.ref;
  9127. },
  9128. /**
  9129. * @return {Array} An array of the visible portion of the PDF page in the
  9130. * user space units - [x1, y1, x2, y2].
  9131. */
  9132. get view() {
  9133. return this.pageInfo.view;
  9134. },
  9135. /**
  9136. * @param {number} scale The desired scale of the viewport.
  9137. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  9138. * defaults to the page rotation.
  9139. * @return {PageViewport} Contains 'width' and 'height' properties
  9140. * along with transforms required for rendering.
  9141. */
  9142. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  9143. if (arguments.length < 2) {
  9144. rotate = this.rotate;
  9145. }
  9146. return new PageViewport(this.view, scale, rotate, 0, 0);
  9147. },
  9148. /**
  9149. * @param {GetAnnotationsParameters} params - Annotation parameters.
  9150. * @return {Promise} A promise that is resolved with an {Array} of the
  9151. * annotation objects.
  9152. */
  9153. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  9154. var intent = params && params.intent || null;
  9155. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  9156. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  9157. this.annotationsIntent = intent;
  9158. }
  9159. return this.annotationsPromise;
  9160. },
  9161. /**
  9162. * Begins the process of rendering a page to the desired context.
  9163. * @param {RenderParameters} params Page render parameters.
  9164. * @return {RenderTask} An object that contains the promise, which
  9165. * is resolved when the page finishes rendering.
  9166. */
  9167. render: function PDFPageProxy_render(params) {
  9168. var stats = this.stats;
  9169. stats.time('Overall');
  9170. // If there was a pending destroy cancel it so no cleanup happens during
  9171. // this call to render.
  9172. this.pendingCleanup = false;
  9173. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  9174. var renderInteractiveForms = params.renderInteractiveForms === true ? true : /* Default */
  9175. false;
  9176. if (!this.intentStates[renderingIntent]) {
  9177. this.intentStates[renderingIntent] = Object.create(null);
  9178. }
  9179. var intentState = this.intentStates[renderingIntent];
  9180. // If there's no displayReadyCapability yet, then the operatorList
  9181. // was never requested before. Make the request and create the promise.
  9182. if (!intentState.displayReadyCapability) {
  9183. intentState.receivingOperatorList = true;
  9184. intentState.displayReadyCapability = createPromiseCapability();
  9185. intentState.operatorList = {
  9186. fnArray: [],
  9187. argsArray: [],
  9188. lastChunk: false
  9189. };
  9190. this.stats.time('Page Request');
  9191. this.transport.messageHandler.send('RenderPageRequest', {
  9192. pageIndex: this.pageNumber - 1,
  9193. intent: renderingIntent,
  9194. renderInteractiveForms: renderInteractiveForms
  9195. });
  9196. }
  9197. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  9198. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  9199. if (!intentState.renderTasks) {
  9200. intentState.renderTasks = [];
  9201. }
  9202. intentState.renderTasks.push(internalRenderTask);
  9203. var renderTask = internalRenderTask.task;
  9204. // Obsolete parameter support
  9205. if (params.continueCallback) {
  9206. deprecated('render is used with continueCallback parameter');
  9207. renderTask.onContinue = params.continueCallback;
  9208. }
  9209. var self = this;
  9210. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  9211. if (self.pendingCleanup) {
  9212. complete();
  9213. return;
  9214. }
  9215. stats.time('Rendering');
  9216. internalRenderTask.initializeGraphics(transparency);
  9217. internalRenderTask.operatorListChanged();
  9218. }, function pageDisplayReadPromiseError(reason) {
  9219. complete(reason);
  9220. });
  9221. function complete(error) {
  9222. var i = intentState.renderTasks.indexOf(internalRenderTask);
  9223. if (i >= 0) {
  9224. intentState.renderTasks.splice(i, 1);
  9225. }
  9226. if (self.cleanupAfterRender) {
  9227. self.pendingCleanup = true;
  9228. }
  9229. self._tryCleanup();
  9230. if (error) {
  9231. internalRenderTask.capability.reject(error);
  9232. } else {
  9233. internalRenderTask.capability.resolve();
  9234. }
  9235. stats.timeEnd('Rendering');
  9236. stats.timeEnd('Overall');
  9237. }
  9238. return renderTask;
  9239. },
  9240. /**
  9241. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  9242. * object that represents page's operator list.
  9243. */
  9244. getOperatorList: function PDFPageProxy_getOperatorList() {
  9245. function operatorListChanged() {
  9246. if (intentState.operatorList.lastChunk) {
  9247. intentState.opListReadCapability.resolve(intentState.operatorList);
  9248. var i = intentState.renderTasks.indexOf(opListTask);
  9249. if (i >= 0) {
  9250. intentState.renderTasks.splice(i, 1);
  9251. }
  9252. }
  9253. }
  9254. var renderingIntent = 'oplist';
  9255. if (!this.intentStates[renderingIntent]) {
  9256. this.intentStates[renderingIntent] = Object.create(null);
  9257. }
  9258. var intentState = this.intentStates[renderingIntent];
  9259. var opListTask;
  9260. if (!intentState.opListReadCapability) {
  9261. opListTask = {};
  9262. opListTask.operatorListChanged = operatorListChanged;
  9263. intentState.receivingOperatorList = true;
  9264. intentState.opListReadCapability = createPromiseCapability();
  9265. intentState.renderTasks = [];
  9266. intentState.renderTasks.push(opListTask);
  9267. intentState.operatorList = {
  9268. fnArray: [],
  9269. argsArray: [],
  9270. lastChunk: false
  9271. };
  9272. this.transport.messageHandler.send('RenderPageRequest', {
  9273. pageIndex: this.pageIndex,
  9274. intent: renderingIntent
  9275. });
  9276. }
  9277. return intentState.opListReadCapability.promise;
  9278. },
  9279. /**
  9280. * @param {getTextContentParameters} params - getTextContent parameters.
  9281. * @return {Promise} That is resolved a {@link TextContent}
  9282. * object that represent the page text content.
  9283. */
  9284. getTextContent: function PDFPageProxy_getTextContent(params) {
  9285. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  9286. pageIndex: this.pageNumber - 1,
  9287. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : /* Default */
  9288. false,
  9289. combineTextItems: params && params.disableCombineTextItems === true ? false : /* Default */
  9290. true
  9291. });
  9292. },
  9293. /**
  9294. * Destroys page object.
  9295. */
  9296. _destroy: function PDFPageProxy_destroy() {
  9297. this.destroyed = true;
  9298. this.transport.pageCache[this.pageIndex] = null;
  9299. var waitOn = [];
  9300. Object.keys(this.intentStates).forEach(function (intent) {
  9301. if (intent === 'oplist') {
  9302. // Avoid errors below, since the renderTasks are just stubs.
  9303. return;
  9304. }
  9305. var intentState = this.intentStates[intent];
  9306. intentState.renderTasks.forEach(function (renderTask) {
  9307. var renderCompleted = renderTask.capability.promise.catch(function () {
  9308. });
  9309. // ignoring failures
  9310. waitOn.push(renderCompleted);
  9311. renderTask.cancel();
  9312. });
  9313. }, this);
  9314. this.objs.clear();
  9315. this.annotationsPromise = null;
  9316. this.pendingCleanup = false;
  9317. return Promise.all(waitOn);
  9318. },
  9319. /**
  9320. * Cleans up resources allocated by the page. (deprecated)
  9321. */
  9322. destroy: function () {
  9323. deprecated('page destroy method, use cleanup() instead');
  9324. this.cleanup();
  9325. },
  9326. /**
  9327. * Cleans up resources allocated by the page.
  9328. */
  9329. cleanup: function PDFPageProxy_cleanup() {
  9330. this.pendingCleanup = true;
  9331. this._tryCleanup();
  9332. },
  9333. /**
  9334. * For internal use only. Attempts to clean up if rendering is in a state
  9335. * where that's possible.
  9336. * @ignore
  9337. */
  9338. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9339. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  9340. var intentState = this.intentStates[intent];
  9341. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  9342. }, this)) {
  9343. return;
  9344. }
  9345. Object.keys(this.intentStates).forEach(function (intent) {
  9346. delete this.intentStates[intent];
  9347. }, this);
  9348. this.objs.clear();
  9349. this.annotationsPromise = null;
  9350. this.pendingCleanup = false;
  9351. },
  9352. /**
  9353. * For internal use only.
  9354. * @ignore
  9355. */
  9356. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  9357. var intentState = this.intentStates[intent];
  9358. // TODO Refactor RenderPageRequest to separate rendering
  9359. // and operator list logic
  9360. if (intentState.displayReadyCapability) {
  9361. intentState.displayReadyCapability.resolve(transparency);
  9362. }
  9363. },
  9364. /**
  9365. * For internal use only.
  9366. * @ignore
  9367. */
  9368. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  9369. var intentState = this.intentStates[intent];
  9370. var i, ii;
  9371. // Add the new chunk to the current operator list.
  9372. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9373. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9374. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  9375. }
  9376. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9377. // Notify all the rendering tasks there are more operators to be consumed.
  9378. for (i = 0; i < intentState.renderTasks.length; i++) {
  9379. intentState.renderTasks[i].operatorListChanged();
  9380. }
  9381. if (operatorListChunk.lastChunk) {
  9382. intentState.receivingOperatorList = false;
  9383. this._tryCleanup();
  9384. }
  9385. }
  9386. };
  9387. return PDFPageProxy;
  9388. }();
  9389. /**
  9390. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9391. * WorkerTransport for them. If creation of a web worker is not possible,
  9392. * a "fake" worker will be used instead.
  9393. * @class
  9394. */
  9395. var PDFWorker = function PDFWorkerClosure() {
  9396. var nextFakeWorkerId = 0;
  9397. function getWorkerSrc() {
  9398. if (typeof workerSrc !== 'undefined') {
  9399. return workerSrc;
  9400. }
  9401. if (getDefaultSetting('workerSrc')) {
  9402. return getDefaultSetting('workerSrc');
  9403. }
  9404. if (pdfjsFilePath) {
  9405. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9406. }
  9407. error('No PDFJS.workerSrc specified');
  9408. }
  9409. var fakeWorkerFilesLoadedCapability;
  9410. // Loads worker code into main thread.
  9411. function setupFakeWorkerGlobal() {
  9412. var WorkerMessageHandler;
  9413. if (fakeWorkerFilesLoadedCapability) {
  9414. return fakeWorkerFilesLoadedCapability.promise;
  9415. }
  9416. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9417. var loader = fakeWorkerFilesLoader || function (callback) {
  9418. Util.loadScript(getWorkerSrc(), function () {
  9419. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9420. });
  9421. };
  9422. loader(fakeWorkerFilesLoadedCapability.resolve);
  9423. return fakeWorkerFilesLoadedCapability.promise;
  9424. }
  9425. function FakeWorkerPort(defer) {
  9426. this._listeners = [];
  9427. this._defer = defer;
  9428. this._deferred = Promise.resolve(undefined);
  9429. }
  9430. FakeWorkerPort.prototype = {
  9431. postMessage: function (obj, transfers) {
  9432. function cloneValue(value) {
  9433. // Trying to perform a structured clone close to the spec, including
  9434. // transfers.
  9435. if (typeof value !== 'object' || value === null) {
  9436. return value;
  9437. }
  9438. if (cloned.has(value)) {
  9439. // already cloned the object
  9440. return cloned.get(value);
  9441. }
  9442. var result;
  9443. var buffer;
  9444. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9445. // We found object with ArrayBuffer (typed array).
  9446. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9447. if (value === buffer) {
  9448. // Special case when we are faking typed arrays in compatibility.js.
  9449. result = value;
  9450. } else if (transferable) {
  9451. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  9452. } else {
  9453. result = new value.constructor(value);
  9454. }
  9455. cloned.set(value, result);
  9456. return result;
  9457. }
  9458. result = isArray(value) ? [] : {};
  9459. cloned.set(value, result);
  9460. // adding to cache now for cyclic references
  9461. // Cloning all value and object properties, however ignoring properties
  9462. // defined via getter.
  9463. for (var i in value) {
  9464. var desc, p = value;
  9465. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9466. p = Object.getPrototypeOf(p);
  9467. }
  9468. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  9469. continue;
  9470. }
  9471. result[i] = cloneValue(desc.value);
  9472. }
  9473. return result;
  9474. }
  9475. if (!this._defer) {
  9476. this._listeners.forEach(function (listener) {
  9477. listener.call(this, { data: obj });
  9478. }, this);
  9479. return;
  9480. }
  9481. var cloned = new WeakMap();
  9482. var e = { data: cloneValue(obj) };
  9483. this._deferred.then(function () {
  9484. this._listeners.forEach(function (listener) {
  9485. listener.call(this, e);
  9486. }, this);
  9487. }.bind(this));
  9488. },
  9489. addEventListener: function (name, listener) {
  9490. this._listeners.push(listener);
  9491. },
  9492. removeEventListener: function (name, listener) {
  9493. var i = this._listeners.indexOf(listener);
  9494. this._listeners.splice(i, 1);
  9495. },
  9496. terminate: function () {
  9497. this._listeners = [];
  9498. }
  9499. };
  9500. function createCDNWrapper(url) {
  9501. // We will rely on blob URL's property to specify origin.
  9502. // We want this function to fail in case if createObjectURL or Blob do not
  9503. // exist or fail for some reason -- our Worker creation will fail anyway.
  9504. var wrapper = 'importScripts(\'' + url + '\');';
  9505. return URL.createObjectURL(new Blob([wrapper]));
  9506. }
  9507. function PDFWorker(name) {
  9508. this.name = name;
  9509. this.destroyed = false;
  9510. this._readyCapability = createPromiseCapability();
  9511. this._port = null;
  9512. this._webWorker = null;
  9513. this._messageHandler = null;
  9514. this._initialize();
  9515. }
  9516. PDFWorker.prototype = /** @lends PDFWorker.prototype */
  9517. {
  9518. get promise() {
  9519. return this._readyCapability.promise;
  9520. },
  9521. get port() {
  9522. return this._port;
  9523. },
  9524. get messageHandler() {
  9525. return this._messageHandler;
  9526. },
  9527. _initialize: function PDFWorker_initialize() {
  9528. // If worker support isn't disabled explicit and the browser has worker
  9529. // support, create a new web worker and test if it/the browser fulfills
  9530. // all requirements to run parts of pdf.js in a web worker.
  9531. // Right now, the requirement is, that an Uint8Array is still an
  9532. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9533. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  9534. var workerSrc = getWorkerSrc();
  9535. try {
  9536. // Wraps workerSrc path into blob URL, if the former does not belong
  9537. // to the same origin.
  9538. if (!isSameOrigin(window.location.href, workerSrc)) {
  9539. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  9540. }
  9541. // Some versions of FF can't create a worker on localhost, see:
  9542. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9543. var worker = new Worker(workerSrc);
  9544. var messageHandler = new MessageHandler('main', 'worker', worker);
  9545. var terminateEarly = function () {
  9546. worker.removeEventListener('error', onWorkerError);
  9547. messageHandler.destroy();
  9548. worker.terminate();
  9549. if (this.destroyed) {
  9550. this._readyCapability.reject(new Error('Worker was destroyed'));
  9551. } else {
  9552. // Fall back to fake worker if the termination is caused by an
  9553. // error (e.g. NetworkError / SecurityError).
  9554. this._setupFakeWorker();
  9555. }
  9556. }.bind(this);
  9557. var onWorkerError = function (event) {
  9558. if (!this._webWorker) {
  9559. // Worker failed to initialize due to an error. Clean up and fall
  9560. // back to the fake worker.
  9561. terminateEarly();
  9562. }
  9563. }.bind(this);
  9564. worker.addEventListener('error', onWorkerError);
  9565. messageHandler.on('test', function PDFWorker_test(data) {
  9566. worker.removeEventListener('error', onWorkerError);
  9567. if (this.destroyed) {
  9568. terminateEarly();
  9569. return;
  9570. }
  9571. // worker was destroyed
  9572. var supportTypedArray = data && data.supportTypedArray;
  9573. if (supportTypedArray) {
  9574. this._messageHandler = messageHandler;
  9575. this._port = worker;
  9576. this._webWorker = worker;
  9577. if (!data.supportTransfers) {
  9578. isPostMessageTransfersDisabled = true;
  9579. }
  9580. this._readyCapability.resolve();
  9581. // Send global setting, e.g. verbosity level.
  9582. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  9583. } else {
  9584. this._setupFakeWorker();
  9585. messageHandler.destroy();
  9586. worker.terminate();
  9587. }
  9588. }.bind(this));
  9589. messageHandler.on('console_log', function (data) {
  9590. console.log.apply(console, data);
  9591. });
  9592. messageHandler.on('console_error', function (data) {
  9593. console.error.apply(console, data);
  9594. });
  9595. messageHandler.on('ready', function (data) {
  9596. worker.removeEventListener('error', onWorkerError);
  9597. if (this.destroyed) {
  9598. terminateEarly();
  9599. return;
  9600. }
  9601. // worker was destroyed
  9602. try {
  9603. sendTest();
  9604. } catch (e) {
  9605. // We need fallback to a faked worker.
  9606. this._setupFakeWorker();
  9607. }
  9608. }.bind(this));
  9609. var sendTest = function () {
  9610. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  9611. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9612. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9613. // typed array. Also, checking if we can use transfers.
  9614. try {
  9615. messageHandler.send('test', testObj, [testObj.buffer]);
  9616. } catch (ex) {
  9617. info('Cannot use postMessage transfers');
  9618. testObj[0] = 0;
  9619. messageHandler.send('test', testObj);
  9620. }
  9621. };
  9622. // It might take time for worker to initialize (especially when AMD
  9623. // loader is used). We will try to send test immediately, and then
  9624. // when 'ready' message will arrive. The worker shall process only
  9625. // first received 'test'.
  9626. sendTest();
  9627. return;
  9628. } catch (e) {
  9629. info('The worker has been disabled.');
  9630. }
  9631. }
  9632. // Either workers are disabled, not supported or have thrown an exception.
  9633. // Thus, we fallback to a faked worker.
  9634. this._setupFakeWorker();
  9635. },
  9636. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9637. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9638. warn('Setting up fake worker.');
  9639. isWorkerDisabled = true;
  9640. }
  9641. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9642. if (this.destroyed) {
  9643. this._readyCapability.reject(new Error('Worker was destroyed'));
  9644. return;
  9645. }
  9646. // We cannot turn on proper fake port simulation (this includes
  9647. // structured cloning) when typed arrays are not supported. Relying
  9648. // on a chance that messages will be sent in proper order.
  9649. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9650. var port = new FakeWorkerPort(isTypedArraysPresent);
  9651. this._port = port;
  9652. // All fake workers use the same port, making id unique.
  9653. var id = 'fake' + nextFakeWorkerId++;
  9654. // If the main thread is our worker, setup the handling for the
  9655. // messages -- the main thread sends to it self.
  9656. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9657. WorkerMessageHandler.setup(workerHandler, port);
  9658. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9659. this._messageHandler = messageHandler;
  9660. this._readyCapability.resolve();
  9661. }.bind(this));
  9662. },
  9663. /**
  9664. * Destroys the worker instance.
  9665. */
  9666. destroy: function PDFWorker_destroy() {
  9667. this.destroyed = true;
  9668. if (this._webWorker) {
  9669. // We need to terminate only web worker created resource.
  9670. this._webWorker.terminate();
  9671. this._webWorker = null;
  9672. }
  9673. this._port = null;
  9674. if (this._messageHandler) {
  9675. this._messageHandler.destroy();
  9676. this._messageHandler = null;
  9677. }
  9678. }
  9679. };
  9680. return PDFWorker;
  9681. }();
  9682. /**
  9683. * For internal use only.
  9684. * @ignore
  9685. */
  9686. var WorkerTransport = function WorkerTransportClosure() {
  9687. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9688. this.messageHandler = messageHandler;
  9689. this.loadingTask = loadingTask;
  9690. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9691. this.commonObjs = new PDFObjects();
  9692. this.fontLoader = new FontLoader(loadingTask.docId);
  9693. this.destroyed = false;
  9694. this.destroyCapability = null;
  9695. this.pageCache = [];
  9696. this.pagePromises = [];
  9697. this.downloadInfoCapability = createPromiseCapability();
  9698. this.setupMessageHandler();
  9699. }
  9700. WorkerTransport.prototype = {
  9701. destroy: function WorkerTransport_destroy() {
  9702. if (this.destroyCapability) {
  9703. return this.destroyCapability.promise;
  9704. }
  9705. this.destroyed = true;
  9706. this.destroyCapability = createPromiseCapability();
  9707. var waitOn = [];
  9708. // We need to wait for all renderings to be completed, e.g.
  9709. // timeout/rAF can take a long time.
  9710. this.pageCache.forEach(function (page) {
  9711. if (page) {
  9712. waitOn.push(page._destroy());
  9713. }
  9714. });
  9715. this.pageCache = [];
  9716. this.pagePromises = [];
  9717. var self = this;
  9718. // We also need to wait for the worker to finish its long running tasks.
  9719. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9720. waitOn.push(terminated);
  9721. Promise.all(waitOn).then(function () {
  9722. self.fontLoader.clear();
  9723. if (self.pdfDataRangeTransport) {
  9724. self.pdfDataRangeTransport.abort();
  9725. self.pdfDataRangeTransport = null;
  9726. }
  9727. if (self.messageHandler) {
  9728. self.messageHandler.destroy();
  9729. self.messageHandler = null;
  9730. }
  9731. self.destroyCapability.resolve();
  9732. }, this.destroyCapability.reject);
  9733. return this.destroyCapability.promise;
  9734. },
  9735. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  9736. var messageHandler = this.messageHandler;
  9737. function updatePassword(password) {
  9738. messageHandler.send('UpdatePassword', password);
  9739. }
  9740. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9741. if (pdfDataRangeTransport) {
  9742. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  9743. messageHandler.send('OnDataRange', {
  9744. begin: begin,
  9745. chunk: chunk
  9746. });
  9747. });
  9748. pdfDataRangeTransport.addProgressListener(function (loaded) {
  9749. messageHandler.send('OnDataProgress', { loaded: loaded });
  9750. });
  9751. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  9752. messageHandler.send('OnDataRange', { chunk: chunk });
  9753. });
  9754. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  9755. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9756. }, this);
  9757. }
  9758. messageHandler.on('GetDoc', function transportDoc(data) {
  9759. var pdfInfo = data.pdfInfo;
  9760. this.numPages = data.pdfInfo.numPages;
  9761. var loadingTask = this.loadingTask;
  9762. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9763. this.pdfDocument = pdfDocument;
  9764. loadingTask._capability.resolve(pdfDocument);
  9765. }, this);
  9766. messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
  9767. var loadingTask = this.loadingTask;
  9768. if (loadingTask.onPassword) {
  9769. return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
  9770. }
  9771. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9772. }, this);
  9773. messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
  9774. var loadingTask = this.loadingTask;
  9775. if (loadingTask.onPassword) {
  9776. return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
  9777. }
  9778. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9779. }, this);
  9780. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9781. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  9782. }, this);
  9783. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9784. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  9785. }, this);
  9786. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  9787. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  9788. }, this);
  9789. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  9790. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  9791. }, this);
  9792. messageHandler.on('DataLoaded', function transportPage(data) {
  9793. this.downloadInfoCapability.resolve(data);
  9794. }, this);
  9795. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9796. if (this.pdfDataRangeTransport) {
  9797. this.pdfDataRangeTransport.transportReady();
  9798. }
  9799. }, this);
  9800. messageHandler.on('StartRenderPage', function transportRender(data) {
  9801. if (this.destroyed) {
  9802. return;
  9803. }
  9804. // Ignore any pending requests if the worker was terminated.
  9805. var page = this.pageCache[data.pageIndex];
  9806. page.stats.timeEnd('Page Request');
  9807. page._startRenderPage(data.transparency, data.intent);
  9808. }, this);
  9809. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9810. if (this.destroyed) {
  9811. return;
  9812. }
  9813. // Ignore any pending requests if the worker was terminated.
  9814. var page = this.pageCache[data.pageIndex];
  9815. page._renderPageChunk(data.operatorList, data.intent);
  9816. }, this);
  9817. messageHandler.on('commonobj', function transportObj(data) {
  9818. if (this.destroyed) {
  9819. return;
  9820. }
  9821. // Ignore any pending requests if the worker was terminated.
  9822. var id = data[0];
  9823. var type = data[1];
  9824. if (this.commonObjs.hasData(id)) {
  9825. return;
  9826. }
  9827. switch (type) {
  9828. case 'Font':
  9829. var exportedData = data[2];
  9830. if ('error' in exportedData) {
  9831. var exportedError = exportedData.error;
  9832. warn('Error during font loading: ' + exportedError);
  9833. this.commonObjs.resolve(id, exportedError);
  9834. break;
  9835. }
  9836. var fontRegistry = null;
  9837. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  9838. fontRegistry = {
  9839. registerFont: function (font, url) {
  9840. globalScope['FontInspector'].fontAdded(font, url);
  9841. }
  9842. };
  9843. }
  9844. var font = new FontFaceObject(exportedData, {
  9845. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9846. disableFontFace: getDefaultSetting('disableFontFace'),
  9847. fontRegistry: fontRegistry
  9848. });
  9849. this.fontLoader.bind([font], function fontReady(fontObjs) {
  9850. this.commonObjs.resolve(id, font);
  9851. }.bind(this));
  9852. break;
  9853. case 'FontPath':
  9854. this.commonObjs.resolve(id, data[2]);
  9855. break;
  9856. default:
  9857. error('Got unknown common object type ' + type);
  9858. }
  9859. }, this);
  9860. messageHandler.on('obj', function transportObj(data) {
  9861. if (this.destroyed) {
  9862. return;
  9863. }
  9864. // Ignore any pending requests if the worker was terminated.
  9865. var id = data[0];
  9866. var pageIndex = data[1];
  9867. var type = data[2];
  9868. var pageProxy = this.pageCache[pageIndex];
  9869. var imageData;
  9870. if (pageProxy.objs.hasData(id)) {
  9871. return;
  9872. }
  9873. switch (type) {
  9874. case 'JpegStream':
  9875. imageData = data[3];
  9876. loadJpegStream(id, imageData, pageProxy.objs);
  9877. break;
  9878. case 'Image':
  9879. imageData = data[3];
  9880. pageProxy.objs.resolve(id, imageData);
  9881. // heuristics that will allow not to store large data
  9882. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9883. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9884. pageProxy.cleanupAfterRender = true;
  9885. }
  9886. break;
  9887. default:
  9888. error('Got unknown object type ' + type);
  9889. }
  9890. }, this);
  9891. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9892. if (this.destroyed) {
  9893. return;
  9894. }
  9895. // Ignore any pending requests if the worker was terminated.
  9896. var loadingTask = this.loadingTask;
  9897. if (loadingTask.onProgress) {
  9898. loadingTask.onProgress({
  9899. loaded: data.loaded,
  9900. total: data.total
  9901. });
  9902. }
  9903. }, this);
  9904. messageHandler.on('PageError', function transportError(data) {
  9905. if (this.destroyed) {
  9906. return;
  9907. }
  9908. // Ignore any pending requests if the worker was terminated.
  9909. var page = this.pageCache[data.pageNum - 1];
  9910. var intentState = page.intentStates[data.intent];
  9911. if (intentState.displayReadyCapability) {
  9912. intentState.displayReadyCapability.reject(data.error);
  9913. } else {
  9914. error(data.error);
  9915. }
  9916. if (intentState.operatorList) {
  9917. // Mark operator list as complete.
  9918. intentState.operatorList.lastChunk = true;
  9919. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9920. intentState.renderTasks[i].operatorListChanged();
  9921. }
  9922. }
  9923. }, this);
  9924. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  9925. if (this.destroyed) {
  9926. return;
  9927. }
  9928. // Ignore any pending requests if the worker was terminated.
  9929. var featureId = data.featureId;
  9930. var loadingTask = this.loadingTask;
  9931. if (loadingTask.onUnsupportedFeature) {
  9932. loadingTask.onUnsupportedFeature(featureId);
  9933. }
  9934. _UnsupportedManager.notify(featureId);
  9935. }, this);
  9936. messageHandler.on('JpegDecode', function (data) {
  9937. if (this.destroyed) {
  9938. return Promise.reject(new Error('Worker was destroyed'));
  9939. }
  9940. var imageUrl = data[0];
  9941. var components = data[1];
  9942. if (components !== 3 && components !== 1) {
  9943. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  9944. }
  9945. return new Promise(function (resolve, reject) {
  9946. var img = new Image();
  9947. img.onload = function () {
  9948. var width = img.width;
  9949. var height = img.height;
  9950. var size = width * height;
  9951. var rgbaLength = size * 4;
  9952. var buf = new Uint8Array(size * components);
  9953. var tmpCanvas = createScratchCanvas(width, height);
  9954. var tmpCtx = tmpCanvas.getContext('2d');
  9955. tmpCtx.drawImage(img, 0, 0);
  9956. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9957. var i, j;
  9958. if (components === 3) {
  9959. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9960. buf[j] = data[i];
  9961. buf[j + 1] = data[i + 1];
  9962. buf[j + 2] = data[i + 2];
  9963. }
  9964. } else if (components === 1) {
  9965. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9966. buf[j] = data[i];
  9967. }
  9968. }
  9969. resolve({
  9970. data: buf,
  9971. width: width,
  9972. height: height
  9973. });
  9974. };
  9975. img.onerror = function () {
  9976. reject(new Error('JpegDecode failed to load image'));
  9977. };
  9978. img.src = imageUrl;
  9979. });
  9980. }, this);
  9981. },
  9982. getData: function WorkerTransport_getData() {
  9983. return this.messageHandler.sendWithPromise('GetData', null);
  9984. },
  9985. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9986. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9987. return Promise.reject(new Error('Invalid page request'));
  9988. }
  9989. var pageIndex = pageNumber - 1;
  9990. if (pageIndex in this.pagePromises) {
  9991. return this.pagePromises[pageIndex];
  9992. }
  9993. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  9994. if (this.destroyed) {
  9995. throw new Error('Transport destroyed');
  9996. }
  9997. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9998. this.pageCache[pageIndex] = page;
  9999. return page;
  10000. }.bind(this));
  10001. this.pagePromises[pageIndex] = promise;
  10002. return promise;
  10003. },
  10004. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  10005. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  10006. return Promise.reject(new Error(reason));
  10007. });
  10008. },
  10009. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  10010. return this.messageHandler.sendWithPromise('GetAnnotations', {
  10011. pageIndex: pageIndex,
  10012. intent: intent
  10013. });
  10014. },
  10015. getDestinations: function WorkerTransport_getDestinations() {
  10016. return this.messageHandler.sendWithPromise('GetDestinations', null);
  10017. },
  10018. getDestination: function WorkerTransport_getDestination(id) {
  10019. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  10020. },
  10021. getPageLabels: function WorkerTransport_getPageLabels() {
  10022. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  10023. },
  10024. getAttachments: function WorkerTransport_getAttachments() {
  10025. return this.messageHandler.sendWithPromise('GetAttachments', null);
  10026. },
  10027. getJavaScript: function WorkerTransport_getJavaScript() {
  10028. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  10029. },
  10030. getOutline: function WorkerTransport_getOutline() {
  10031. return this.messageHandler.sendWithPromise('GetOutline', null);
  10032. },
  10033. getMetadata: function WorkerTransport_getMetadata() {
  10034. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  10035. return {
  10036. info: results[0],
  10037. metadata: results[1] ? new Metadata(results[1]) : null
  10038. };
  10039. });
  10040. },
  10041. getStats: function WorkerTransport_getStats() {
  10042. return this.messageHandler.sendWithPromise('GetStats', null);
  10043. },
  10044. startCleanup: function WorkerTransport_startCleanup() {
  10045. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  10046. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  10047. var page = this.pageCache[i];
  10048. if (page) {
  10049. page.cleanup();
  10050. }
  10051. }
  10052. this.commonObjs.clear();
  10053. this.fontLoader.clear();
  10054. }.bind(this));
  10055. }
  10056. };
  10057. return WorkerTransport;
  10058. }();
  10059. /**
  10060. * A PDF document and page is built of many objects. E.g. there are objects
  10061. * for fonts, images, rendering code and such. These objects might get processed
  10062. * inside of a worker. The `PDFObjects` implements some basic functions to
  10063. * manage these objects.
  10064. * @ignore
  10065. */
  10066. var PDFObjects = function PDFObjectsClosure() {
  10067. function PDFObjects() {
  10068. this.objs = Object.create(null);
  10069. }
  10070. PDFObjects.prototype = {
  10071. /**
  10072. * Internal function.
  10073. * Ensures there is an object defined for `objId`.
  10074. */
  10075. ensureObj: function PDFObjects_ensureObj(objId) {
  10076. if (this.objs[objId]) {
  10077. return this.objs[objId];
  10078. }
  10079. var obj = {
  10080. capability: createPromiseCapability(),
  10081. data: null,
  10082. resolved: false
  10083. };
  10084. this.objs[objId] = obj;
  10085. return obj;
  10086. },
  10087. /**
  10088. * If called *without* callback, this returns the data of `objId` but the
  10089. * object needs to be resolved. If it isn't, this function throws.
  10090. *
  10091. * If called *with* a callback, the callback is called with the data of the
  10092. * object once the object is resolved. That means, if you call this
  10093. * function and the object is already resolved, the callback gets called
  10094. * right away.
  10095. */
  10096. get: function PDFObjects_get(objId, callback) {
  10097. // If there is a callback, then the get can be async and the object is
  10098. // not required to be resolved right now
  10099. if (callback) {
  10100. this.ensureObj(objId).capability.promise.then(callback);
  10101. return null;
  10102. }
  10103. // If there isn't a callback, the user expects to get the resolved data
  10104. // directly.
  10105. var obj = this.objs[objId];
  10106. // If there isn't an object yet or the object isn't resolved, then the
  10107. // data isn't ready yet!
  10108. if (!obj || !obj.resolved) {
  10109. error('Requesting object that isn\'t resolved yet ' + objId);
  10110. }
  10111. return obj.data;
  10112. },
  10113. /**
  10114. * Resolves the object `objId` with optional `data`.
  10115. */
  10116. resolve: function PDFObjects_resolve(objId, data) {
  10117. var obj = this.ensureObj(objId);
  10118. obj.resolved = true;
  10119. obj.data = data;
  10120. obj.capability.resolve(data);
  10121. },
  10122. isResolved: function PDFObjects_isResolved(objId) {
  10123. var objs = this.objs;
  10124. if (!objs[objId]) {
  10125. return false;
  10126. } else {
  10127. return objs[objId].resolved;
  10128. }
  10129. },
  10130. hasData: function PDFObjects_hasData(objId) {
  10131. return this.isResolved(objId);
  10132. },
  10133. /**
  10134. * Returns the data of `objId` if object exists, null otherwise.
  10135. */
  10136. getData: function PDFObjects_getData(objId) {
  10137. var objs = this.objs;
  10138. if (!objs[objId] || !objs[objId].resolved) {
  10139. return null;
  10140. } else {
  10141. return objs[objId].data;
  10142. }
  10143. },
  10144. clear: function PDFObjects_clear() {
  10145. this.objs = Object.create(null);
  10146. }
  10147. };
  10148. return PDFObjects;
  10149. }();
  10150. /**
  10151. * Allows controlling of the rendering tasks.
  10152. * @class
  10153. * @alias RenderTask
  10154. */
  10155. var RenderTask = function RenderTaskClosure() {
  10156. function RenderTask(internalRenderTask) {
  10157. this._internalRenderTask = internalRenderTask;
  10158. /**
  10159. * Callback for incremental rendering -- a function that will be called
  10160. * each time the rendering is paused. To continue rendering call the
  10161. * function that is the first argument to the callback.
  10162. * @type {function}
  10163. */
  10164. this.onContinue = null;
  10165. }
  10166. RenderTask.prototype = /** @lends RenderTask.prototype */
  10167. {
  10168. /**
  10169. * Promise for rendering task completion.
  10170. * @return {Promise}
  10171. */
  10172. get promise() {
  10173. return this._internalRenderTask.capability.promise;
  10174. },
  10175. /**
  10176. * Cancels the rendering task. If the task is currently rendering it will
  10177. * not be cancelled until graphics pauses with a timeout. The promise that
  10178. * this object extends will resolved when cancelled.
  10179. */
  10180. cancel: function RenderTask_cancel() {
  10181. this._internalRenderTask.cancel();
  10182. },
  10183. /**
  10184. * Registers callbacks to indicate the rendering task completion.
  10185. *
  10186. * @param {function} onFulfilled The callback for the rendering completion.
  10187. * @param {function} onRejected The callback for the rendering failure.
  10188. * @return {Promise} A promise that is resolved after the onFulfilled or
  10189. * onRejected callback.
  10190. */
  10191. then: function RenderTask_then(onFulfilled, onRejected) {
  10192. return this.promise.then.apply(this.promise, arguments);
  10193. }
  10194. };
  10195. return RenderTask;
  10196. }();
  10197. /**
  10198. * For internal use only.
  10199. * @ignore
  10200. */
  10201. var InternalRenderTask = function InternalRenderTaskClosure() {
  10202. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  10203. this.callback = callback;
  10204. this.params = params;
  10205. this.objs = objs;
  10206. this.commonObjs = commonObjs;
  10207. this.operatorListIdx = null;
  10208. this.operatorList = operatorList;
  10209. this.pageNumber = pageNumber;
  10210. this.running = false;
  10211. this.graphicsReadyCallback = null;
  10212. this.graphicsReady = false;
  10213. this.useRequestAnimationFrame = false;
  10214. this.cancelled = false;
  10215. this.capability = createPromiseCapability();
  10216. this.task = new RenderTask(this);
  10217. // caching this-bound methods
  10218. this._continueBound = this._continue.bind(this);
  10219. this._scheduleNextBound = this._scheduleNext.bind(this);
  10220. this._nextBound = this._next.bind(this);
  10221. }
  10222. InternalRenderTask.prototype = {
  10223. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  10224. if (this.cancelled) {
  10225. return;
  10226. }
  10227. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  10228. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  10229. this.stepper.init(this.operatorList);
  10230. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  10231. }
  10232. var params = this.params;
  10233. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  10234. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  10235. this.operatorListIdx = 0;
  10236. this.graphicsReady = true;
  10237. if (this.graphicsReadyCallback) {
  10238. this.graphicsReadyCallback();
  10239. }
  10240. },
  10241. cancel: function InternalRenderTask_cancel() {
  10242. this.running = false;
  10243. this.cancelled = true;
  10244. this.callback('cancelled');
  10245. },
  10246. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  10247. if (!this.graphicsReady) {
  10248. if (!this.graphicsReadyCallback) {
  10249. this.graphicsReadyCallback = this._continueBound;
  10250. }
  10251. return;
  10252. }
  10253. if (this.stepper) {
  10254. this.stepper.updateOperatorList(this.operatorList);
  10255. }
  10256. if (this.running) {
  10257. return;
  10258. }
  10259. this._continue();
  10260. },
  10261. _continue: function InternalRenderTask__continue() {
  10262. this.running = true;
  10263. if (this.cancelled) {
  10264. return;
  10265. }
  10266. if (this.task.onContinue) {
  10267. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10268. } else {
  10269. this._scheduleNext();
  10270. }
  10271. },
  10272. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10273. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10274. window.requestAnimationFrame(this._nextBound);
  10275. } else {
  10276. Promise.resolve(undefined).then(this._nextBound);
  10277. }
  10278. },
  10279. _next: function InternalRenderTask__next() {
  10280. if (this.cancelled) {
  10281. return;
  10282. }
  10283. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  10284. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10285. this.running = false;
  10286. if (this.operatorList.lastChunk) {
  10287. this.gfx.endDrawing();
  10288. this.callback();
  10289. }
  10290. }
  10291. }
  10292. };
  10293. return InternalRenderTask;
  10294. }();
  10295. /**
  10296. * (Deprecated) Global observer of unsupported feature usages. Use
  10297. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10298. */
  10299. var _UnsupportedManager = function UnsupportedManagerClosure() {
  10300. var listeners = [];
  10301. return {
  10302. listen: function (cb) {
  10303. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10304. listeners.push(cb);
  10305. },
  10306. notify: function (featureId) {
  10307. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10308. listeners[i](featureId);
  10309. }
  10310. }
  10311. };
  10312. }();
  10313. if (typeof pdfjsVersion !== 'undefined') {
  10314. exports.version = pdfjsVersion;
  10315. }
  10316. if (typeof pdfjsBuild !== 'undefined') {
  10317. exports.build = pdfjsBuild;
  10318. }
  10319. exports.getDocument = getDocument;
  10320. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10321. exports.PDFWorker = PDFWorker;
  10322. exports.PDFDocumentProxy = PDFDocumentProxy;
  10323. exports.PDFPageProxy = PDFPageProxy;
  10324. exports._UnsupportedManager = _UnsupportedManager;
  10325. }));
  10326. (function (root, factory) {
  10327. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10328. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  10329. var globalScope = sharedUtil.globalScope;
  10330. var deprecated = sharedUtil.deprecated;
  10331. var warn = sharedUtil.warn;
  10332. var LinkTarget = displayDOMUtils.LinkTarget;
  10333. var isWorker = typeof window === 'undefined';
  10334. // The global PDFJS object is now deprecated and will not be supported in
  10335. // the future. The members below are maintained for backward compatibility
  10336. // and shall not be extended or modified. If the global.js is included as
  10337. // a module, we will create a global PDFJS object instance or use existing.
  10338. if (!globalScope.PDFJS) {
  10339. globalScope.PDFJS = {};
  10340. }
  10341. var PDFJS = globalScope.PDFJS;
  10342. if (typeof pdfjsVersion !== 'undefined') {
  10343. PDFJS.version = pdfjsVersion;
  10344. }
  10345. if (typeof pdfjsBuild !== 'undefined') {
  10346. PDFJS.build = pdfjsBuild;
  10347. }
  10348. PDFJS.pdfBug = false;
  10349. if (PDFJS.verbosity !== undefined) {
  10350. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10351. }
  10352. delete PDFJS.verbosity;
  10353. Object.defineProperty(PDFJS, 'verbosity', {
  10354. get: function () {
  10355. return sharedUtil.getVerbosityLevel();
  10356. },
  10357. set: function (level) {
  10358. sharedUtil.setVerbosityLevel(level);
  10359. },
  10360. enumerable: true,
  10361. configurable: true
  10362. });
  10363. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10364. PDFJS.OPS = sharedUtil.OPS;
  10365. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10366. PDFJS.isValidUrl = displayDOMUtils.isValidUrl;
  10367. PDFJS.shadow = sharedUtil.shadow;
  10368. PDFJS.createBlob = sharedUtil.createBlob;
  10369. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10370. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  10371. };
  10372. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10373. configurable: true,
  10374. get: function PDFJS_isLittleEndian() {
  10375. var value = sharedUtil.isLittleEndian();
  10376. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10377. }
  10378. });
  10379. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10380. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10381. PDFJS.PasswordException = sharedUtil.PasswordException;
  10382. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10383. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10384. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10385. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10386. PDFJS.Util = sharedUtil.Util;
  10387. PDFJS.PageViewport = sharedUtil.PageViewport;
  10388. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10389. /**
  10390. * The maximum allowed image size in total pixels e.g. width * height. Images
  10391. * above this value will not be drawn. Use -1 for no limit.
  10392. * @var {number}
  10393. */
  10394. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  10395. /**
  10396. * The url of where the predefined Adobe CMaps are located. Include trailing
  10397. * slash.
  10398. * @var {string}
  10399. */
  10400. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  10401. /**
  10402. * Specifies if CMaps are binary packed.
  10403. * @var {boolean}
  10404. */
  10405. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10406. /**
  10407. * By default fonts are converted to OpenType fonts and loaded via font face
  10408. * rules. If disabled, the font will be rendered using a built in font
  10409. * renderer that constructs the glyphs with primitive path commands.
  10410. * @var {boolean}
  10411. */
  10412. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  10413. /**
  10414. * Path for image resources, mainly for annotation icons. Include trailing
  10415. * slash.
  10416. * @var {string}
  10417. */
  10418. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  10419. /**
  10420. * Disable the web worker and run all code on the main thread. This will
  10421. * happen automatically if the browser doesn't support workers or sending
  10422. * typed arrays to workers.
  10423. * @var {boolean}
  10424. */
  10425. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  10426. /**
  10427. * Path and filename of the worker file. Required when the worker is enabled
  10428. * in development mode. If unspecified in the production build, the worker
  10429. * will be loaded based on the location of the pdf.js file. It is recommended
  10430. * that the workerSrc is set in a custom application to prevent issues caused
  10431. * by third-party frameworks and libraries.
  10432. * @var {string}
  10433. */
  10434. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  10435. /**
  10436. * Disable range request loading of PDF files. When enabled and if the server
  10437. * supports partial content requests then the PDF will be fetched in chunks.
  10438. * Enabled (false) by default.
  10439. * @var {boolean}
  10440. */
  10441. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  10442. /**
  10443. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10444. * in chunks. This default behavior can be disabled.
  10445. * @var {boolean}
  10446. */
  10447. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  10448. /**
  10449. * Disable pre-fetching of PDF file data. When range requests are enabled
  10450. * PDF.js will automatically keep fetching more data even if it isn't needed
  10451. * to display the current page. This default behavior can be disabled.
  10452. *
  10453. * NOTE: It is also necessary to disable streaming, see above,
  10454. * in order for disabling of pre-fetching to work correctly.
  10455. * @var {boolean}
  10456. */
  10457. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  10458. /**
  10459. * Enables special hooks for debugging PDF.js.
  10460. * @var {boolean}
  10461. */
  10462. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  10463. /**
  10464. * Enables transfer usage in postMessage for ArrayBuffers.
  10465. * @var {boolean}
  10466. */
  10467. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  10468. /**
  10469. * Disables URL.createObjectURL usage.
  10470. * @var {boolean}
  10471. */
  10472. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  10473. /**
  10474. * Disables WebGL usage.
  10475. * @var {boolean}
  10476. */
  10477. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  10478. /**
  10479. * Specifies the |target| attribute for external links.
  10480. * The constants from PDFJS.LinkTarget should be used:
  10481. * - NONE [default]
  10482. * - SELF
  10483. * - BLANK
  10484. * - PARENT
  10485. * - TOP
  10486. * @var {number}
  10487. */
  10488. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  10489. /**
  10490. * Specifies the |rel| attribute for external links. Defaults to stripping
  10491. * the referrer.
  10492. * @var {string}
  10493. */
  10494. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel;
  10495. /**
  10496. * Determines if we can eval strings as JS. Primarily used to improve
  10497. * performance for font rendering.
  10498. * @var {boolean}
  10499. */
  10500. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  10501. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10502. delete PDFJS.openExternalLinksInNewWindow;
  10503. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10504. get: function () {
  10505. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10506. },
  10507. set: function (value) {
  10508. if (value) {
  10509. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10510. }
  10511. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10512. warn('PDFJS.externalLinkTarget is already initialized');
  10513. return;
  10514. }
  10515. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. if (savedOpenExternalLinksInNewWindow) {
  10521. /**
  10522. * (Deprecated) Opens external links in a new window if enabled.
  10523. * The default behavior opens external links in the PDF.js window.
  10524. *
  10525. * NOTE: This property has been deprecated, please use
  10526. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10527. * @var {boolean}
  10528. */
  10529. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10530. }
  10531. PDFJS.getDocument = displayAPI.getDocument;
  10532. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10533. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10534. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10535. configurable: true,
  10536. get: function PDFJS_hasCanvasTypedArrays() {
  10537. var value = displayDOMUtils.hasCanvasTypedArrays();
  10538. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10539. }
  10540. });
  10541. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10542. PDFJS.LinkTarget = LinkTarget;
  10543. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10544. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10545. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10546. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10547. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10548. PDFJS.Metadata = displayMetadata.Metadata;
  10549. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10550. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10551. exports.globalScope = globalScope;
  10552. exports.isWorker = isWorker;
  10553. exports.PDFJS = globalScope.PDFJS;
  10554. }));
  10555. }.call(pdfjsLibs));
  10556. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10557. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10558. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10559. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10560. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10561. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10562. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10563. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10564. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10565. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10566. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10567. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10568. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10569. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10570. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10571. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10572. exports.isValidUrl = pdfjsLibs.pdfjsDisplayDOMUtils.isValidUrl;
  10573. exports.createValidAbsoluteUrl = pdfjsLibs.pdfjsSharedUtil.createValidAbsoluteUrl;
  10574. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10575. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10576. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10577. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10578. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10579. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10580. }));