pdf.js 547 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2023 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. (function webpackUniversalModuleDefinition(root, factory) {
  23. if(typeof exports === 'object' && typeof module === 'object')
  24. module.exports = root.pdfjsLib = factory();
  25. else if(typeof define === 'function' && define.amd)
  26. define("pdfjs-dist/build/pdf", [], () => { return (root.pdfjsLib = factory()); });
  27. else if(typeof exports === 'object')
  28. exports["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
  29. else
  30. root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
  31. })(globalThis, () => {
  32. return /******/ (() => { // webpackBootstrap
  33. /******/ "use strict";
  34. /******/ var __webpack_modules__ = ([
  35. /* 0 */,
  36. /* 1 */
  37. /***/ ((__unused_webpack_module, exports) => {
  38. Object.defineProperty(exports, "__esModule", ({
  39. value: true
  40. }));
  41. exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PromiseCapability = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.MAX_IMAGE_SIZE_TO_CACHE = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  42. exports.assert = assert;
  43. exports.bytesToString = bytesToString;
  44. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  45. exports.getModificationDate = getModificationDate;
  46. exports.getUuid = getUuid;
  47. exports.getVerbosityLevel = getVerbosityLevel;
  48. exports.info = info;
  49. exports.isArrayBuffer = isArrayBuffer;
  50. exports.isArrayEqual = isArrayEqual;
  51. exports.isNodeJS = void 0;
  52. exports.normalizeUnicode = normalizeUnicode;
  53. exports.objectFromMap = objectFromMap;
  54. exports.objectSize = objectSize;
  55. exports.setVerbosityLevel = setVerbosityLevel;
  56. exports.shadow = shadow;
  57. exports.string32 = string32;
  58. exports.stringToBytes = stringToBytes;
  59. exports.stringToPDFString = stringToPDFString;
  60. exports.stringToUTF8String = stringToUTF8String;
  61. exports.unreachable = unreachable;
  62. exports.utf8StringToString = utf8StringToString;
  63. exports.warn = warn;
  64. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  65. exports.isNodeJS = isNodeJS;
  66. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  67. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  68. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  69. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  70. const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
  71. exports.MAX_IMAGE_SIZE_TO_CACHE = MAX_IMAGE_SIZE_TO_CACHE;
  72. const LINE_FACTOR = 1.35;
  73. exports.LINE_FACTOR = LINE_FACTOR;
  74. const LINE_DESCENT_FACTOR = 0.35;
  75. exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
  76. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  77. exports.BASELINE_FACTOR = BASELINE_FACTOR;
  78. const RenderingIntentFlag = {
  79. ANY: 0x01,
  80. DISPLAY: 0x02,
  81. PRINT: 0x04,
  82. SAVE: 0x08,
  83. ANNOTATIONS_FORMS: 0x10,
  84. ANNOTATIONS_STORAGE: 0x20,
  85. ANNOTATIONS_DISABLE: 0x40,
  86. OPLIST: 0x100
  87. };
  88. exports.RenderingIntentFlag = RenderingIntentFlag;
  89. const AnnotationMode = {
  90. DISABLE: 0,
  91. ENABLE: 1,
  92. ENABLE_FORMS: 2,
  93. ENABLE_STORAGE: 3
  94. };
  95. exports.AnnotationMode = AnnotationMode;
  96. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  97. exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
  98. const AnnotationEditorType = {
  99. DISABLE: -1,
  100. NONE: 0,
  101. FREETEXT: 3,
  102. STAMP: 13,
  103. INK: 15
  104. };
  105. exports.AnnotationEditorType = AnnotationEditorType;
  106. const AnnotationEditorParamsType = {
  107. RESIZE: 1,
  108. CREATE: 2,
  109. FREETEXT_SIZE: 11,
  110. FREETEXT_COLOR: 12,
  111. FREETEXT_OPACITY: 13,
  112. INK_COLOR: 21,
  113. INK_THICKNESS: 22,
  114. INK_OPACITY: 23
  115. };
  116. exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
  117. const PermissionFlag = {
  118. PRINT: 0x04,
  119. MODIFY_CONTENTS: 0x08,
  120. COPY: 0x10,
  121. MODIFY_ANNOTATIONS: 0x20,
  122. FILL_INTERACTIVE_FORMS: 0x100,
  123. COPY_FOR_ACCESSIBILITY: 0x200,
  124. ASSEMBLE: 0x400,
  125. PRINT_HIGH_QUALITY: 0x800
  126. };
  127. exports.PermissionFlag = PermissionFlag;
  128. const TextRenderingMode = {
  129. FILL: 0,
  130. STROKE: 1,
  131. FILL_STROKE: 2,
  132. INVISIBLE: 3,
  133. FILL_ADD_TO_PATH: 4,
  134. STROKE_ADD_TO_PATH: 5,
  135. FILL_STROKE_ADD_TO_PATH: 6,
  136. ADD_TO_PATH: 7,
  137. FILL_STROKE_MASK: 3,
  138. ADD_TO_PATH_FLAG: 4
  139. };
  140. exports.TextRenderingMode = TextRenderingMode;
  141. const ImageKind = {
  142. GRAYSCALE_1BPP: 1,
  143. RGB_24BPP: 2,
  144. RGBA_32BPP: 3
  145. };
  146. exports.ImageKind = ImageKind;
  147. const AnnotationType = {
  148. TEXT: 1,
  149. LINK: 2,
  150. FREETEXT: 3,
  151. LINE: 4,
  152. SQUARE: 5,
  153. CIRCLE: 6,
  154. POLYGON: 7,
  155. POLYLINE: 8,
  156. HIGHLIGHT: 9,
  157. UNDERLINE: 10,
  158. SQUIGGLY: 11,
  159. STRIKEOUT: 12,
  160. STAMP: 13,
  161. CARET: 14,
  162. INK: 15,
  163. POPUP: 16,
  164. FILEATTACHMENT: 17,
  165. SOUND: 18,
  166. MOVIE: 19,
  167. WIDGET: 20,
  168. SCREEN: 21,
  169. PRINTERMARK: 22,
  170. TRAPNET: 23,
  171. WATERMARK: 24,
  172. THREED: 25,
  173. REDACT: 26
  174. };
  175. exports.AnnotationType = AnnotationType;
  176. const AnnotationReplyType = {
  177. GROUP: "Group",
  178. REPLY: "R"
  179. };
  180. exports.AnnotationReplyType = AnnotationReplyType;
  181. const AnnotationFlag = {
  182. INVISIBLE: 0x01,
  183. HIDDEN: 0x02,
  184. PRINT: 0x04,
  185. NOZOOM: 0x08,
  186. NOROTATE: 0x10,
  187. NOVIEW: 0x20,
  188. READONLY: 0x40,
  189. LOCKED: 0x80,
  190. TOGGLENOVIEW: 0x100,
  191. LOCKEDCONTENTS: 0x200
  192. };
  193. exports.AnnotationFlag = AnnotationFlag;
  194. const AnnotationFieldFlag = {
  195. READONLY: 0x0000001,
  196. REQUIRED: 0x0000002,
  197. NOEXPORT: 0x0000004,
  198. MULTILINE: 0x0001000,
  199. PASSWORD: 0x0002000,
  200. NOTOGGLETOOFF: 0x0004000,
  201. RADIO: 0x0008000,
  202. PUSHBUTTON: 0x0010000,
  203. COMBO: 0x0020000,
  204. EDIT: 0x0040000,
  205. SORT: 0x0080000,
  206. FILESELECT: 0x0100000,
  207. MULTISELECT: 0x0200000,
  208. DONOTSPELLCHECK: 0x0400000,
  209. DONOTSCROLL: 0x0800000,
  210. COMB: 0x1000000,
  211. RICHTEXT: 0x2000000,
  212. RADIOSINUNISON: 0x2000000,
  213. COMMITONSELCHANGE: 0x4000000
  214. };
  215. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  216. const AnnotationBorderStyleType = {
  217. SOLID: 1,
  218. DASHED: 2,
  219. BEVELED: 3,
  220. INSET: 4,
  221. UNDERLINE: 5
  222. };
  223. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  224. const AnnotationActionEventType = {
  225. E: "Mouse Enter",
  226. X: "Mouse Exit",
  227. D: "Mouse Down",
  228. U: "Mouse Up",
  229. Fo: "Focus",
  230. Bl: "Blur",
  231. PO: "PageOpen",
  232. PC: "PageClose",
  233. PV: "PageVisible",
  234. PI: "PageInvisible",
  235. K: "Keystroke",
  236. F: "Format",
  237. V: "Validate",
  238. C: "Calculate"
  239. };
  240. exports.AnnotationActionEventType = AnnotationActionEventType;
  241. const DocumentActionEventType = {
  242. WC: "WillClose",
  243. WS: "WillSave",
  244. DS: "DidSave",
  245. WP: "WillPrint",
  246. DP: "DidPrint"
  247. };
  248. exports.DocumentActionEventType = DocumentActionEventType;
  249. const PageActionEventType = {
  250. O: "PageOpen",
  251. C: "PageClose"
  252. };
  253. exports.PageActionEventType = PageActionEventType;
  254. const VerbosityLevel = {
  255. ERRORS: 0,
  256. WARNINGS: 1,
  257. INFOS: 5
  258. };
  259. exports.VerbosityLevel = VerbosityLevel;
  260. const CMapCompressionType = {
  261. NONE: 0,
  262. BINARY: 1
  263. };
  264. exports.CMapCompressionType = CMapCompressionType;
  265. const OPS = {
  266. dependency: 1,
  267. setLineWidth: 2,
  268. setLineCap: 3,
  269. setLineJoin: 4,
  270. setMiterLimit: 5,
  271. setDash: 6,
  272. setRenderingIntent: 7,
  273. setFlatness: 8,
  274. setGState: 9,
  275. save: 10,
  276. restore: 11,
  277. transform: 12,
  278. moveTo: 13,
  279. lineTo: 14,
  280. curveTo: 15,
  281. curveTo2: 16,
  282. curveTo3: 17,
  283. closePath: 18,
  284. rectangle: 19,
  285. stroke: 20,
  286. closeStroke: 21,
  287. fill: 22,
  288. eoFill: 23,
  289. fillStroke: 24,
  290. eoFillStroke: 25,
  291. closeFillStroke: 26,
  292. closeEOFillStroke: 27,
  293. endPath: 28,
  294. clip: 29,
  295. eoClip: 30,
  296. beginText: 31,
  297. endText: 32,
  298. setCharSpacing: 33,
  299. setWordSpacing: 34,
  300. setHScale: 35,
  301. setLeading: 36,
  302. setFont: 37,
  303. setTextRenderingMode: 38,
  304. setTextRise: 39,
  305. moveText: 40,
  306. setLeadingMoveText: 41,
  307. setTextMatrix: 42,
  308. nextLine: 43,
  309. showText: 44,
  310. showSpacedText: 45,
  311. nextLineShowText: 46,
  312. nextLineSetSpacingShowText: 47,
  313. setCharWidth: 48,
  314. setCharWidthAndBounds: 49,
  315. setStrokeColorSpace: 50,
  316. setFillColorSpace: 51,
  317. setStrokeColor: 52,
  318. setStrokeColorN: 53,
  319. setFillColor: 54,
  320. setFillColorN: 55,
  321. setStrokeGray: 56,
  322. setFillGray: 57,
  323. setStrokeRGBColor: 58,
  324. setFillRGBColor: 59,
  325. setStrokeCMYKColor: 60,
  326. setFillCMYKColor: 61,
  327. shadingFill: 62,
  328. beginInlineImage: 63,
  329. beginImageData: 64,
  330. endInlineImage: 65,
  331. paintXObject: 66,
  332. markPoint: 67,
  333. markPointProps: 68,
  334. beginMarkedContent: 69,
  335. beginMarkedContentProps: 70,
  336. endMarkedContent: 71,
  337. beginCompat: 72,
  338. endCompat: 73,
  339. paintFormXObjectBegin: 74,
  340. paintFormXObjectEnd: 75,
  341. beginGroup: 76,
  342. endGroup: 77,
  343. beginAnnotation: 80,
  344. endAnnotation: 81,
  345. paintImageMaskXObject: 83,
  346. paintImageMaskXObjectGroup: 84,
  347. paintImageXObject: 85,
  348. paintInlineImageXObject: 86,
  349. paintInlineImageXObjectGroup: 87,
  350. paintImageXObjectRepeat: 88,
  351. paintImageMaskXObjectRepeat: 89,
  352. paintSolidColorImageMask: 90,
  353. constructPath: 91
  354. };
  355. exports.OPS = OPS;
  356. const PasswordResponses = {
  357. NEED_PASSWORD: 1,
  358. INCORRECT_PASSWORD: 2
  359. };
  360. exports.PasswordResponses = PasswordResponses;
  361. let verbosity = VerbosityLevel.WARNINGS;
  362. function setVerbosityLevel(level) {
  363. if (Number.isInteger(level)) {
  364. verbosity = level;
  365. }
  366. }
  367. function getVerbosityLevel() {
  368. return verbosity;
  369. }
  370. function info(msg) {
  371. if (verbosity >= VerbosityLevel.INFOS) {
  372. console.log(`Info: ${msg}`);
  373. }
  374. }
  375. function warn(msg) {
  376. if (verbosity >= VerbosityLevel.WARNINGS) {
  377. console.log(`Warning: ${msg}`);
  378. }
  379. }
  380. function unreachable(msg) {
  381. throw new Error(msg);
  382. }
  383. function assert(cond, msg) {
  384. if (!cond) {
  385. unreachable(msg);
  386. }
  387. }
  388. function _isValidProtocol(url) {
  389. switch (url?.protocol) {
  390. case "http:":
  391. case "https:":
  392. case "ftp:":
  393. case "mailto:":
  394. case "tel:":
  395. return true;
  396. default:
  397. return false;
  398. }
  399. }
  400. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  401. if (!url) {
  402. return null;
  403. }
  404. try {
  405. if (options && typeof url === "string") {
  406. if (options.addDefaultProtocol && url.startsWith("www.")) {
  407. const dots = url.match(/\./g);
  408. if (dots?.length >= 2) {
  409. url = `http://${url}`;
  410. }
  411. }
  412. if (options.tryConvertEncoding) {
  413. try {
  414. url = stringToUTF8String(url);
  415. } catch {}
  416. }
  417. }
  418. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  419. if (_isValidProtocol(absoluteUrl)) {
  420. return absoluteUrl;
  421. }
  422. } catch {}
  423. return null;
  424. }
  425. function shadow(obj, prop, value, nonSerializable = false) {
  426. Object.defineProperty(obj, prop, {
  427. value,
  428. enumerable: !nonSerializable,
  429. configurable: true,
  430. writable: false
  431. });
  432. return value;
  433. }
  434. const BaseException = function BaseExceptionClosure() {
  435. function BaseException(message, name) {
  436. if (this.constructor === BaseException) {
  437. unreachable("Cannot initialize BaseException.");
  438. }
  439. this.message = message;
  440. this.name = name;
  441. }
  442. BaseException.prototype = new Error();
  443. BaseException.constructor = BaseException;
  444. return BaseException;
  445. }();
  446. exports.BaseException = BaseException;
  447. class PasswordException extends BaseException {
  448. constructor(msg, code) {
  449. super(msg, "PasswordException");
  450. this.code = code;
  451. }
  452. }
  453. exports.PasswordException = PasswordException;
  454. class UnknownErrorException extends BaseException {
  455. constructor(msg, details) {
  456. super(msg, "UnknownErrorException");
  457. this.details = details;
  458. }
  459. }
  460. exports.UnknownErrorException = UnknownErrorException;
  461. class InvalidPDFException extends BaseException {
  462. constructor(msg) {
  463. super(msg, "InvalidPDFException");
  464. }
  465. }
  466. exports.InvalidPDFException = InvalidPDFException;
  467. class MissingPDFException extends BaseException {
  468. constructor(msg) {
  469. super(msg, "MissingPDFException");
  470. }
  471. }
  472. exports.MissingPDFException = MissingPDFException;
  473. class UnexpectedResponseException extends BaseException {
  474. constructor(msg, status) {
  475. super(msg, "UnexpectedResponseException");
  476. this.status = status;
  477. }
  478. }
  479. exports.UnexpectedResponseException = UnexpectedResponseException;
  480. class FormatError extends BaseException {
  481. constructor(msg) {
  482. super(msg, "FormatError");
  483. }
  484. }
  485. exports.FormatError = FormatError;
  486. class AbortException extends BaseException {
  487. constructor(msg) {
  488. super(msg, "AbortException");
  489. }
  490. }
  491. exports.AbortException = AbortException;
  492. function bytesToString(bytes) {
  493. if (typeof bytes !== "object" || bytes?.length === undefined) {
  494. unreachable("Invalid argument for bytesToString");
  495. }
  496. const length = bytes.length;
  497. const MAX_ARGUMENT_COUNT = 8192;
  498. if (length < MAX_ARGUMENT_COUNT) {
  499. return String.fromCharCode.apply(null, bytes);
  500. }
  501. const strBuf = [];
  502. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  503. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  504. const chunk = bytes.subarray(i, chunkEnd);
  505. strBuf.push(String.fromCharCode.apply(null, chunk));
  506. }
  507. return strBuf.join("");
  508. }
  509. function stringToBytes(str) {
  510. if (typeof str !== "string") {
  511. unreachable("Invalid argument for stringToBytes");
  512. }
  513. const length = str.length;
  514. const bytes = new Uint8Array(length);
  515. for (let i = 0; i < length; ++i) {
  516. bytes[i] = str.charCodeAt(i) & 0xff;
  517. }
  518. return bytes;
  519. }
  520. function string32(value) {
  521. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  522. }
  523. function objectSize(obj) {
  524. return Object.keys(obj).length;
  525. }
  526. function objectFromMap(map) {
  527. const obj = Object.create(null);
  528. for (const [key, value] of map) {
  529. obj[key] = value;
  530. }
  531. return obj;
  532. }
  533. function isLittleEndian() {
  534. const buffer8 = new Uint8Array(4);
  535. buffer8[0] = 1;
  536. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  537. return view32[0] === 1;
  538. }
  539. function isEvalSupported() {
  540. try {
  541. new Function("");
  542. return true;
  543. } catch {
  544. return false;
  545. }
  546. }
  547. class FeatureTest {
  548. static get isLittleEndian() {
  549. return shadow(this, "isLittleEndian", isLittleEndian());
  550. }
  551. static get isEvalSupported() {
  552. return shadow(this, "isEvalSupported", isEvalSupported());
  553. }
  554. static get isOffscreenCanvasSupported() {
  555. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  556. }
  557. static get platform() {
  558. if (typeof navigator === "undefined") {
  559. return shadow(this, "platform", {
  560. isWin: false,
  561. isMac: false
  562. });
  563. }
  564. return shadow(this, "platform", {
  565. isWin: navigator.platform.includes("Win"),
  566. isMac: navigator.platform.includes("Mac")
  567. });
  568. }
  569. static get isCSSRoundSupported() {
  570. return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  571. }
  572. }
  573. exports.FeatureTest = FeatureTest;
  574. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  575. class Util {
  576. static makeHexColor(r, g, b) {
  577. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  578. }
  579. static scaleMinMax(transform, minMax) {
  580. let temp;
  581. if (transform[0]) {
  582. if (transform[0] < 0) {
  583. temp = minMax[0];
  584. minMax[0] = minMax[1];
  585. minMax[1] = temp;
  586. }
  587. minMax[0] *= transform[0];
  588. minMax[1] *= transform[0];
  589. if (transform[3] < 0) {
  590. temp = minMax[2];
  591. minMax[2] = minMax[3];
  592. minMax[3] = temp;
  593. }
  594. minMax[2] *= transform[3];
  595. minMax[3] *= transform[3];
  596. } else {
  597. temp = minMax[0];
  598. minMax[0] = minMax[2];
  599. minMax[2] = temp;
  600. temp = minMax[1];
  601. minMax[1] = minMax[3];
  602. minMax[3] = temp;
  603. if (transform[1] < 0) {
  604. temp = minMax[2];
  605. minMax[2] = minMax[3];
  606. minMax[3] = temp;
  607. }
  608. minMax[2] *= transform[1];
  609. minMax[3] *= transform[1];
  610. if (transform[2] < 0) {
  611. temp = minMax[0];
  612. minMax[0] = minMax[1];
  613. minMax[1] = temp;
  614. }
  615. minMax[0] *= transform[2];
  616. minMax[1] *= transform[2];
  617. }
  618. minMax[0] += transform[4];
  619. minMax[1] += transform[4];
  620. minMax[2] += transform[5];
  621. minMax[3] += transform[5];
  622. }
  623. static transform(m1, m2) {
  624. return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  625. }
  626. static applyTransform(p, m) {
  627. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  628. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  629. return [xt, yt];
  630. }
  631. static applyInverseTransform(p, m) {
  632. const d = m[0] * m[3] - m[1] * m[2];
  633. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  634. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  635. return [xt, yt];
  636. }
  637. static getAxialAlignedBoundingBox(r, m) {
  638. const p1 = this.applyTransform(r, m);
  639. const p2 = this.applyTransform(r.slice(2, 4), m);
  640. const p3 = this.applyTransform([r[0], r[3]], m);
  641. const p4 = this.applyTransform([r[2], r[1]], m);
  642. return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  643. }
  644. static inverseTransform(m) {
  645. const d = m[0] * m[3] - m[1] * m[2];
  646. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  647. }
  648. static singularValueDecompose2dScale(m) {
  649. const transpose = [m[0], m[2], m[1], m[3]];
  650. const a = m[0] * transpose[0] + m[1] * transpose[2];
  651. const b = m[0] * transpose[1] + m[1] * transpose[3];
  652. const c = m[2] * transpose[0] + m[3] * transpose[2];
  653. const d = m[2] * transpose[1] + m[3] * transpose[3];
  654. const first = (a + d) / 2;
  655. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  656. const sx = first + second || 1;
  657. const sy = first - second || 1;
  658. return [Math.sqrt(sx), Math.sqrt(sy)];
  659. }
  660. static normalizeRect(rect) {
  661. const r = rect.slice(0);
  662. if (rect[0] > rect[2]) {
  663. r[0] = rect[2];
  664. r[2] = rect[0];
  665. }
  666. if (rect[1] > rect[3]) {
  667. r[1] = rect[3];
  668. r[3] = rect[1];
  669. }
  670. return r;
  671. }
  672. static intersect(rect1, rect2) {
  673. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  674. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  675. if (xLow > xHigh) {
  676. return null;
  677. }
  678. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  679. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  680. if (yLow > yHigh) {
  681. return null;
  682. }
  683. return [xLow, yLow, xHigh, yHigh];
  684. }
  685. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  686. const tvalues = [],
  687. bounds = [[], []];
  688. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  689. for (let i = 0; i < 2; ++i) {
  690. if (i === 0) {
  691. b = 6 * x0 - 12 * x1 + 6 * x2;
  692. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  693. c = 3 * x1 - 3 * x0;
  694. } else {
  695. b = 6 * y0 - 12 * y1 + 6 * y2;
  696. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  697. c = 3 * y1 - 3 * y0;
  698. }
  699. if (Math.abs(a) < 1e-12) {
  700. if (Math.abs(b) < 1e-12) {
  701. continue;
  702. }
  703. t = -c / b;
  704. if (0 < t && t < 1) {
  705. tvalues.push(t);
  706. }
  707. continue;
  708. }
  709. b2ac = b * b - 4 * c * a;
  710. sqrtb2ac = Math.sqrt(b2ac);
  711. if (b2ac < 0) {
  712. continue;
  713. }
  714. t1 = (-b + sqrtb2ac) / (2 * a);
  715. if (0 < t1 && t1 < 1) {
  716. tvalues.push(t1);
  717. }
  718. t2 = (-b - sqrtb2ac) / (2 * a);
  719. if (0 < t2 && t2 < 1) {
  720. tvalues.push(t2);
  721. }
  722. }
  723. let j = tvalues.length,
  724. mt;
  725. const jlen = j;
  726. while (j--) {
  727. t = tvalues[j];
  728. mt = 1 - t;
  729. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  730. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  731. }
  732. bounds[0][jlen] = x0;
  733. bounds[1][jlen] = y0;
  734. bounds[0][jlen + 1] = x3;
  735. bounds[1][jlen + 1] = y3;
  736. bounds[0].length = bounds[1].length = jlen + 2;
  737. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  738. }
  739. }
  740. exports.Util = Util;
  741. const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
  742. function stringToPDFString(str) {
  743. if (str[0] >= "\xEF") {
  744. let encoding;
  745. if (str[0] === "\xFE" && str[1] === "\xFF") {
  746. encoding = "utf-16be";
  747. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  748. encoding = "utf-16le";
  749. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  750. encoding = "utf-8";
  751. }
  752. if (encoding) {
  753. try {
  754. const decoder = new TextDecoder(encoding, {
  755. fatal: true
  756. });
  757. const buffer = stringToBytes(str);
  758. return decoder.decode(buffer);
  759. } catch (ex) {
  760. warn(`stringToPDFString: "${ex}".`);
  761. }
  762. }
  763. }
  764. const strBuf = [];
  765. for (let i = 0, ii = str.length; i < ii; i++) {
  766. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  767. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  768. }
  769. return strBuf.join("");
  770. }
  771. function stringToUTF8String(str) {
  772. return decodeURIComponent(escape(str));
  773. }
  774. function utf8StringToString(str) {
  775. return unescape(encodeURIComponent(str));
  776. }
  777. function isArrayBuffer(v) {
  778. return typeof v === "object" && v?.byteLength !== undefined;
  779. }
  780. function isArrayEqual(arr1, arr2) {
  781. if (arr1.length !== arr2.length) {
  782. return false;
  783. }
  784. for (let i = 0, ii = arr1.length; i < ii; i++) {
  785. if (arr1[i] !== arr2[i]) {
  786. return false;
  787. }
  788. }
  789. return true;
  790. }
  791. function getModificationDate(date = new Date()) {
  792. const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
  793. return buffer.join("");
  794. }
  795. class PromiseCapability {
  796. #settled = false;
  797. constructor() {
  798. this.promise = new Promise((resolve, reject) => {
  799. this.resolve = data => {
  800. this.#settled = true;
  801. resolve(data);
  802. };
  803. this.reject = reason => {
  804. this.#settled = true;
  805. reject(reason);
  806. };
  807. });
  808. }
  809. get settled() {
  810. return this.#settled;
  811. }
  812. }
  813. exports.PromiseCapability = PromiseCapability;
  814. let NormalizeRegex = null;
  815. let NormalizationMap = null;
  816. function normalizeUnicode(str) {
  817. if (!NormalizeRegex) {
  818. NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
  819. NormalizationMap = new Map([["ſt", "ſt"]]);
  820. }
  821. return str.replaceAll(NormalizeRegex, (_, p1, p2) => {
  822. return p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2);
  823. });
  824. }
  825. function getUuid() {
  826. if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") {
  827. return crypto.randomUUID();
  828. }
  829. const buf = new Uint8Array(32);
  830. if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") {
  831. crypto.getRandomValues(buf);
  832. } else {
  833. for (let i = 0; i < 32; i++) {
  834. buf[i] = Math.floor(Math.random() * 255);
  835. }
  836. }
  837. return bytesToString(buf);
  838. }
  839. /***/ }),
  840. /* 2 */
  841. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  842. Object.defineProperty(exports, "__esModule", ({
  843. value: true
  844. }));
  845. exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultFilterFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
  846. Object.defineProperty(exports, "SVGGraphics", ({
  847. enumerable: true,
  848. get: function () {
  849. return _displaySvg.SVGGraphics;
  850. }
  851. }));
  852. exports.build = void 0;
  853. exports.getDocument = getDocument;
  854. exports.version = void 0;
  855. var _util = __w_pdfjs_require__(1);
  856. var _annotation_storage = __w_pdfjs_require__(3);
  857. var _display_utils = __w_pdfjs_require__(6);
  858. var _font_loader = __w_pdfjs_require__(9);
  859. var _displayNode_utils = __w_pdfjs_require__(10);
  860. var _canvas = __w_pdfjs_require__(11);
  861. var _worker_options = __w_pdfjs_require__(14);
  862. var _message_handler = __w_pdfjs_require__(15);
  863. var _metadata = __w_pdfjs_require__(16);
  864. var _optional_content_config = __w_pdfjs_require__(17);
  865. var _transport_stream = __w_pdfjs_require__(18);
  866. var _displayFetch_stream = __w_pdfjs_require__(19);
  867. var _displayNetwork = __w_pdfjs_require__(22);
  868. var _displayNode_stream = __w_pdfjs_require__(23);
  869. var _displaySvg = __w_pdfjs_require__(24);
  870. var _xfa_text = __w_pdfjs_require__(25);
  871. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  872. const RENDERING_CANCELLED_TIMEOUT = 100;
  873. const DELAYED_CLEANUP_TIMEOUT = 5000;
  874. const DefaultCanvasFactory = _util.isNodeJS ? _displayNode_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
  875. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  876. const DefaultCMapReaderFactory = _util.isNodeJS ? _displayNode_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
  877. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  878. const DefaultFilterFactory = _util.isNodeJS ? _displayNode_utils.NodeFilterFactory : _display_utils.DOMFilterFactory;
  879. exports.DefaultFilterFactory = DefaultFilterFactory;
  880. const DefaultStandardFontDataFactory = _util.isNodeJS ? _displayNode_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
  881. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  882. function getDocument(src) {
  883. if (typeof src === "string" || src instanceof URL) {
  884. src = {
  885. url: src
  886. };
  887. } else if ((0, _util.isArrayBuffer)(src)) {
  888. src = {
  889. data: src
  890. };
  891. }
  892. if (typeof src !== "object") {
  893. throw new Error("Invalid parameter in getDocument, need parameter object.");
  894. }
  895. if (!src.url && !src.data && !src.range) {
  896. throw new Error("Invalid parameter object: need either .data, .range or .url");
  897. }
  898. const task = new PDFDocumentLoadingTask();
  899. const {
  900. docId
  901. } = task;
  902. const url = src.url ? getUrlProp(src.url) : null;
  903. const data = src.data ? getDataProp(src.data) : null;
  904. const httpHeaders = src.httpHeaders || null;
  905. const withCredentials = src.withCredentials === true;
  906. const password = src.password ?? null;
  907. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  908. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  909. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  910. const verbosity = src.verbosity;
  911. const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null;
  912. const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  913. const cMapPacked = src.cMapPacked !== false;
  914. const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  915. const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  916. const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  917. const ignoreErrors = src.stopAtErrors !== true;
  918. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  919. const isEvalSupported = src.isEvalSupported !== false;
  920. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_util.isNodeJS;
  921. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  922. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _util.isNodeJS;
  923. const fontExtraProperties = src.fontExtraProperties === true;
  924. const enableXfa = src.enableXfa === true;
  925. const ownerDocument = src.ownerDocument || globalThis.document;
  926. const disableRange = src.disableRange === true;
  927. const disableStream = src.disableStream === true;
  928. const disableAutoFetch = src.disableAutoFetch === true;
  929. const pdfBug = src.pdfBug === true;
  930. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  931. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_util.isNodeJS && !disableFontFace;
  932. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI);
  933. const canvasFactory = src.canvasFactory || new DefaultCanvasFactory({
  934. ownerDocument
  935. });
  936. const filterFactory = src.filterFactory || new DefaultFilterFactory({
  937. docId,
  938. ownerDocument
  939. });
  940. const styleElement = null;
  941. (0, _util.setVerbosityLevel)(verbosity);
  942. const transportFactory = {
  943. canvasFactory,
  944. filterFactory
  945. };
  946. if (!useWorkerFetch) {
  947. transportFactory.cMapReaderFactory = new CMapReaderFactory({
  948. baseUrl: cMapUrl,
  949. isCompressed: cMapPacked
  950. });
  951. transportFactory.standardFontDataFactory = new StandardFontDataFactory({
  952. baseUrl: standardFontDataUrl
  953. });
  954. }
  955. if (!worker) {
  956. const workerParams = {
  957. verbosity,
  958. port: _worker_options.GlobalWorkerOptions.workerPort
  959. };
  960. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  961. task._worker = worker;
  962. }
  963. const fetchDocParams = {
  964. docId,
  965. apiVersion: '3.10.111',
  966. data,
  967. password,
  968. disableAutoFetch,
  969. rangeChunkSize,
  970. length,
  971. docBaseUrl,
  972. enableXfa,
  973. evaluatorOptions: {
  974. maxImageSize,
  975. disableFontFace,
  976. ignoreErrors,
  977. isEvalSupported,
  978. isOffscreenCanvasSupported,
  979. canvasMaxAreaInBytes,
  980. fontExtraProperties,
  981. useSystemFonts,
  982. cMapUrl: useWorkerFetch ? cMapUrl : null,
  983. standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
  984. }
  985. };
  986. const transportParams = {
  987. ignoreErrors,
  988. isEvalSupported,
  989. disableFontFace,
  990. fontExtraProperties,
  991. enableXfa,
  992. ownerDocument,
  993. disableAutoFetch,
  994. pdfBug,
  995. styleElement
  996. };
  997. worker.promise.then(function () {
  998. if (task.destroyed) {
  999. throw new Error("Loading aborted");
  1000. }
  1001. const workerIdPromise = _fetchDocument(worker, fetchDocParams);
  1002. const networkStreamPromise = new Promise(function (resolve) {
  1003. let networkStream;
  1004. if (rangeTransport) {
  1005. networkStream = new _transport_stream.PDFDataTransportStream({
  1006. length,
  1007. initialData: rangeTransport.initialData,
  1008. progressiveDone: rangeTransport.progressiveDone,
  1009. contentDispositionFilename: rangeTransport.contentDispositionFilename,
  1010. disableRange,
  1011. disableStream
  1012. }, rangeTransport);
  1013. } else if (!data) {
  1014. const createPDFNetworkStream = params => {
  1015. if (_util.isNodeJS) {
  1016. return new _displayNode_stream.PDFNodeStream(params);
  1017. }
  1018. return (0, _display_utils.isValidFetchUrl)(params.url) ? new _displayFetch_stream.PDFFetchStream(params) : new _displayNetwork.PDFNetworkStream(params);
  1019. };
  1020. networkStream = createPDFNetworkStream({
  1021. url,
  1022. length,
  1023. httpHeaders,
  1024. withCredentials,
  1025. rangeChunkSize,
  1026. disableRange,
  1027. disableStream
  1028. });
  1029. }
  1030. resolve(networkStream);
  1031. });
  1032. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1033. if (task.destroyed) {
  1034. throw new Error("Loading aborted");
  1035. }
  1036. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1037. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  1038. task._transport = transport;
  1039. messageHandler.send("Ready", null);
  1040. });
  1041. }).catch(task._capability.reject);
  1042. return task;
  1043. }
  1044. async function _fetchDocument(worker, source) {
  1045. if (worker.destroyed) {
  1046. throw new Error("Worker was destroyed");
  1047. }
  1048. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null);
  1049. if (worker.destroyed) {
  1050. throw new Error("Worker was destroyed");
  1051. }
  1052. return workerId;
  1053. }
  1054. function getUrlProp(val) {
  1055. if (val instanceof URL) {
  1056. return val.href;
  1057. }
  1058. try {
  1059. return new URL(val, window.location).href;
  1060. } catch {
  1061. if (_util.isNodeJS && typeof val === "string") {
  1062. return val;
  1063. }
  1064. }
  1065. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1066. }
  1067. function getDataProp(val) {
  1068. if (_util.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  1069. throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  1070. }
  1071. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  1072. return val;
  1073. }
  1074. if (typeof val === "string") {
  1075. return (0, _util.stringToBytes)(val);
  1076. }
  1077. if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) {
  1078. return new Uint8Array(val);
  1079. }
  1080. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  1081. }
  1082. class PDFDocumentLoadingTask {
  1083. static #docId = 0;
  1084. constructor() {
  1085. this._capability = new _util.PromiseCapability();
  1086. this._transport = null;
  1087. this._worker = null;
  1088. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1089. this.destroyed = false;
  1090. this.onPassword = null;
  1091. this.onProgress = null;
  1092. }
  1093. get promise() {
  1094. return this._capability.promise;
  1095. }
  1096. async destroy() {
  1097. this.destroyed = true;
  1098. try {
  1099. if (this._worker?.port) {
  1100. this._worker._pendingDestroy = true;
  1101. }
  1102. await this._transport?.destroy();
  1103. } catch (ex) {
  1104. if (this._worker?.port) {
  1105. delete this._worker._pendingDestroy;
  1106. }
  1107. throw ex;
  1108. }
  1109. this._transport = null;
  1110. if (this._worker) {
  1111. this._worker.destroy();
  1112. this._worker = null;
  1113. }
  1114. }
  1115. }
  1116. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1117. class PDFDataRangeTransport {
  1118. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1119. this.length = length;
  1120. this.initialData = initialData;
  1121. this.progressiveDone = progressiveDone;
  1122. this.contentDispositionFilename = contentDispositionFilename;
  1123. this._rangeListeners = [];
  1124. this._progressListeners = [];
  1125. this._progressiveReadListeners = [];
  1126. this._progressiveDoneListeners = [];
  1127. this._readyCapability = new _util.PromiseCapability();
  1128. }
  1129. addRangeListener(listener) {
  1130. this._rangeListeners.push(listener);
  1131. }
  1132. addProgressListener(listener) {
  1133. this._progressListeners.push(listener);
  1134. }
  1135. addProgressiveReadListener(listener) {
  1136. this._progressiveReadListeners.push(listener);
  1137. }
  1138. addProgressiveDoneListener(listener) {
  1139. this._progressiveDoneListeners.push(listener);
  1140. }
  1141. onDataRange(begin, chunk) {
  1142. for (const listener of this._rangeListeners) {
  1143. listener(begin, chunk);
  1144. }
  1145. }
  1146. onDataProgress(loaded, total) {
  1147. this._readyCapability.promise.then(() => {
  1148. for (const listener of this._progressListeners) {
  1149. listener(loaded, total);
  1150. }
  1151. });
  1152. }
  1153. onDataProgressiveRead(chunk) {
  1154. this._readyCapability.promise.then(() => {
  1155. for (const listener of this._progressiveReadListeners) {
  1156. listener(chunk);
  1157. }
  1158. });
  1159. }
  1160. onDataProgressiveDone() {
  1161. this._readyCapability.promise.then(() => {
  1162. for (const listener of this._progressiveDoneListeners) {
  1163. listener();
  1164. }
  1165. });
  1166. }
  1167. transportReady() {
  1168. this._readyCapability.resolve();
  1169. }
  1170. requestDataRange(begin, end) {
  1171. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1172. }
  1173. abort() {}
  1174. }
  1175. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1176. class PDFDocumentProxy {
  1177. constructor(pdfInfo, transport) {
  1178. this._pdfInfo = pdfInfo;
  1179. this._transport = transport;
  1180. Object.defineProperty(this, "getJavaScript", {
  1181. value: () => {
  1182. (0, _display_utils.deprecated)("`PDFDocumentProxy.getJavaScript`, " + "please use `PDFDocumentProxy.getJSActions` instead.");
  1183. return this.getJSActions().then(js => {
  1184. if (!js) {
  1185. return js;
  1186. }
  1187. const jsArr = [];
  1188. for (const name in js) {
  1189. jsArr.push(...js[name]);
  1190. }
  1191. return jsArr;
  1192. });
  1193. }
  1194. });
  1195. }
  1196. get annotationStorage() {
  1197. return this._transport.annotationStorage;
  1198. }
  1199. get filterFactory() {
  1200. return this._transport.filterFactory;
  1201. }
  1202. get numPages() {
  1203. return this._pdfInfo.numPages;
  1204. }
  1205. get fingerprints() {
  1206. return this._pdfInfo.fingerprints;
  1207. }
  1208. get isPureXfa() {
  1209. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1210. }
  1211. get allXfaHtml() {
  1212. return this._transport._htmlForXfa;
  1213. }
  1214. getPage(pageNumber) {
  1215. return this._transport.getPage(pageNumber);
  1216. }
  1217. getPageIndex(ref) {
  1218. return this._transport.getPageIndex(ref);
  1219. }
  1220. getDestinations() {
  1221. return this._transport.getDestinations();
  1222. }
  1223. getDestination(id) {
  1224. return this._transport.getDestination(id);
  1225. }
  1226. getPageLabels() {
  1227. return this._transport.getPageLabels();
  1228. }
  1229. getPageLayout() {
  1230. return this._transport.getPageLayout();
  1231. }
  1232. getPageMode() {
  1233. return this._transport.getPageMode();
  1234. }
  1235. getViewerPreferences() {
  1236. return this._transport.getViewerPreferences();
  1237. }
  1238. getOpenAction() {
  1239. return this._transport.getOpenAction();
  1240. }
  1241. getAttachments() {
  1242. return this._transport.getAttachments();
  1243. }
  1244. getJSActions() {
  1245. return this._transport.getDocJSActions();
  1246. }
  1247. getOutline() {
  1248. return this._transport.getOutline();
  1249. }
  1250. getOptionalContentConfig() {
  1251. return this._transport.getOptionalContentConfig();
  1252. }
  1253. getPermissions() {
  1254. return this._transport.getPermissions();
  1255. }
  1256. getMetadata() {
  1257. return this._transport.getMetadata();
  1258. }
  1259. getMarkInfo() {
  1260. return this._transport.getMarkInfo();
  1261. }
  1262. getData() {
  1263. return this._transport.getData();
  1264. }
  1265. saveDocument() {
  1266. return this._transport.saveDocument();
  1267. }
  1268. getDownloadInfo() {
  1269. return this._transport.downloadInfoCapability.promise;
  1270. }
  1271. cleanup(keepLoadedFonts = false) {
  1272. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1273. }
  1274. destroy() {
  1275. return this.loadingTask.destroy();
  1276. }
  1277. get loadingParams() {
  1278. return this._transport.loadingParams;
  1279. }
  1280. get loadingTask() {
  1281. return this._transport.loadingTask;
  1282. }
  1283. getFieldObjects() {
  1284. return this._transport.getFieldObjects();
  1285. }
  1286. hasJSActions() {
  1287. return this._transport.hasJSActions();
  1288. }
  1289. getCalculationOrderIds() {
  1290. return this._transport.getCalculationOrderIds();
  1291. }
  1292. }
  1293. exports.PDFDocumentProxy = PDFDocumentProxy;
  1294. class PDFPageProxy {
  1295. #delayedCleanupTimeout = null;
  1296. #pendingCleanup = false;
  1297. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  1298. this._pageIndex = pageIndex;
  1299. this._pageInfo = pageInfo;
  1300. this._transport = transport;
  1301. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1302. this._pdfBug = pdfBug;
  1303. this.commonObjs = transport.commonObjs;
  1304. this.objs = new PDFObjects();
  1305. this._maybeCleanupAfterRender = false;
  1306. this._intentStates = new Map();
  1307. this.destroyed = false;
  1308. }
  1309. get pageNumber() {
  1310. return this._pageIndex + 1;
  1311. }
  1312. get rotate() {
  1313. return this._pageInfo.rotate;
  1314. }
  1315. get ref() {
  1316. return this._pageInfo.ref;
  1317. }
  1318. get userUnit() {
  1319. return this._pageInfo.userUnit;
  1320. }
  1321. get view() {
  1322. return this._pageInfo.view;
  1323. }
  1324. getViewport({
  1325. scale,
  1326. rotation = this.rotate,
  1327. offsetX = 0,
  1328. offsetY = 0,
  1329. dontFlip = false
  1330. } = {}) {
  1331. return new _display_utils.PageViewport({
  1332. viewBox: this.view,
  1333. scale,
  1334. rotation,
  1335. offsetX,
  1336. offsetY,
  1337. dontFlip
  1338. });
  1339. }
  1340. getAnnotations({
  1341. intent = "display"
  1342. } = {}) {
  1343. const intentArgs = this._transport.getRenderingIntent(intent);
  1344. return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1345. }
  1346. getJSActions() {
  1347. return this._transport.getPageJSActions(this._pageIndex);
  1348. }
  1349. get filterFactory() {
  1350. return this._transport.filterFactory;
  1351. }
  1352. get isPureXfa() {
  1353. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1354. }
  1355. async getXfa() {
  1356. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1357. }
  1358. render({
  1359. canvasContext,
  1360. viewport,
  1361. intent = "display",
  1362. annotationMode = _util.AnnotationMode.ENABLE,
  1363. transform = null,
  1364. background = null,
  1365. optionalContentConfigPromise = null,
  1366. annotationCanvasMap = null,
  1367. pageColors = null,
  1368. printAnnotationStorage = null
  1369. }) {
  1370. this._stats?.time("Overall");
  1371. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  1372. this.#pendingCleanup = false;
  1373. this.#abortDelayedCleanup();
  1374. if (!optionalContentConfigPromise) {
  1375. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1376. }
  1377. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1378. if (!intentState) {
  1379. intentState = Object.create(null);
  1380. this._intentStates.set(intentArgs.cacheKey, intentState);
  1381. }
  1382. if (intentState.streamReaderCancelTimeout) {
  1383. clearTimeout(intentState.streamReaderCancelTimeout);
  1384. intentState.streamReaderCancelTimeout = null;
  1385. }
  1386. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1387. if (!intentState.displayReadyCapability) {
  1388. intentState.displayReadyCapability = new _util.PromiseCapability();
  1389. intentState.operatorList = {
  1390. fnArray: [],
  1391. argsArray: [],
  1392. lastChunk: false,
  1393. separateAnnots: null
  1394. };
  1395. this._stats?.time("Page Request");
  1396. this._pumpOperatorList(intentArgs);
  1397. }
  1398. const complete = error => {
  1399. intentState.renderTasks.delete(internalRenderTask);
  1400. if (this._maybeCleanupAfterRender || intentPrint) {
  1401. this.#pendingCleanup = true;
  1402. }
  1403. this.#tryCleanup(!intentPrint);
  1404. if (error) {
  1405. internalRenderTask.capability.reject(error);
  1406. this._abortOperatorList({
  1407. intentState,
  1408. reason: error instanceof Error ? error : new Error(error)
  1409. });
  1410. } else {
  1411. internalRenderTask.capability.resolve();
  1412. }
  1413. this._stats?.timeEnd("Rendering");
  1414. this._stats?.timeEnd("Overall");
  1415. };
  1416. const internalRenderTask = new InternalRenderTask({
  1417. callback: complete,
  1418. params: {
  1419. canvasContext,
  1420. viewport,
  1421. transform,
  1422. background
  1423. },
  1424. objs: this.objs,
  1425. commonObjs: this.commonObjs,
  1426. annotationCanvasMap,
  1427. operatorList: intentState.operatorList,
  1428. pageIndex: this._pageIndex,
  1429. canvasFactory: this._transport.canvasFactory,
  1430. filterFactory: this._transport.filterFactory,
  1431. useRequestAnimationFrame: !intentPrint,
  1432. pdfBug: this._pdfBug,
  1433. pageColors
  1434. });
  1435. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  1436. const renderTask = internalRenderTask.task;
  1437. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1438. if (this.destroyed) {
  1439. complete();
  1440. return;
  1441. }
  1442. this._stats?.time("Rendering");
  1443. internalRenderTask.initializeGraphics({
  1444. transparency,
  1445. optionalContentConfig
  1446. });
  1447. internalRenderTask.operatorListChanged();
  1448. }).catch(complete);
  1449. return renderTask;
  1450. }
  1451. getOperatorList({
  1452. intent = "display",
  1453. annotationMode = _util.AnnotationMode.ENABLE,
  1454. printAnnotationStorage = null
  1455. } = {}) {
  1456. function operatorListChanged() {
  1457. if (intentState.operatorList.lastChunk) {
  1458. intentState.opListReadCapability.resolve(intentState.operatorList);
  1459. intentState.renderTasks.delete(opListTask);
  1460. }
  1461. }
  1462. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  1463. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1464. if (!intentState) {
  1465. intentState = Object.create(null);
  1466. this._intentStates.set(intentArgs.cacheKey, intentState);
  1467. }
  1468. let opListTask;
  1469. if (!intentState.opListReadCapability) {
  1470. opListTask = Object.create(null);
  1471. opListTask.operatorListChanged = operatorListChanged;
  1472. intentState.opListReadCapability = new _util.PromiseCapability();
  1473. (intentState.renderTasks ||= new Set()).add(opListTask);
  1474. intentState.operatorList = {
  1475. fnArray: [],
  1476. argsArray: [],
  1477. lastChunk: false,
  1478. separateAnnots: null
  1479. };
  1480. this._stats?.time("Page Request");
  1481. this._pumpOperatorList(intentArgs);
  1482. }
  1483. return intentState.opListReadCapability.promise;
  1484. }
  1485. streamTextContent({
  1486. includeMarkedContent = false,
  1487. disableNormalization = false
  1488. } = {}) {
  1489. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1490. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1491. pageIndex: this._pageIndex,
  1492. includeMarkedContent: includeMarkedContent === true,
  1493. disableNormalization: disableNormalization === true
  1494. }, {
  1495. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1496. size(textContent) {
  1497. return textContent.items.length;
  1498. }
  1499. });
  1500. }
  1501. getTextContent(params = {}) {
  1502. if (this._transport._htmlForXfa) {
  1503. return this.getXfa().then(xfa => {
  1504. return _xfa_text.XfaText.textContent(xfa);
  1505. });
  1506. }
  1507. const readableStream = this.streamTextContent(params);
  1508. return new Promise(function (resolve, reject) {
  1509. function pump() {
  1510. reader.read().then(function ({
  1511. value,
  1512. done
  1513. }) {
  1514. if (done) {
  1515. resolve(textContent);
  1516. return;
  1517. }
  1518. Object.assign(textContent.styles, value.styles);
  1519. textContent.items.push(...value.items);
  1520. pump();
  1521. }, reject);
  1522. }
  1523. const reader = readableStream.getReader();
  1524. const textContent = {
  1525. items: [],
  1526. styles: Object.create(null)
  1527. };
  1528. pump();
  1529. });
  1530. }
  1531. getStructTree() {
  1532. return this._transport.getStructTree(this._pageIndex);
  1533. }
  1534. _destroy() {
  1535. this.destroyed = true;
  1536. const waitOn = [];
  1537. for (const intentState of this._intentStates.values()) {
  1538. this._abortOperatorList({
  1539. intentState,
  1540. reason: new Error("Page was destroyed."),
  1541. force: true
  1542. });
  1543. if (intentState.opListReadCapability) {
  1544. continue;
  1545. }
  1546. for (const internalRenderTask of intentState.renderTasks) {
  1547. waitOn.push(internalRenderTask.completed);
  1548. internalRenderTask.cancel();
  1549. }
  1550. }
  1551. this.objs.clear();
  1552. this.#pendingCleanup = false;
  1553. this.#abortDelayedCleanup();
  1554. return Promise.all(waitOn);
  1555. }
  1556. cleanup(resetStats = false) {
  1557. this.#pendingCleanup = true;
  1558. const success = this.#tryCleanup(false);
  1559. if (resetStats && success) {
  1560. this._stats &&= new _display_utils.StatTimer();
  1561. }
  1562. return success;
  1563. }
  1564. #tryCleanup(delayed = false) {
  1565. this.#abortDelayedCleanup();
  1566. if (!this.#pendingCleanup || this.destroyed) {
  1567. return false;
  1568. }
  1569. if (delayed) {
  1570. this.#delayedCleanupTimeout = setTimeout(() => {
  1571. this.#delayedCleanupTimeout = null;
  1572. this.#tryCleanup(false);
  1573. }, DELAYED_CLEANUP_TIMEOUT);
  1574. return false;
  1575. }
  1576. for (const {
  1577. renderTasks,
  1578. operatorList
  1579. } of this._intentStates.values()) {
  1580. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  1581. return false;
  1582. }
  1583. }
  1584. this._intentStates.clear();
  1585. this.objs.clear();
  1586. this.#pendingCleanup = false;
  1587. return true;
  1588. }
  1589. #abortDelayedCleanup() {
  1590. if (this.#delayedCleanupTimeout) {
  1591. clearTimeout(this.#delayedCleanupTimeout);
  1592. this.#delayedCleanupTimeout = null;
  1593. }
  1594. }
  1595. _startRenderPage(transparency, cacheKey) {
  1596. const intentState = this._intentStates.get(cacheKey);
  1597. if (!intentState) {
  1598. return;
  1599. }
  1600. this._stats?.timeEnd("Page Request");
  1601. intentState.displayReadyCapability?.resolve(transparency);
  1602. }
  1603. _renderPageChunk(operatorListChunk, intentState) {
  1604. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  1605. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  1606. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  1607. }
  1608. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  1609. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  1610. for (const internalRenderTask of intentState.renderTasks) {
  1611. internalRenderTask.operatorListChanged();
  1612. }
  1613. if (operatorListChunk.lastChunk) {
  1614. this.#tryCleanup(true);
  1615. }
  1616. }
  1617. _pumpOperatorList({
  1618. renderingIntent,
  1619. cacheKey,
  1620. annotationStorageSerializable
  1621. }) {
  1622. const {
  1623. map,
  1624. transfers
  1625. } = annotationStorageSerializable;
  1626. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  1627. pageIndex: this._pageIndex,
  1628. intent: renderingIntent,
  1629. cacheKey,
  1630. annotationStorage: map
  1631. }, transfers);
  1632. const reader = readableStream.getReader();
  1633. const intentState = this._intentStates.get(cacheKey);
  1634. intentState.streamReader = reader;
  1635. const pump = () => {
  1636. reader.read().then(({
  1637. value,
  1638. done
  1639. }) => {
  1640. if (done) {
  1641. intentState.streamReader = null;
  1642. return;
  1643. }
  1644. if (this._transport.destroyed) {
  1645. return;
  1646. }
  1647. this._renderPageChunk(value, intentState);
  1648. pump();
  1649. }, reason => {
  1650. intentState.streamReader = null;
  1651. if (this._transport.destroyed) {
  1652. return;
  1653. }
  1654. if (intentState.operatorList) {
  1655. intentState.operatorList.lastChunk = true;
  1656. for (const internalRenderTask of intentState.renderTasks) {
  1657. internalRenderTask.operatorListChanged();
  1658. }
  1659. this.#tryCleanup(true);
  1660. }
  1661. if (intentState.displayReadyCapability) {
  1662. intentState.displayReadyCapability.reject(reason);
  1663. } else if (intentState.opListReadCapability) {
  1664. intentState.opListReadCapability.reject(reason);
  1665. } else {
  1666. throw reason;
  1667. }
  1668. });
  1669. };
  1670. pump();
  1671. }
  1672. _abortOperatorList({
  1673. intentState,
  1674. reason,
  1675. force = false
  1676. }) {
  1677. if (!intentState.streamReader) {
  1678. return;
  1679. }
  1680. if (intentState.streamReaderCancelTimeout) {
  1681. clearTimeout(intentState.streamReaderCancelTimeout);
  1682. intentState.streamReaderCancelTimeout = null;
  1683. }
  1684. if (!force) {
  1685. if (intentState.renderTasks.size > 0) {
  1686. return;
  1687. }
  1688. if (reason instanceof _display_utils.RenderingCancelledException) {
  1689. let delay = RENDERING_CANCELLED_TIMEOUT;
  1690. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  1691. delay += reason.extraDelay;
  1692. }
  1693. intentState.streamReaderCancelTimeout = setTimeout(() => {
  1694. intentState.streamReaderCancelTimeout = null;
  1695. this._abortOperatorList({
  1696. intentState,
  1697. reason,
  1698. force: true
  1699. });
  1700. }, delay);
  1701. return;
  1702. }
  1703. }
  1704. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  1705. intentState.streamReader = null;
  1706. if (this._transport.destroyed) {
  1707. return;
  1708. }
  1709. for (const [curCacheKey, curIntentState] of this._intentStates) {
  1710. if (curIntentState === intentState) {
  1711. this._intentStates.delete(curCacheKey);
  1712. break;
  1713. }
  1714. }
  1715. this.cleanup();
  1716. }
  1717. get stats() {
  1718. return this._stats;
  1719. }
  1720. }
  1721. exports.PDFPageProxy = PDFPageProxy;
  1722. class LoopbackPort {
  1723. #listeners = new Set();
  1724. #deferred = Promise.resolve();
  1725. postMessage(obj, transfer) {
  1726. const event = {
  1727. data: structuredClone(obj, transfer ? {
  1728. transfer
  1729. } : null)
  1730. };
  1731. this.#deferred.then(() => {
  1732. for (const listener of this.#listeners) {
  1733. listener.call(this, event);
  1734. }
  1735. });
  1736. }
  1737. addEventListener(name, listener) {
  1738. this.#listeners.add(listener);
  1739. }
  1740. removeEventListener(name, listener) {
  1741. this.#listeners.delete(listener);
  1742. }
  1743. terminate() {
  1744. this.#listeners.clear();
  1745. }
  1746. }
  1747. exports.LoopbackPort = LoopbackPort;
  1748. const PDFWorkerUtil = {
  1749. isWorkerDisabled: false,
  1750. fallbackWorkerSrc: null,
  1751. fakeWorkerId: 0
  1752. };
  1753. exports.PDFWorkerUtil = PDFWorkerUtil;
  1754. {
  1755. if (_util.isNodeJS && typeof require === "function") {
  1756. PDFWorkerUtil.isWorkerDisabled = true;
  1757. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  1758. } else if (typeof document === "object") {
  1759. const pdfjsFilePath = document?.currentScript?.src;
  1760. if (pdfjsFilePath) {
  1761. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  1762. }
  1763. }
  1764. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  1765. let base;
  1766. try {
  1767. base = new URL(baseUrl);
  1768. if (!base.origin || base.origin === "null") {
  1769. return false;
  1770. }
  1771. } catch {
  1772. return false;
  1773. }
  1774. const other = new URL(otherUrl, base);
  1775. return base.origin === other.origin;
  1776. };
  1777. PDFWorkerUtil.createCDNWrapper = function (url) {
  1778. const wrapper = `importScripts("${url}");`;
  1779. return URL.createObjectURL(new Blob([wrapper]));
  1780. };
  1781. }
  1782. class PDFWorker {
  1783. static #workerPorts;
  1784. constructor({
  1785. name = null,
  1786. port = null,
  1787. verbosity = (0, _util.getVerbosityLevel)()
  1788. } = {}) {
  1789. this.name = name;
  1790. this.destroyed = false;
  1791. this.verbosity = verbosity;
  1792. this._readyCapability = new _util.PromiseCapability();
  1793. this._port = null;
  1794. this._webWorker = null;
  1795. this._messageHandler = null;
  1796. if (port) {
  1797. if (PDFWorker.#workerPorts?.has(port)) {
  1798. throw new Error("Cannot use more than one PDFWorker per port.");
  1799. }
  1800. (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
  1801. this._initializeFromPort(port);
  1802. return;
  1803. }
  1804. this._initialize();
  1805. }
  1806. get promise() {
  1807. return this._readyCapability.promise;
  1808. }
  1809. get port() {
  1810. return this._port;
  1811. }
  1812. get messageHandler() {
  1813. return this._messageHandler;
  1814. }
  1815. _initializeFromPort(port) {
  1816. this._port = port;
  1817. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  1818. this._messageHandler.on("ready", function () {});
  1819. this._readyCapability.resolve();
  1820. this._messageHandler.send("configure", {
  1821. verbosity: this.verbosity
  1822. });
  1823. }
  1824. _initialize() {
  1825. if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  1826. let {
  1827. workerSrc
  1828. } = PDFWorker;
  1829. try {
  1830. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  1831. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  1832. }
  1833. const worker = new Worker(workerSrc);
  1834. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  1835. const terminateEarly = () => {
  1836. worker.removeEventListener("error", onWorkerError);
  1837. messageHandler.destroy();
  1838. worker.terminate();
  1839. if (this.destroyed) {
  1840. this._readyCapability.reject(new Error("Worker was destroyed"));
  1841. } else {
  1842. this._setupFakeWorker();
  1843. }
  1844. };
  1845. const onWorkerError = () => {
  1846. if (!this._webWorker) {
  1847. terminateEarly();
  1848. }
  1849. };
  1850. worker.addEventListener("error", onWorkerError);
  1851. messageHandler.on("test", data => {
  1852. worker.removeEventListener("error", onWorkerError);
  1853. if (this.destroyed) {
  1854. terminateEarly();
  1855. return;
  1856. }
  1857. if (data) {
  1858. this._messageHandler = messageHandler;
  1859. this._port = worker;
  1860. this._webWorker = worker;
  1861. this._readyCapability.resolve();
  1862. messageHandler.send("configure", {
  1863. verbosity: this.verbosity
  1864. });
  1865. } else {
  1866. this._setupFakeWorker();
  1867. messageHandler.destroy();
  1868. worker.terminate();
  1869. }
  1870. });
  1871. messageHandler.on("ready", data => {
  1872. worker.removeEventListener("error", onWorkerError);
  1873. if (this.destroyed) {
  1874. terminateEarly();
  1875. return;
  1876. }
  1877. try {
  1878. sendTest();
  1879. } catch {
  1880. this._setupFakeWorker();
  1881. }
  1882. });
  1883. const sendTest = () => {
  1884. const testObj = new Uint8Array();
  1885. messageHandler.send("test", testObj, [testObj.buffer]);
  1886. };
  1887. sendTest();
  1888. return;
  1889. } catch {
  1890. (0, _util.info)("The worker has been disabled.");
  1891. }
  1892. }
  1893. this._setupFakeWorker();
  1894. }
  1895. _setupFakeWorker() {
  1896. if (!PDFWorkerUtil.isWorkerDisabled) {
  1897. (0, _util.warn)("Setting up fake worker.");
  1898. PDFWorkerUtil.isWorkerDisabled = true;
  1899. }
  1900. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  1901. if (this.destroyed) {
  1902. this._readyCapability.reject(new Error("Worker was destroyed"));
  1903. return;
  1904. }
  1905. const port = new LoopbackPort();
  1906. this._port = port;
  1907. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  1908. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  1909. WorkerMessageHandler.setup(workerHandler, port);
  1910. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  1911. this._messageHandler = messageHandler;
  1912. this._readyCapability.resolve();
  1913. messageHandler.send("configure", {
  1914. verbosity: this.verbosity
  1915. });
  1916. }).catch(reason => {
  1917. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  1918. });
  1919. }
  1920. destroy() {
  1921. this.destroyed = true;
  1922. if (this._webWorker) {
  1923. this._webWorker.terminate();
  1924. this._webWorker = null;
  1925. }
  1926. PDFWorker.#workerPorts?.delete(this._port);
  1927. this._port = null;
  1928. if (this._messageHandler) {
  1929. this._messageHandler.destroy();
  1930. this._messageHandler = null;
  1931. }
  1932. }
  1933. static fromPort(params) {
  1934. if (!params?.port) {
  1935. throw new Error("PDFWorker.fromPort - invalid method signature.");
  1936. }
  1937. const cachedPort = this.#workerPorts?.get(params.port);
  1938. if (cachedPort) {
  1939. if (cachedPort._pendingDestroy) {
  1940. throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
  1941. }
  1942. return cachedPort;
  1943. }
  1944. return new PDFWorker(params);
  1945. }
  1946. static get workerSrc() {
  1947. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  1948. return _worker_options.GlobalWorkerOptions.workerSrc;
  1949. }
  1950. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  1951. if (!_util.isNodeJS) {
  1952. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  1953. }
  1954. return PDFWorkerUtil.fallbackWorkerSrc;
  1955. }
  1956. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  1957. }
  1958. static get _mainThreadWorkerMessageHandler() {
  1959. try {
  1960. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  1961. } catch {
  1962. return null;
  1963. }
  1964. }
  1965. static get _setupFakeWorkerGlobal() {
  1966. const loader = async () => {
  1967. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  1968. if (mainWorkerMessageHandler) {
  1969. return mainWorkerMessageHandler;
  1970. }
  1971. if (_util.isNodeJS && typeof require === "function") {
  1972. const worker = eval("require")(this.workerSrc);
  1973. return worker.WorkerMessageHandler;
  1974. }
  1975. await (0, _display_utils.loadScript)(this.workerSrc);
  1976. return window.pdfjsWorker.WorkerMessageHandler;
  1977. };
  1978. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  1979. }
  1980. }
  1981. exports.PDFWorker = PDFWorker;
  1982. class WorkerTransport {
  1983. #methodPromises = new Map();
  1984. #pageCache = new Map();
  1985. #pagePromises = new Map();
  1986. #passwordCapability = null;
  1987. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  1988. this.messageHandler = messageHandler;
  1989. this.loadingTask = loadingTask;
  1990. this.commonObjs = new PDFObjects();
  1991. this.fontLoader = new _font_loader.FontLoader({
  1992. ownerDocument: params.ownerDocument,
  1993. styleElement: params.styleElement
  1994. });
  1995. this._params = params;
  1996. this.canvasFactory = factory.canvasFactory;
  1997. this.filterFactory = factory.filterFactory;
  1998. this.cMapReaderFactory = factory.cMapReaderFactory;
  1999. this.standardFontDataFactory = factory.standardFontDataFactory;
  2000. this.destroyed = false;
  2001. this.destroyCapability = null;
  2002. this._networkStream = networkStream;
  2003. this._fullReader = null;
  2004. this._lastProgress = null;
  2005. this.downloadInfoCapability = new _util.PromiseCapability();
  2006. this.setupMessageHandler();
  2007. }
  2008. #cacheSimpleMethod(name, data = null) {
  2009. const cachedPromise = this.#methodPromises.get(name);
  2010. if (cachedPromise) {
  2011. return cachedPromise;
  2012. }
  2013. const promise = this.messageHandler.sendWithPromise(name, data);
  2014. this.#methodPromises.set(name, promise);
  2015. return promise;
  2016. }
  2017. get annotationStorage() {
  2018. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2019. }
  2020. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  2021. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2022. let annotationStorageSerializable = _annotation_storage.SerializableEmpty;
  2023. switch (intent) {
  2024. case "any":
  2025. renderingIntent = _util.RenderingIntentFlag.ANY;
  2026. break;
  2027. case "display":
  2028. break;
  2029. case "print":
  2030. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2031. break;
  2032. default:
  2033. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2034. }
  2035. switch (annotationMode) {
  2036. case _util.AnnotationMode.DISABLE:
  2037. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2038. break;
  2039. case _util.AnnotationMode.ENABLE:
  2040. break;
  2041. case _util.AnnotationMode.ENABLE_FORMS:
  2042. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2043. break;
  2044. case _util.AnnotationMode.ENABLE_STORAGE:
  2045. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2046. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2047. annotationStorageSerializable = annotationStorage.serializable;
  2048. break;
  2049. default:
  2050. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2051. }
  2052. if (isOpList) {
  2053. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2054. }
  2055. return {
  2056. renderingIntent,
  2057. cacheKey: `${renderingIntent}_${annotationStorageSerializable.hash}`,
  2058. annotationStorageSerializable
  2059. };
  2060. }
  2061. destroy() {
  2062. if (this.destroyCapability) {
  2063. return this.destroyCapability.promise;
  2064. }
  2065. this.destroyed = true;
  2066. this.destroyCapability = new _util.PromiseCapability();
  2067. this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
  2068. const waitOn = [];
  2069. for (const page of this.#pageCache.values()) {
  2070. waitOn.push(page._destroy());
  2071. }
  2072. this.#pageCache.clear();
  2073. this.#pagePromises.clear();
  2074. if (this.hasOwnProperty("annotationStorage")) {
  2075. this.annotationStorage.resetModified();
  2076. }
  2077. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2078. waitOn.push(terminated);
  2079. Promise.all(waitOn).then(() => {
  2080. this.commonObjs.clear();
  2081. this.fontLoader.clear();
  2082. this.#methodPromises.clear();
  2083. this.filterFactory.destroy();
  2084. this._networkStream?.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2085. if (this.messageHandler) {
  2086. this.messageHandler.destroy();
  2087. this.messageHandler = null;
  2088. }
  2089. this.destroyCapability.resolve();
  2090. }, this.destroyCapability.reject);
  2091. return this.destroyCapability.promise;
  2092. }
  2093. setupMessageHandler() {
  2094. const {
  2095. messageHandler,
  2096. loadingTask
  2097. } = this;
  2098. messageHandler.on("GetReader", (data, sink) => {
  2099. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2100. this._fullReader = this._networkStream.getFullReader();
  2101. this._fullReader.onProgress = evt => {
  2102. this._lastProgress = {
  2103. loaded: evt.loaded,
  2104. total: evt.total
  2105. };
  2106. };
  2107. sink.onPull = () => {
  2108. this._fullReader.read().then(function ({
  2109. value,
  2110. done
  2111. }) {
  2112. if (done) {
  2113. sink.close();
  2114. return;
  2115. }
  2116. (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  2117. sink.enqueue(new Uint8Array(value), 1, [value]);
  2118. }).catch(reason => {
  2119. sink.error(reason);
  2120. });
  2121. };
  2122. sink.onCancel = reason => {
  2123. this._fullReader.cancel(reason);
  2124. sink.ready.catch(readyReason => {
  2125. if (this.destroyed) {
  2126. return;
  2127. }
  2128. throw readyReason;
  2129. });
  2130. };
  2131. });
  2132. messageHandler.on("ReaderHeadersReady", data => {
  2133. const headersCapability = new _util.PromiseCapability();
  2134. const fullReader = this._fullReader;
  2135. fullReader.headersReady.then(() => {
  2136. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2137. if (this._lastProgress) {
  2138. loadingTask.onProgress?.(this._lastProgress);
  2139. }
  2140. fullReader.onProgress = evt => {
  2141. loadingTask.onProgress?.({
  2142. loaded: evt.loaded,
  2143. total: evt.total
  2144. });
  2145. };
  2146. }
  2147. headersCapability.resolve({
  2148. isStreamingSupported: fullReader.isStreamingSupported,
  2149. isRangeSupported: fullReader.isRangeSupported,
  2150. contentLength: fullReader.contentLength
  2151. });
  2152. }, headersCapability.reject);
  2153. return headersCapability.promise;
  2154. });
  2155. messageHandler.on("GetRangeReader", (data, sink) => {
  2156. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2157. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2158. if (!rangeReader) {
  2159. sink.close();
  2160. return;
  2161. }
  2162. sink.onPull = () => {
  2163. rangeReader.read().then(function ({
  2164. value,
  2165. done
  2166. }) {
  2167. if (done) {
  2168. sink.close();
  2169. return;
  2170. }
  2171. (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  2172. sink.enqueue(new Uint8Array(value), 1, [value]);
  2173. }).catch(reason => {
  2174. sink.error(reason);
  2175. });
  2176. };
  2177. sink.onCancel = reason => {
  2178. rangeReader.cancel(reason);
  2179. sink.ready.catch(readyReason => {
  2180. if (this.destroyed) {
  2181. return;
  2182. }
  2183. throw readyReason;
  2184. });
  2185. };
  2186. });
  2187. messageHandler.on("GetDoc", ({
  2188. pdfInfo
  2189. }) => {
  2190. this._numPages = pdfInfo.numPages;
  2191. this._htmlForXfa = pdfInfo.htmlForXfa;
  2192. delete pdfInfo.htmlForXfa;
  2193. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2194. });
  2195. messageHandler.on("DocException", function (ex) {
  2196. let reason;
  2197. switch (ex.name) {
  2198. case "PasswordException":
  2199. reason = new _util.PasswordException(ex.message, ex.code);
  2200. break;
  2201. case "InvalidPDFException":
  2202. reason = new _util.InvalidPDFException(ex.message);
  2203. break;
  2204. case "MissingPDFException":
  2205. reason = new _util.MissingPDFException(ex.message);
  2206. break;
  2207. case "UnexpectedResponseException":
  2208. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2209. break;
  2210. case "UnknownErrorException":
  2211. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2212. break;
  2213. default:
  2214. (0, _util.unreachable)("DocException - expected a valid Error.");
  2215. }
  2216. loadingTask._capability.reject(reason);
  2217. });
  2218. messageHandler.on("PasswordRequest", exception => {
  2219. this.#passwordCapability = new _util.PromiseCapability();
  2220. if (loadingTask.onPassword) {
  2221. const updatePassword = password => {
  2222. if (password instanceof Error) {
  2223. this.#passwordCapability.reject(password);
  2224. } else {
  2225. this.#passwordCapability.resolve({
  2226. password
  2227. });
  2228. }
  2229. };
  2230. try {
  2231. loadingTask.onPassword(updatePassword, exception.code);
  2232. } catch (ex) {
  2233. this.#passwordCapability.reject(ex);
  2234. }
  2235. } else {
  2236. this.#passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2237. }
  2238. return this.#passwordCapability.promise;
  2239. });
  2240. messageHandler.on("DataLoaded", data => {
  2241. loadingTask.onProgress?.({
  2242. loaded: data.length,
  2243. total: data.length
  2244. });
  2245. this.downloadInfoCapability.resolve(data);
  2246. });
  2247. messageHandler.on("StartRenderPage", data => {
  2248. if (this.destroyed) {
  2249. return;
  2250. }
  2251. const page = this.#pageCache.get(data.pageIndex);
  2252. page._startRenderPage(data.transparency, data.cacheKey);
  2253. });
  2254. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2255. if (this.destroyed) {
  2256. return;
  2257. }
  2258. if (this.commonObjs.has(id)) {
  2259. return;
  2260. }
  2261. switch (type) {
  2262. case "Font":
  2263. const params = this._params;
  2264. if ("error" in exportedData) {
  2265. const exportedError = exportedData.error;
  2266. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2267. this.commonObjs.resolve(id, exportedError);
  2268. break;
  2269. }
  2270. const inspectFont = params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  2271. const font = new _font_loader.FontFaceObject(exportedData, {
  2272. isEvalSupported: params.isEvalSupported,
  2273. disableFontFace: params.disableFontFace,
  2274. ignoreErrors: params.ignoreErrors,
  2275. inspectFont
  2276. });
  2277. this.fontLoader.bind(font).catch(reason => {
  2278. return messageHandler.sendWithPromise("FontFallback", {
  2279. id
  2280. });
  2281. }).finally(() => {
  2282. if (!params.fontExtraProperties && font.data) {
  2283. font.data = null;
  2284. }
  2285. this.commonObjs.resolve(id, font);
  2286. });
  2287. break;
  2288. case "FontPath":
  2289. case "Image":
  2290. case "Pattern":
  2291. this.commonObjs.resolve(id, exportedData);
  2292. break;
  2293. default:
  2294. throw new Error(`Got unknown common object type ${type}`);
  2295. }
  2296. });
  2297. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  2298. if (this.destroyed) {
  2299. return;
  2300. }
  2301. const pageProxy = this.#pageCache.get(pageIndex);
  2302. if (pageProxy.objs.has(id)) {
  2303. return;
  2304. }
  2305. switch (type) {
  2306. case "Image":
  2307. pageProxy.objs.resolve(id, imageData);
  2308. if (imageData) {
  2309. let length;
  2310. if (imageData.bitmap) {
  2311. const {
  2312. width,
  2313. height
  2314. } = imageData;
  2315. length = width * height * 4;
  2316. } else {
  2317. length = imageData.data?.length || 0;
  2318. }
  2319. if (length > _util.MAX_IMAGE_SIZE_TO_CACHE) {
  2320. pageProxy._maybeCleanupAfterRender = true;
  2321. }
  2322. }
  2323. break;
  2324. case "Pattern":
  2325. pageProxy.objs.resolve(id, imageData);
  2326. break;
  2327. default:
  2328. throw new Error(`Got unknown object type ${type}`);
  2329. }
  2330. });
  2331. messageHandler.on("DocProgress", data => {
  2332. if (this.destroyed) {
  2333. return;
  2334. }
  2335. loadingTask.onProgress?.({
  2336. loaded: data.loaded,
  2337. total: data.total
  2338. });
  2339. });
  2340. messageHandler.on("FetchBuiltInCMap", data => {
  2341. if (this.destroyed) {
  2342. return Promise.reject(new Error("Worker was destroyed."));
  2343. }
  2344. if (!this.cMapReaderFactory) {
  2345. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2346. }
  2347. return this.cMapReaderFactory.fetch(data);
  2348. });
  2349. messageHandler.on("FetchStandardFontData", data => {
  2350. if (this.destroyed) {
  2351. return Promise.reject(new Error("Worker was destroyed."));
  2352. }
  2353. if (!this.standardFontDataFactory) {
  2354. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2355. }
  2356. return this.standardFontDataFactory.fetch(data);
  2357. });
  2358. }
  2359. getData() {
  2360. return this.messageHandler.sendWithPromise("GetData", null);
  2361. }
  2362. saveDocument() {
  2363. if (this.annotationStorage.size <= 0) {
  2364. (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  2365. }
  2366. const {
  2367. map,
  2368. transfers
  2369. } = this.annotationStorage.serializable;
  2370. return this.messageHandler.sendWithPromise("SaveDocument", {
  2371. isPureXfa: !!this._htmlForXfa,
  2372. numPages: this._numPages,
  2373. annotationStorage: map,
  2374. filename: this._fullReader?.filename ?? null
  2375. }, transfers).finally(() => {
  2376. this.annotationStorage.resetModified();
  2377. });
  2378. }
  2379. getPage(pageNumber) {
  2380. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2381. return Promise.reject(new Error("Invalid page request."));
  2382. }
  2383. const pageIndex = pageNumber - 1,
  2384. cachedPromise = this.#pagePromises.get(pageIndex);
  2385. if (cachedPromise) {
  2386. return cachedPromise;
  2387. }
  2388. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2389. pageIndex
  2390. }).then(pageInfo => {
  2391. if (this.destroyed) {
  2392. throw new Error("Transport destroyed");
  2393. }
  2394. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  2395. this.#pageCache.set(pageIndex, page);
  2396. return page;
  2397. });
  2398. this.#pagePromises.set(pageIndex, promise);
  2399. return promise;
  2400. }
  2401. getPageIndex(ref) {
  2402. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  2403. return Promise.reject(new Error("Invalid pageIndex request."));
  2404. }
  2405. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2406. num: ref.num,
  2407. gen: ref.gen
  2408. });
  2409. }
  2410. getAnnotations(pageIndex, intent) {
  2411. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2412. pageIndex,
  2413. intent
  2414. });
  2415. }
  2416. getFieldObjects() {
  2417. return this.#cacheSimpleMethod("GetFieldObjects");
  2418. }
  2419. hasJSActions() {
  2420. return this.#cacheSimpleMethod("HasJSActions");
  2421. }
  2422. getCalculationOrderIds() {
  2423. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2424. }
  2425. getDestinations() {
  2426. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2427. }
  2428. getDestination(id) {
  2429. if (typeof id !== "string") {
  2430. return Promise.reject(new Error("Invalid destination request."));
  2431. }
  2432. return this.messageHandler.sendWithPromise("GetDestination", {
  2433. id
  2434. });
  2435. }
  2436. getPageLabels() {
  2437. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2438. }
  2439. getPageLayout() {
  2440. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2441. }
  2442. getPageMode() {
  2443. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2444. }
  2445. getViewerPreferences() {
  2446. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2447. }
  2448. getOpenAction() {
  2449. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2450. }
  2451. getAttachments() {
  2452. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2453. }
  2454. getDocJSActions() {
  2455. return this.#cacheSimpleMethod("GetDocJSActions");
  2456. }
  2457. getPageJSActions(pageIndex) {
  2458. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2459. pageIndex
  2460. });
  2461. }
  2462. getStructTree(pageIndex) {
  2463. return this.messageHandler.sendWithPromise("GetStructTree", {
  2464. pageIndex
  2465. });
  2466. }
  2467. getOutline() {
  2468. return this.messageHandler.sendWithPromise("GetOutline", null);
  2469. }
  2470. getOptionalContentConfig() {
  2471. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2472. return new _optional_content_config.OptionalContentConfig(results);
  2473. });
  2474. }
  2475. getPermissions() {
  2476. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2477. }
  2478. getMetadata() {
  2479. const name = "GetMetadata",
  2480. cachedPromise = this.#methodPromises.get(name);
  2481. if (cachedPromise) {
  2482. return cachedPromise;
  2483. }
  2484. const promise = this.messageHandler.sendWithPromise(name, null).then(results => {
  2485. return {
  2486. info: results[0],
  2487. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2488. contentDispositionFilename: this._fullReader?.filename ?? null,
  2489. contentLength: this._fullReader?.contentLength ?? null
  2490. };
  2491. });
  2492. this.#methodPromises.set(name, promise);
  2493. return promise;
  2494. }
  2495. getMarkInfo() {
  2496. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2497. }
  2498. async startCleanup(keepLoadedFonts = false) {
  2499. if (this.destroyed) {
  2500. return;
  2501. }
  2502. await this.messageHandler.sendWithPromise("Cleanup", null);
  2503. for (const page of this.#pageCache.values()) {
  2504. const cleanupSuccessful = page.cleanup();
  2505. if (!cleanupSuccessful) {
  2506. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  2507. }
  2508. }
  2509. this.commonObjs.clear();
  2510. if (!keepLoadedFonts) {
  2511. this.fontLoader.clear();
  2512. }
  2513. this.#methodPromises.clear();
  2514. this.filterFactory.destroy(true);
  2515. }
  2516. get loadingParams() {
  2517. const {
  2518. disableAutoFetch,
  2519. enableXfa
  2520. } = this._params;
  2521. return (0, _util.shadow)(this, "loadingParams", {
  2522. disableAutoFetch,
  2523. enableXfa
  2524. });
  2525. }
  2526. }
  2527. class PDFObjects {
  2528. #objs = Object.create(null);
  2529. #ensureObj(objId) {
  2530. return this.#objs[objId] ||= {
  2531. capability: new _util.PromiseCapability(),
  2532. data: null
  2533. };
  2534. }
  2535. get(objId, callback = null) {
  2536. if (callback) {
  2537. const obj = this.#ensureObj(objId);
  2538. obj.capability.promise.then(() => callback(obj.data));
  2539. return null;
  2540. }
  2541. const obj = this.#objs[objId];
  2542. if (!obj?.capability.settled) {
  2543. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2544. }
  2545. return obj.data;
  2546. }
  2547. has(objId) {
  2548. const obj = this.#objs[objId];
  2549. return obj?.capability.settled || false;
  2550. }
  2551. resolve(objId, data = null) {
  2552. const obj = this.#ensureObj(objId);
  2553. obj.data = data;
  2554. obj.capability.resolve();
  2555. }
  2556. clear() {
  2557. for (const objId in this.#objs) {
  2558. const {
  2559. data
  2560. } = this.#objs[objId];
  2561. data?.bitmap?.close();
  2562. }
  2563. this.#objs = Object.create(null);
  2564. }
  2565. }
  2566. class RenderTask {
  2567. #internalRenderTask = null;
  2568. constructor(internalRenderTask) {
  2569. this.#internalRenderTask = internalRenderTask;
  2570. this.onContinue = null;
  2571. }
  2572. get promise() {
  2573. return this.#internalRenderTask.capability.promise;
  2574. }
  2575. cancel(extraDelay = 0) {
  2576. this.#internalRenderTask.cancel(null, extraDelay);
  2577. }
  2578. get separateAnnots() {
  2579. const {
  2580. separateAnnots
  2581. } = this.#internalRenderTask.operatorList;
  2582. if (!separateAnnots) {
  2583. return false;
  2584. }
  2585. const {
  2586. annotationCanvasMap
  2587. } = this.#internalRenderTask;
  2588. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  2589. }
  2590. }
  2591. exports.RenderTask = RenderTask;
  2592. class InternalRenderTask {
  2593. static #canvasInUse = new WeakSet();
  2594. constructor({
  2595. callback,
  2596. params,
  2597. objs,
  2598. commonObjs,
  2599. annotationCanvasMap,
  2600. operatorList,
  2601. pageIndex,
  2602. canvasFactory,
  2603. filterFactory,
  2604. useRequestAnimationFrame = false,
  2605. pdfBug = false,
  2606. pageColors = null
  2607. }) {
  2608. this.callback = callback;
  2609. this.params = params;
  2610. this.objs = objs;
  2611. this.commonObjs = commonObjs;
  2612. this.annotationCanvasMap = annotationCanvasMap;
  2613. this.operatorListIdx = null;
  2614. this.operatorList = operatorList;
  2615. this._pageIndex = pageIndex;
  2616. this.canvasFactory = canvasFactory;
  2617. this.filterFactory = filterFactory;
  2618. this._pdfBug = pdfBug;
  2619. this.pageColors = pageColors;
  2620. this.running = false;
  2621. this.graphicsReadyCallback = null;
  2622. this.graphicsReady = false;
  2623. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  2624. this.cancelled = false;
  2625. this.capability = new _util.PromiseCapability();
  2626. this.task = new RenderTask(this);
  2627. this._cancelBound = this.cancel.bind(this);
  2628. this._continueBound = this._continue.bind(this);
  2629. this._scheduleNextBound = this._scheduleNext.bind(this);
  2630. this._nextBound = this._next.bind(this);
  2631. this._canvas = params.canvasContext.canvas;
  2632. }
  2633. get completed() {
  2634. return this.capability.promise.catch(function () {});
  2635. }
  2636. initializeGraphics({
  2637. transparency = false,
  2638. optionalContentConfig
  2639. }) {
  2640. if (this.cancelled) {
  2641. return;
  2642. }
  2643. if (this._canvas) {
  2644. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  2645. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  2646. }
  2647. InternalRenderTask.#canvasInUse.add(this._canvas);
  2648. }
  2649. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  2650. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  2651. this.stepper.init(this.operatorList);
  2652. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2653. }
  2654. const {
  2655. canvasContext,
  2656. viewport,
  2657. transform,
  2658. background
  2659. } = this.params;
  2660. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  2661. optionalContentConfig
  2662. }, this.annotationCanvasMap, this.pageColors);
  2663. this.gfx.beginDrawing({
  2664. transform,
  2665. viewport,
  2666. transparency,
  2667. background
  2668. });
  2669. this.operatorListIdx = 0;
  2670. this.graphicsReady = true;
  2671. this.graphicsReadyCallback?.();
  2672. }
  2673. cancel(error = null, extraDelay = 0) {
  2674. this.running = false;
  2675. this.cancelled = true;
  2676. this.gfx?.endDrawing();
  2677. if (this._canvas) {
  2678. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2679. }
  2680. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
  2681. }
  2682. operatorListChanged() {
  2683. if (!this.graphicsReady) {
  2684. this.graphicsReadyCallback ||= this._continueBound;
  2685. return;
  2686. }
  2687. this.stepper?.updateOperatorList(this.operatorList);
  2688. if (this.running) {
  2689. return;
  2690. }
  2691. this._continue();
  2692. }
  2693. _continue() {
  2694. this.running = true;
  2695. if (this.cancelled) {
  2696. return;
  2697. }
  2698. if (this.task.onContinue) {
  2699. this.task.onContinue(this._scheduleNextBound);
  2700. } else {
  2701. this._scheduleNext();
  2702. }
  2703. }
  2704. _scheduleNext() {
  2705. if (this._useRequestAnimationFrame) {
  2706. window.requestAnimationFrame(() => {
  2707. this._nextBound().catch(this._cancelBound);
  2708. });
  2709. } else {
  2710. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  2711. }
  2712. }
  2713. async _next() {
  2714. if (this.cancelled) {
  2715. return;
  2716. }
  2717. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  2718. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2719. this.running = false;
  2720. if (this.operatorList.lastChunk) {
  2721. this.gfx.endDrawing(this.pageColors);
  2722. if (this._canvas) {
  2723. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2724. }
  2725. this.callback();
  2726. }
  2727. }
  2728. }
  2729. }
  2730. const version = '3.10.111';
  2731. exports.version = version;
  2732. const build = 'e142baecb';
  2733. exports.build = build;
  2734. /***/ }),
  2735. /* 3 */
  2736. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2737. Object.defineProperty(exports, "__esModule", ({
  2738. value: true
  2739. }));
  2740. exports.SerializableEmpty = exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
  2741. var _util = __w_pdfjs_require__(1);
  2742. var _editor = __w_pdfjs_require__(4);
  2743. var _murmurhash = __w_pdfjs_require__(8);
  2744. const SerializableEmpty = Object.freeze({
  2745. map: null,
  2746. hash: "",
  2747. transfers: undefined
  2748. });
  2749. exports.SerializableEmpty = SerializableEmpty;
  2750. class AnnotationStorage {
  2751. #modified = false;
  2752. #storage = new Map();
  2753. constructor() {
  2754. this.onSetModified = null;
  2755. this.onResetModified = null;
  2756. this.onAnnotationEditor = null;
  2757. }
  2758. getValue(key, defaultValue) {
  2759. const value = this.#storage.get(key);
  2760. if (value === undefined) {
  2761. return defaultValue;
  2762. }
  2763. return Object.assign(defaultValue, value);
  2764. }
  2765. getRawValue(key) {
  2766. return this.#storage.get(key);
  2767. }
  2768. remove(key) {
  2769. this.#storage.delete(key);
  2770. if (this.#storage.size === 0) {
  2771. this.resetModified();
  2772. }
  2773. if (typeof this.onAnnotationEditor === "function") {
  2774. for (const value of this.#storage.values()) {
  2775. if (value instanceof _editor.AnnotationEditor) {
  2776. return;
  2777. }
  2778. }
  2779. this.onAnnotationEditor(null);
  2780. }
  2781. }
  2782. setValue(key, value) {
  2783. const obj = this.#storage.get(key);
  2784. let modified = false;
  2785. if (obj !== undefined) {
  2786. for (const [entry, val] of Object.entries(value)) {
  2787. if (obj[entry] !== val) {
  2788. modified = true;
  2789. obj[entry] = val;
  2790. }
  2791. }
  2792. } else {
  2793. modified = true;
  2794. this.#storage.set(key, value);
  2795. }
  2796. if (modified) {
  2797. this.#setModified();
  2798. }
  2799. if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  2800. this.onAnnotationEditor(value.constructor._type);
  2801. }
  2802. }
  2803. has(key) {
  2804. return this.#storage.has(key);
  2805. }
  2806. getAll() {
  2807. return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
  2808. }
  2809. setAll(obj) {
  2810. for (const [key, val] of Object.entries(obj)) {
  2811. this.setValue(key, val);
  2812. }
  2813. }
  2814. get size() {
  2815. return this.#storage.size;
  2816. }
  2817. #setModified() {
  2818. if (!this.#modified) {
  2819. this.#modified = true;
  2820. if (typeof this.onSetModified === "function") {
  2821. this.onSetModified();
  2822. }
  2823. }
  2824. }
  2825. resetModified() {
  2826. if (this.#modified) {
  2827. this.#modified = false;
  2828. if (typeof this.onResetModified === "function") {
  2829. this.onResetModified();
  2830. }
  2831. }
  2832. }
  2833. get print() {
  2834. return new PrintAnnotationStorage(this);
  2835. }
  2836. get serializable() {
  2837. if (this.#storage.size === 0) {
  2838. return SerializableEmpty;
  2839. }
  2840. const map = new Map(),
  2841. hash = new _murmurhash.MurmurHash3_64(),
  2842. transfers = [];
  2843. const context = Object.create(null);
  2844. let hasBitmap = false;
  2845. for (const [key, val] of this.#storage) {
  2846. const serialized = val instanceof _editor.AnnotationEditor ? val.serialize(false, context) : val;
  2847. if (serialized) {
  2848. map.set(key, serialized);
  2849. hash.update(`${key}:${JSON.stringify(serialized)}`);
  2850. hasBitmap ||= !!serialized.bitmap;
  2851. }
  2852. }
  2853. if (hasBitmap) {
  2854. for (const value of map.values()) {
  2855. if (value.bitmap) {
  2856. transfers.push(value.bitmap);
  2857. }
  2858. }
  2859. }
  2860. return map.size > 0 ? {
  2861. map,
  2862. hash: hash.hexdigest(),
  2863. transfers
  2864. } : SerializableEmpty;
  2865. }
  2866. }
  2867. exports.AnnotationStorage = AnnotationStorage;
  2868. class PrintAnnotationStorage extends AnnotationStorage {
  2869. #serializable;
  2870. constructor(parent) {
  2871. super();
  2872. const {
  2873. map,
  2874. hash,
  2875. transfers
  2876. } = parent.serializable;
  2877. const clone = structuredClone(map, transfers ? {
  2878. transfer: transfers
  2879. } : null);
  2880. this.#serializable = {
  2881. map: clone,
  2882. hash,
  2883. transfers
  2884. };
  2885. }
  2886. get print() {
  2887. (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  2888. }
  2889. get serializable() {
  2890. return this.#serializable;
  2891. }
  2892. }
  2893. exports.PrintAnnotationStorage = PrintAnnotationStorage;
  2894. /***/ }),
  2895. /* 4 */
  2896. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2897. Object.defineProperty(exports, "__esModule", ({
  2898. value: true
  2899. }));
  2900. exports.AnnotationEditor = void 0;
  2901. var _tools = __w_pdfjs_require__(5);
  2902. var _util = __w_pdfjs_require__(1);
  2903. class AnnotationEditor {
  2904. #keepAspectRatio = false;
  2905. #resizersDiv = null;
  2906. #boundFocusin = this.focusin.bind(this);
  2907. #boundFocusout = this.focusout.bind(this);
  2908. #hasBeenClicked = false;
  2909. #isEditing = false;
  2910. #isInEditMode = false;
  2911. _initialOptions = Object.create(null);
  2912. _uiManager = null;
  2913. _focusEventsAllowed = true;
  2914. #isDraggable = false;
  2915. #zIndex = AnnotationEditor._zIndex++;
  2916. static _colorManager = new _tools.ColorManager();
  2917. static _zIndex = 1;
  2918. constructor(parameters) {
  2919. if (this.constructor === AnnotationEditor) {
  2920. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  2921. }
  2922. this.parent = parameters.parent;
  2923. this.id = parameters.id;
  2924. this.width = this.height = null;
  2925. this.pageIndex = parameters.parent.pageIndex;
  2926. this.name = parameters.name;
  2927. this.div = null;
  2928. this._uiManager = parameters.uiManager;
  2929. this.annotationElementId = null;
  2930. this._willKeepAspectRatio = false;
  2931. this._initialOptions.isCentered = parameters.isCentered;
  2932. const {
  2933. rotation,
  2934. rawDims: {
  2935. pageWidth,
  2936. pageHeight,
  2937. pageX,
  2938. pageY
  2939. }
  2940. } = this.parent.viewport;
  2941. this.rotation = rotation;
  2942. this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
  2943. this.pageDimensions = [pageWidth, pageHeight];
  2944. this.pageTranslation = [pageX, pageY];
  2945. const [width, height] = this.parentDimensions;
  2946. this.x = parameters.x / width;
  2947. this.y = parameters.y / height;
  2948. this.isAttachedToDOM = false;
  2949. this.deleted = false;
  2950. }
  2951. static get _defaultLineColor() {
  2952. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  2953. }
  2954. static deleteAnnotationElement(editor) {
  2955. const fakeEditor = new FakeEditor({
  2956. id: editor.parent.getNextId(),
  2957. parent: editor.parent,
  2958. uiManager: editor._uiManager
  2959. });
  2960. fakeEditor.annotationElementId = editor.annotationElementId;
  2961. fakeEditor.deleted = true;
  2962. fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  2963. }
  2964. static initialize(_l10n) {}
  2965. static updateDefaultParams(_type, _value) {}
  2966. static get defaultPropertiesToUpdate() {
  2967. return [];
  2968. }
  2969. static isHandlingMimeForPasting(_mime) {
  2970. return false;
  2971. }
  2972. static paste(item, parent) {
  2973. (0, _util.unreachable)("Not implemented");
  2974. }
  2975. get propertiesToUpdate() {
  2976. return [];
  2977. }
  2978. get _isDraggable() {
  2979. return this.#isDraggable;
  2980. }
  2981. set _isDraggable(value) {
  2982. this.#isDraggable = value;
  2983. this.div?.classList.toggle("draggable", value);
  2984. }
  2985. center() {
  2986. const [pageWidth, pageHeight] = this.pageDimensions;
  2987. switch (this.parentRotation) {
  2988. case 90:
  2989. this.x -= this.height * pageHeight / (pageWidth * 2);
  2990. this.y += this.width * pageWidth / (pageHeight * 2);
  2991. break;
  2992. case 180:
  2993. this.x += this.width / 2;
  2994. this.y += this.height / 2;
  2995. break;
  2996. case 270:
  2997. this.x += this.height * pageHeight / (pageWidth * 2);
  2998. this.y -= this.width * pageWidth / (pageHeight * 2);
  2999. break;
  3000. default:
  3001. this.x -= this.width / 2;
  3002. this.y -= this.height / 2;
  3003. break;
  3004. }
  3005. this.fixAndSetPosition();
  3006. }
  3007. addCommands(params) {
  3008. this._uiManager.addCommands(params);
  3009. }
  3010. get currentLayer() {
  3011. return this._uiManager.currentLayer;
  3012. }
  3013. setInBackground() {
  3014. this.div.style.zIndex = 0;
  3015. }
  3016. setInForeground() {
  3017. this.div.style.zIndex = this.#zIndex;
  3018. }
  3019. setParent(parent) {
  3020. if (parent !== null) {
  3021. this.pageIndex = parent.pageIndex;
  3022. this.pageDimensions = parent.pageDimensions;
  3023. }
  3024. this.parent = parent;
  3025. }
  3026. focusin(event) {
  3027. if (!this._focusEventsAllowed) {
  3028. return;
  3029. }
  3030. if (!this.#hasBeenClicked) {
  3031. this.parent.setSelected(this);
  3032. } else {
  3033. this.#hasBeenClicked = false;
  3034. }
  3035. }
  3036. focusout(event) {
  3037. if (!this._focusEventsAllowed) {
  3038. return;
  3039. }
  3040. if (!this.isAttachedToDOM) {
  3041. return;
  3042. }
  3043. const target = event.relatedTarget;
  3044. if (target?.closest(`#${this.id}`)) {
  3045. return;
  3046. }
  3047. event.preventDefault();
  3048. if (!this.parent?.isMultipleSelection) {
  3049. this.commitOrRemove();
  3050. }
  3051. }
  3052. commitOrRemove() {
  3053. if (this.isEmpty()) {
  3054. this.remove();
  3055. } else {
  3056. this.commit();
  3057. }
  3058. }
  3059. commit() {
  3060. this.addToAnnotationStorage();
  3061. }
  3062. addToAnnotationStorage() {
  3063. this._uiManager.addToAnnotationStorage(this);
  3064. }
  3065. setAt(x, y, tx, ty) {
  3066. const [width, height] = this.parentDimensions;
  3067. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3068. this.x = (x + tx) / width;
  3069. this.y = (y + ty) / height;
  3070. this.fixAndSetPosition();
  3071. }
  3072. #translate([width, height], x, y) {
  3073. [x, y] = this.screenToPageTranslation(x, y);
  3074. this.x += x / width;
  3075. this.y += y / height;
  3076. this.fixAndSetPosition();
  3077. }
  3078. translate(x, y) {
  3079. this.#translate(this.parentDimensions, x, y);
  3080. }
  3081. translateInPage(x, y) {
  3082. this.#translate(this.pageDimensions, x, y);
  3083. this.moveInDOM();
  3084. this.div.scrollIntoView({
  3085. block: "nearest"
  3086. });
  3087. }
  3088. drag(tx, ty) {
  3089. const [parentWidth, parentHeight] = this.parentDimensions;
  3090. this.x += tx / parentWidth;
  3091. this.y += ty / parentHeight;
  3092. if (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1) {
  3093. const {
  3094. x,
  3095. y
  3096. } = this.div.getBoundingClientRect();
  3097. if (this.parent.findNewParent(this, x, y)) {
  3098. this.x -= Math.floor(this.x);
  3099. this.y -= Math.floor(this.y);
  3100. }
  3101. }
  3102. this.div.style.left = `${(100 * this.x).toFixed(2)}%`;
  3103. this.div.style.top = `${(100 * this.y).toFixed(2)}%`;
  3104. this.div.scrollIntoView({
  3105. block: "nearest"
  3106. });
  3107. }
  3108. fixAndSetPosition() {
  3109. const [pageWidth, pageHeight] = this.pageDimensions;
  3110. let {
  3111. x,
  3112. y,
  3113. width,
  3114. height
  3115. } = this;
  3116. width *= pageWidth;
  3117. height *= pageHeight;
  3118. x *= pageWidth;
  3119. y *= pageHeight;
  3120. switch (this.rotation) {
  3121. case 0:
  3122. x = Math.max(0, Math.min(pageWidth - width, x));
  3123. y = Math.max(0, Math.min(pageHeight - height, y));
  3124. break;
  3125. case 90:
  3126. x = Math.max(0, Math.min(pageWidth - height, x));
  3127. y = Math.min(pageHeight, Math.max(width, y));
  3128. break;
  3129. case 180:
  3130. x = Math.min(pageWidth, Math.max(width, x));
  3131. y = Math.min(pageHeight, Math.max(height, y));
  3132. break;
  3133. case 270:
  3134. x = Math.min(pageWidth, Math.max(height, x));
  3135. y = Math.max(0, Math.min(pageHeight - width, y));
  3136. break;
  3137. }
  3138. this.x = x / pageWidth;
  3139. this.y = y / pageHeight;
  3140. this.div.style.left = `${(100 * this.x).toFixed(2)}%`;
  3141. this.div.style.top = `${(100 * this.y).toFixed(2)}%`;
  3142. }
  3143. static #rotatePoint(x, y, angle) {
  3144. switch (angle) {
  3145. case 90:
  3146. return [y, -x];
  3147. case 180:
  3148. return [-x, -y];
  3149. case 270:
  3150. return [-y, x];
  3151. default:
  3152. return [x, y];
  3153. }
  3154. }
  3155. screenToPageTranslation(x, y) {
  3156. return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
  3157. }
  3158. pageTranslationToScreen(x, y) {
  3159. return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
  3160. }
  3161. #getRotationMatrix(rotation) {
  3162. switch (rotation) {
  3163. case 90:
  3164. {
  3165. const [pageWidth, pageHeight] = this.pageDimensions;
  3166. return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
  3167. }
  3168. case 180:
  3169. return [-1, 0, 0, -1];
  3170. case 270:
  3171. {
  3172. const [pageWidth, pageHeight] = this.pageDimensions;
  3173. return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
  3174. }
  3175. default:
  3176. return [1, 0, 0, 1];
  3177. }
  3178. }
  3179. get parentScale() {
  3180. return this._uiManager.viewParameters.realScale;
  3181. }
  3182. get parentRotation() {
  3183. return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  3184. }
  3185. get parentDimensions() {
  3186. const {
  3187. parentScale,
  3188. pageDimensions: [pageWidth, pageHeight]
  3189. } = this;
  3190. const scaledWidth = pageWidth * parentScale;
  3191. const scaledHeight = pageHeight * parentScale;
  3192. return _util.FeatureTest.isCSSRoundSupported ? [Math.round(scaledWidth), Math.round(scaledHeight)] : [scaledWidth, scaledHeight];
  3193. }
  3194. setDims(width, height) {
  3195. const [parentWidth, parentHeight] = this.parentDimensions;
  3196. this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
  3197. if (!this.#keepAspectRatio) {
  3198. this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
  3199. }
  3200. }
  3201. fixDims() {
  3202. const {
  3203. style
  3204. } = this.div;
  3205. const {
  3206. height,
  3207. width
  3208. } = style;
  3209. const widthPercent = width.endsWith("%");
  3210. const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
  3211. if (widthPercent && heightPercent) {
  3212. return;
  3213. }
  3214. const [parentWidth, parentHeight] = this.parentDimensions;
  3215. if (!widthPercent) {
  3216. style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
  3217. }
  3218. if (!this.#keepAspectRatio && !heightPercent) {
  3219. style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
  3220. }
  3221. }
  3222. getInitialTranslation() {
  3223. return [0, 0];
  3224. }
  3225. static #noContextMenu(e) {
  3226. e.preventDefault();
  3227. }
  3228. #createResizers() {
  3229. if (this.#resizersDiv) {
  3230. return;
  3231. }
  3232. this.#resizersDiv = document.createElement("div");
  3233. this.#resizersDiv.classList.add("resizers");
  3234. const classes = ["topLeft", "topRight", "bottomRight", "bottomLeft"];
  3235. if (!this._willKeepAspectRatio) {
  3236. classes.push("topMiddle", "middleRight", "bottomMiddle", "middleLeft");
  3237. }
  3238. for (const name of classes) {
  3239. const div = document.createElement("div");
  3240. this.#resizersDiv.append(div);
  3241. div.classList.add("resizer", name);
  3242. div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name));
  3243. div.addEventListener("contextmenu", AnnotationEditor.#noContextMenu);
  3244. }
  3245. this.div.prepend(this.#resizersDiv);
  3246. }
  3247. #resizerPointerdown(name, event) {
  3248. event.preventDefault();
  3249. const {
  3250. isMac
  3251. } = _util.FeatureTest.platform;
  3252. if (event.button !== 0 || event.ctrlKey && isMac) {
  3253. return;
  3254. }
  3255. const boundResizerPointermove = this.#resizerPointermove.bind(this, name);
  3256. const savedDraggable = this._isDraggable;
  3257. this._isDraggable = false;
  3258. const pointerMoveOptions = {
  3259. passive: true,
  3260. capture: true
  3261. };
  3262. window.addEventListener("pointermove", boundResizerPointermove, pointerMoveOptions);
  3263. const savedX = this.x;
  3264. const savedY = this.y;
  3265. const savedWidth = this.width;
  3266. const savedHeight = this.height;
  3267. const savedParentCursor = this.parent.div.style.cursor;
  3268. const savedCursor = this.div.style.cursor;
  3269. this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
  3270. const pointerUpCallback = () => {
  3271. this._isDraggable = savedDraggable;
  3272. window.removeEventListener("pointerup", pointerUpCallback);
  3273. window.removeEventListener("blur", pointerUpCallback);
  3274. window.removeEventListener("pointermove", boundResizerPointermove, pointerMoveOptions);
  3275. this.parent.div.style.cursor = savedParentCursor;
  3276. this.div.style.cursor = savedCursor;
  3277. const newX = this.x;
  3278. const newY = this.y;
  3279. const newWidth = this.width;
  3280. const newHeight = this.height;
  3281. if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
  3282. return;
  3283. }
  3284. this.addCommands({
  3285. cmd: () => {
  3286. this.width = newWidth;
  3287. this.height = newHeight;
  3288. this.x = newX;
  3289. this.y = newY;
  3290. const [parentWidth, parentHeight] = this.parentDimensions;
  3291. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  3292. this.fixAndSetPosition();
  3293. this.moveInDOM();
  3294. },
  3295. undo: () => {
  3296. this.width = savedWidth;
  3297. this.height = savedHeight;
  3298. this.x = savedX;
  3299. this.y = savedY;
  3300. const [parentWidth, parentHeight] = this.parentDimensions;
  3301. this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);
  3302. this.fixAndSetPosition();
  3303. this.moveInDOM();
  3304. },
  3305. mustExec: true
  3306. });
  3307. };
  3308. window.addEventListener("pointerup", pointerUpCallback);
  3309. window.addEventListener("blur", pointerUpCallback);
  3310. }
  3311. #resizerPointermove(name, event) {
  3312. const [parentWidth, parentHeight] = this.parentDimensions;
  3313. const savedX = this.x;
  3314. const savedY = this.y;
  3315. const savedWidth = this.width;
  3316. const savedHeight = this.height;
  3317. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  3318. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  3319. const round = x => Math.round(x * 10000) / 10000;
  3320. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  3321. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  3322. const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
  3323. const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
  3324. let getPoint;
  3325. let getOpposite;
  3326. let isDiagonal = false;
  3327. let isHorizontal = false;
  3328. switch (name) {
  3329. case "topLeft":
  3330. isDiagonal = true;
  3331. getPoint = (w, h) => [0, 0];
  3332. getOpposite = (w, h) => [w, h];
  3333. break;
  3334. case "topMiddle":
  3335. getPoint = (w, h) => [w / 2, 0];
  3336. getOpposite = (w, h) => [w / 2, h];
  3337. break;
  3338. case "topRight":
  3339. isDiagonal = true;
  3340. getPoint = (w, h) => [w, 0];
  3341. getOpposite = (w, h) => [0, h];
  3342. break;
  3343. case "middleRight":
  3344. isHorizontal = true;
  3345. getPoint = (w, h) => [w, h / 2];
  3346. getOpposite = (w, h) => [0, h / 2];
  3347. break;
  3348. case "bottomRight":
  3349. isDiagonal = true;
  3350. getPoint = (w, h) => [w, h];
  3351. getOpposite = (w, h) => [0, 0];
  3352. break;
  3353. case "bottomMiddle":
  3354. getPoint = (w, h) => [w / 2, h];
  3355. getOpposite = (w, h) => [w / 2, 0];
  3356. break;
  3357. case "bottomLeft":
  3358. isDiagonal = true;
  3359. getPoint = (w, h) => [0, h];
  3360. getOpposite = (w, h) => [w, 0];
  3361. break;
  3362. case "middleLeft":
  3363. isHorizontal = true;
  3364. getPoint = (w, h) => [0, h / 2];
  3365. getOpposite = (w, h) => [w, h / 2];
  3366. break;
  3367. }
  3368. const point = getPoint(savedWidth, savedHeight);
  3369. const oppositePoint = getOpposite(savedWidth, savedHeight);
  3370. let transfOppositePoint = transf(...oppositePoint);
  3371. const oppositeX = round(savedX + transfOppositePoint[0]);
  3372. const oppositeY = round(savedY + transfOppositePoint[1]);
  3373. let ratioX = 1;
  3374. let ratioY = 1;
  3375. let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY);
  3376. [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
  3377. if (isDiagonal) {
  3378. const oldDiag = Math.hypot(savedWidth, savedHeight);
  3379. ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
  3380. } else if (isHorizontal) {
  3381. ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
  3382. } else {
  3383. ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
  3384. }
  3385. const newWidth = round(savedWidth * ratioX);
  3386. const newHeight = round(savedHeight * ratioY);
  3387. transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
  3388. const newX = oppositeX - transfOppositePoint[0];
  3389. const newY = oppositeY - transfOppositePoint[1];
  3390. this.width = newWidth;
  3391. this.height = newHeight;
  3392. this.x = newX;
  3393. this.y = newY;
  3394. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  3395. this.fixAndSetPosition();
  3396. }
  3397. render() {
  3398. this.div = document.createElement("div");
  3399. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3400. this.div.className = this.name;
  3401. this.div.setAttribute("id", this.id);
  3402. this.div.setAttribute("tabIndex", 0);
  3403. this.setInForeground();
  3404. this.div.addEventListener("focusin", this.#boundFocusin);
  3405. this.div.addEventListener("focusout", this.#boundFocusout);
  3406. const [parentWidth, parentHeight] = this.parentDimensions;
  3407. if (this.parentRotation % 180 !== 0) {
  3408. this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
  3409. this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
  3410. }
  3411. const [tx, ty] = this.getInitialTranslation();
  3412. this.translate(tx, ty);
  3413. (0, _tools.bindEvents)(this, this.div, ["pointerdown"]);
  3414. return this.div;
  3415. }
  3416. pointerdown(event) {
  3417. const {
  3418. isMac
  3419. } = _util.FeatureTest.platform;
  3420. if (event.button !== 0 || event.ctrlKey && isMac) {
  3421. event.preventDefault();
  3422. return;
  3423. }
  3424. this.#hasBeenClicked = true;
  3425. this.#setUpDragSession(event);
  3426. }
  3427. #setUpDragSession(event) {
  3428. if (!this._isDraggable) {
  3429. return;
  3430. }
  3431. const isSelected = this._uiManager.isSelected(this);
  3432. this._uiManager.setUpDragSession();
  3433. let pointerMoveOptions, pointerMoveCallback;
  3434. if (isSelected) {
  3435. pointerMoveOptions = {
  3436. passive: true,
  3437. capture: true
  3438. };
  3439. pointerMoveCallback = e => {
  3440. const [tx, ty] = this.screenToPageTranslation(e.movementX, e.movementY);
  3441. this._uiManager.dragSelectedEditors(tx, ty);
  3442. };
  3443. window.addEventListener("pointermove", pointerMoveCallback, pointerMoveOptions);
  3444. }
  3445. const pointerUpCallback = () => {
  3446. window.removeEventListener("pointerup", pointerUpCallback);
  3447. window.removeEventListener("blur", pointerUpCallback);
  3448. if (isSelected) {
  3449. window.removeEventListener("pointermove", pointerMoveCallback, pointerMoveOptions);
  3450. }
  3451. this.#hasBeenClicked = false;
  3452. if (!this._uiManager.endDragSession()) {
  3453. const {
  3454. isMac
  3455. } = _util.FeatureTest.platform;
  3456. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3457. this.parent.toggleSelected(this);
  3458. } else {
  3459. this.parent.setSelected(this);
  3460. }
  3461. }
  3462. };
  3463. window.addEventListener("pointerup", pointerUpCallback);
  3464. window.addEventListener("blur", pointerUpCallback);
  3465. }
  3466. moveInDOM() {
  3467. this.parent.moveEditorInDOM(this);
  3468. }
  3469. _setParentAndPosition(parent, x, y) {
  3470. parent.changeParent(this);
  3471. this.x = x;
  3472. this.y = y;
  3473. this.fixAndSetPosition();
  3474. this.moveInDOM();
  3475. }
  3476. getRect(tx, ty) {
  3477. const scale = this.parentScale;
  3478. const [pageWidth, pageHeight] = this.pageDimensions;
  3479. const [pageX, pageY] = this.pageTranslation;
  3480. const shiftX = tx / scale;
  3481. const shiftY = ty / scale;
  3482. const x = this.x * pageWidth;
  3483. const y = this.y * pageHeight;
  3484. const width = this.width * pageWidth;
  3485. const height = this.height * pageHeight;
  3486. switch (this.rotation) {
  3487. case 0:
  3488. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  3489. case 90:
  3490. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  3491. case 180:
  3492. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  3493. case 270:
  3494. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  3495. default:
  3496. throw new Error("Invalid rotation");
  3497. }
  3498. }
  3499. getRectInCurrentCoords(rect, pageHeight) {
  3500. const [x1, y1, x2, y2] = rect;
  3501. const width = x2 - x1;
  3502. const height = y2 - y1;
  3503. switch (this.rotation) {
  3504. case 0:
  3505. return [x1, pageHeight - y2, width, height];
  3506. case 90:
  3507. return [x1, pageHeight - y1, height, width];
  3508. case 180:
  3509. return [x2, pageHeight - y1, width, height];
  3510. case 270:
  3511. return [x2, pageHeight - y2, height, width];
  3512. default:
  3513. throw new Error("Invalid rotation");
  3514. }
  3515. }
  3516. onceAdded() {}
  3517. isEmpty() {
  3518. return false;
  3519. }
  3520. enableEditMode() {
  3521. this.#isInEditMode = true;
  3522. }
  3523. disableEditMode() {
  3524. this.#isInEditMode = false;
  3525. }
  3526. isInEditMode() {
  3527. return this.#isInEditMode;
  3528. }
  3529. shouldGetKeyboardEvents() {
  3530. return false;
  3531. }
  3532. needsToBeRebuilt() {
  3533. return this.div && !this.isAttachedToDOM;
  3534. }
  3535. rebuild() {
  3536. this.div?.addEventListener("focusin", this.#boundFocusin);
  3537. this.div?.addEventListener("focusout", this.#boundFocusout);
  3538. }
  3539. serialize(_isForCopying = false, _context = null) {
  3540. (0, _util.unreachable)("An editor must be serializable");
  3541. }
  3542. static deserialize(data, parent, uiManager) {
  3543. const editor = new this.prototype.constructor({
  3544. parent,
  3545. id: parent.getNextId(),
  3546. uiManager
  3547. });
  3548. editor.rotation = data.rotation;
  3549. const [pageWidth, pageHeight] = editor.pageDimensions;
  3550. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3551. editor.x = x / pageWidth;
  3552. editor.y = y / pageHeight;
  3553. editor.width = width / pageWidth;
  3554. editor.height = height / pageHeight;
  3555. return editor;
  3556. }
  3557. remove() {
  3558. this.div.removeEventListener("focusin", this.#boundFocusin);
  3559. this.div.removeEventListener("focusout", this.#boundFocusout);
  3560. if (!this.isEmpty()) {
  3561. this.commit();
  3562. }
  3563. if (this.parent) {
  3564. this.parent.remove(this);
  3565. } else {
  3566. this._uiManager.removeEditor(this);
  3567. }
  3568. }
  3569. get isResizable() {
  3570. return false;
  3571. }
  3572. makeResizable() {
  3573. if (this.isResizable) {
  3574. this.#createResizers();
  3575. this.#resizersDiv.classList.remove("hidden");
  3576. }
  3577. }
  3578. select() {
  3579. this.makeResizable();
  3580. this.div?.classList.add("selectedEditor");
  3581. }
  3582. unselect() {
  3583. this.#resizersDiv?.classList.add("hidden");
  3584. this.div?.classList.remove("selectedEditor");
  3585. if (this.div?.contains(document.activeElement)) {
  3586. this._uiManager.currentLayer.div.focus();
  3587. }
  3588. }
  3589. updateParams(type, value) {}
  3590. disableEditing() {}
  3591. enableEditing() {}
  3592. enterInEditMode() {}
  3593. get contentDiv() {
  3594. return this.div;
  3595. }
  3596. get isEditing() {
  3597. return this.#isEditing;
  3598. }
  3599. set isEditing(value) {
  3600. this.#isEditing = value;
  3601. if (!this.parent) {
  3602. return;
  3603. }
  3604. if (value) {
  3605. this.parent.setSelected(this);
  3606. this.parent.setActiveEditor(this);
  3607. } else {
  3608. this.parent.setActiveEditor(null);
  3609. }
  3610. }
  3611. setAspectRatio(width, height) {
  3612. this.#keepAspectRatio = true;
  3613. const aspectRatio = width / height;
  3614. const {
  3615. style
  3616. } = this.div;
  3617. style.aspectRatio = aspectRatio;
  3618. style.height = "auto";
  3619. }
  3620. static get MIN_SIZE() {
  3621. return 16;
  3622. }
  3623. }
  3624. exports.AnnotationEditor = AnnotationEditor;
  3625. class FakeEditor extends AnnotationEditor {
  3626. constructor(params) {
  3627. super(params);
  3628. this.annotationElementId = params.annotationElementId;
  3629. this.deleted = true;
  3630. }
  3631. serialize() {
  3632. return {
  3633. id: this.annotationElementId,
  3634. deleted: true,
  3635. pageIndex: this.pageIndex
  3636. };
  3637. }
  3638. }
  3639. /***/ }),
  3640. /* 5 */
  3641. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3642. Object.defineProperty(exports, "__esModule", ({
  3643. value: true
  3644. }));
  3645. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3646. exports.bindEvents = bindEvents;
  3647. exports.opacityToHex = opacityToHex;
  3648. var _util = __w_pdfjs_require__(1);
  3649. var _display_utils = __w_pdfjs_require__(6);
  3650. function bindEvents(obj, element, names) {
  3651. for (const name of names) {
  3652. element.addEventListener(name, obj[name].bind(obj));
  3653. }
  3654. }
  3655. function opacityToHex(opacity) {
  3656. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3657. }
  3658. class IdManager {
  3659. #id = 0;
  3660. getId() {
  3661. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3662. }
  3663. }
  3664. class ImageManager {
  3665. #baseId = (0, _util.getUuid)();
  3666. #id = 0;
  3667. #cache = null;
  3668. static get _isSVGFittingCanvas() {
  3669. const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;
  3670. const canvas = new OffscreenCanvas(1, 3);
  3671. const ctx = canvas.getContext("2d");
  3672. const image = new Image();
  3673. image.src = svg;
  3674. const promise = image.decode().then(() => {
  3675. ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
  3676. return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
  3677. });
  3678. return (0, _util.shadow)(this, "_isSVGFittingCanvas", promise);
  3679. }
  3680. async #get(key, rawData) {
  3681. this.#cache ||= new Map();
  3682. let data = this.#cache.get(key);
  3683. if (data === null) {
  3684. return null;
  3685. }
  3686. if (data?.bitmap) {
  3687. data.refCounter += 1;
  3688. return data;
  3689. }
  3690. try {
  3691. data ||= {
  3692. bitmap: null,
  3693. id: `image_${this.#baseId}_${this.#id++}`,
  3694. refCounter: 0,
  3695. isSvg: false
  3696. };
  3697. let image;
  3698. if (typeof rawData === "string") {
  3699. data.url = rawData;
  3700. const response = await fetch(rawData);
  3701. if (!response.ok) {
  3702. throw new Error(response.statusText);
  3703. }
  3704. image = await response.blob();
  3705. } else {
  3706. image = data.file = rawData;
  3707. }
  3708. if (image.type === "image/svg+xml") {
  3709. const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
  3710. const fileReader = new FileReader();
  3711. const imageElement = new Image();
  3712. const imagePromise = new Promise((resolve, reject) => {
  3713. imageElement.onload = () => {
  3714. data.bitmap = imageElement;
  3715. data.isSvg = true;
  3716. resolve();
  3717. };
  3718. fileReader.onload = async () => {
  3719. const url = data.svgUrl = fileReader.result;
  3720. imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
  3721. };
  3722. imageElement.onerror = fileReader.onerror = reject;
  3723. });
  3724. fileReader.readAsDataURL(image);
  3725. await imagePromise;
  3726. } else {
  3727. data.bitmap = await createImageBitmap(image);
  3728. }
  3729. data.refCounter = 1;
  3730. } catch (e) {
  3731. console.error(e);
  3732. data = null;
  3733. }
  3734. this.#cache.set(key, data);
  3735. if (data) {
  3736. this.#cache.set(data.id, data);
  3737. }
  3738. return data;
  3739. }
  3740. async getFromFile(file) {
  3741. const {
  3742. lastModified,
  3743. name,
  3744. size,
  3745. type
  3746. } = file;
  3747. return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  3748. }
  3749. async getFromUrl(url) {
  3750. return this.#get(url, url);
  3751. }
  3752. async getFromId(id) {
  3753. this.#cache ||= new Map();
  3754. const data = this.#cache.get(id);
  3755. if (!data) {
  3756. return null;
  3757. }
  3758. if (data.bitmap) {
  3759. data.refCounter += 1;
  3760. return data;
  3761. }
  3762. if (data.file) {
  3763. return this.getFromFile(data.file);
  3764. }
  3765. return this.getFromUrl(data.url);
  3766. }
  3767. getSvgUrl(id) {
  3768. const data = this.#cache.get(id);
  3769. if (!data?.isSvg) {
  3770. return null;
  3771. }
  3772. return data.svgUrl;
  3773. }
  3774. deleteId(id) {
  3775. this.#cache ||= new Map();
  3776. const data = this.#cache.get(id);
  3777. if (!data) {
  3778. return;
  3779. }
  3780. data.refCounter -= 1;
  3781. if (data.refCounter !== 0) {
  3782. return;
  3783. }
  3784. data.bitmap = null;
  3785. }
  3786. isValidId(id) {
  3787. return id.startsWith(`image_${this.#baseId}_`);
  3788. }
  3789. }
  3790. class CommandManager {
  3791. #commands = [];
  3792. #locked = false;
  3793. #maxSize;
  3794. #position = -1;
  3795. constructor(maxSize = 128) {
  3796. this.#maxSize = maxSize;
  3797. }
  3798. add({
  3799. cmd,
  3800. undo,
  3801. mustExec,
  3802. type = NaN,
  3803. overwriteIfSameType = false,
  3804. keepUndo = false
  3805. }) {
  3806. if (mustExec) {
  3807. cmd();
  3808. }
  3809. if (this.#locked) {
  3810. return;
  3811. }
  3812. const save = {
  3813. cmd,
  3814. undo,
  3815. type
  3816. };
  3817. if (this.#position === -1) {
  3818. if (this.#commands.length > 0) {
  3819. this.#commands.length = 0;
  3820. }
  3821. this.#position = 0;
  3822. this.#commands.push(save);
  3823. return;
  3824. }
  3825. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3826. if (keepUndo) {
  3827. save.undo = this.#commands[this.#position].undo;
  3828. }
  3829. this.#commands[this.#position] = save;
  3830. return;
  3831. }
  3832. const next = this.#position + 1;
  3833. if (next === this.#maxSize) {
  3834. this.#commands.splice(0, 1);
  3835. } else {
  3836. this.#position = next;
  3837. if (next < this.#commands.length) {
  3838. this.#commands.splice(next);
  3839. }
  3840. }
  3841. this.#commands.push(save);
  3842. }
  3843. undo() {
  3844. if (this.#position === -1) {
  3845. return;
  3846. }
  3847. this.#locked = true;
  3848. this.#commands[this.#position].undo();
  3849. this.#locked = false;
  3850. this.#position -= 1;
  3851. }
  3852. redo() {
  3853. if (this.#position < this.#commands.length - 1) {
  3854. this.#position += 1;
  3855. this.#locked = true;
  3856. this.#commands[this.#position].cmd();
  3857. this.#locked = false;
  3858. }
  3859. }
  3860. hasSomethingToUndo() {
  3861. return this.#position !== -1;
  3862. }
  3863. hasSomethingToRedo() {
  3864. return this.#position < this.#commands.length - 1;
  3865. }
  3866. destroy() {
  3867. this.#commands = null;
  3868. }
  3869. }
  3870. exports.CommandManager = CommandManager;
  3871. class KeyboardManager {
  3872. constructor(callbacks) {
  3873. this.buffer = [];
  3874. this.callbacks = new Map();
  3875. this.allKeys = new Set();
  3876. const {
  3877. isMac
  3878. } = _util.FeatureTest.platform;
  3879. for (const [keys, callback, options = {}] of callbacks) {
  3880. for (const key of keys) {
  3881. const isMacKey = key.startsWith("mac+");
  3882. if (isMac && isMacKey) {
  3883. this.callbacks.set(key.slice(4), {
  3884. callback,
  3885. options
  3886. });
  3887. this.allKeys.add(key.split("+").at(-1));
  3888. } else if (!isMac && !isMacKey) {
  3889. this.callbacks.set(key, {
  3890. callback,
  3891. options
  3892. });
  3893. this.allKeys.add(key.split("+").at(-1));
  3894. }
  3895. }
  3896. }
  3897. }
  3898. #serialize(event) {
  3899. if (event.altKey) {
  3900. this.buffer.push("alt");
  3901. }
  3902. if (event.ctrlKey) {
  3903. this.buffer.push("ctrl");
  3904. }
  3905. if (event.metaKey) {
  3906. this.buffer.push("meta");
  3907. }
  3908. if (event.shiftKey) {
  3909. this.buffer.push("shift");
  3910. }
  3911. this.buffer.push(event.key);
  3912. const str = this.buffer.join("+");
  3913. this.buffer.length = 0;
  3914. return str;
  3915. }
  3916. exec(self, event) {
  3917. if (!this.allKeys.has(event.key)) {
  3918. return;
  3919. }
  3920. const info = this.callbacks.get(this.#serialize(event));
  3921. if (!info) {
  3922. return;
  3923. }
  3924. const {
  3925. callback,
  3926. options: {
  3927. bubbles = false,
  3928. args = [],
  3929. checker = null
  3930. }
  3931. } = info;
  3932. if (checker && !checker(self, event)) {
  3933. return;
  3934. }
  3935. callback.bind(self, ...args)();
  3936. if (!bubbles) {
  3937. event.stopPropagation();
  3938. event.preventDefault();
  3939. }
  3940. }
  3941. }
  3942. exports.KeyboardManager = KeyboardManager;
  3943. class ColorManager {
  3944. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  3945. get _colors() {
  3946. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  3947. (0, _display_utils.getColorValues)(colors);
  3948. return (0, _util.shadow)(this, "_colors", colors);
  3949. }
  3950. convert(color) {
  3951. const rgb = (0, _display_utils.getRGB)(color);
  3952. if (!window.matchMedia("(forced-colors: active)").matches) {
  3953. return rgb;
  3954. }
  3955. for (const [name, RGB] of this._colors) {
  3956. if (RGB.every((x, i) => x === rgb[i])) {
  3957. return ColorManager._colorsMapping.get(name);
  3958. }
  3959. }
  3960. return rgb;
  3961. }
  3962. getHexCode(name) {
  3963. const rgb = this._colors.get(name);
  3964. if (!rgb) {
  3965. return name;
  3966. }
  3967. return _util.Util.makeHexColor(...rgb);
  3968. }
  3969. }
  3970. exports.ColorManager = ColorManager;
  3971. class AnnotationEditorUIManager {
  3972. #activeEditor = null;
  3973. #allEditors = new Map();
  3974. #allLayers = new Map();
  3975. #annotationStorage = null;
  3976. #commandManager = new CommandManager();
  3977. #currentPageIndex = 0;
  3978. #deletedAnnotationsElementIds = new Set();
  3979. #draggingEditors = null;
  3980. #editorTypes = null;
  3981. #editorsToRescale = new Set();
  3982. #eventBus = null;
  3983. #filterFactory = null;
  3984. #idManager = new IdManager();
  3985. #isEnabled = false;
  3986. #isWaiting = false;
  3987. #lastActiveElement = null;
  3988. #mode = _util.AnnotationEditorType.NONE;
  3989. #selectedEditors = new Set();
  3990. #pageColors = null;
  3991. #boundBlur = this.blur.bind(this);
  3992. #boundFocus = this.focus.bind(this);
  3993. #boundCopy = this.copy.bind(this);
  3994. #boundCut = this.cut.bind(this);
  3995. #boundPaste = this.paste.bind(this);
  3996. #boundKeydown = this.keydown.bind(this);
  3997. #boundOnEditingAction = this.onEditingAction.bind(this);
  3998. #boundOnPageChanging = this.onPageChanging.bind(this);
  3999. #boundOnScaleChanging = this.onScaleChanging.bind(this);
  4000. #boundOnRotationChanging = this.onRotationChanging.bind(this);
  4001. #previousStates = {
  4002. isEditing: false,
  4003. isEmpty: true,
  4004. hasSomethingToUndo: false,
  4005. hasSomethingToRedo: false,
  4006. hasSelectedEditor: false
  4007. };
  4008. #translation = [0, 0];
  4009. #translationTimeoutId = null;
  4010. #container = null;
  4011. #viewer = null;
  4012. static TRANSLATE_SMALL = 1;
  4013. static TRANSLATE_BIG = 10;
  4014. static get _keyboardManager() {
  4015. const proto = AnnotationEditorUIManager.prototype;
  4016. const arrowChecker = self => {
  4017. const {
  4018. activeElement
  4019. } = document;
  4020. return activeElement && self.#container.contains(activeElement) && self.hasSomethingToControl();
  4021. };
  4022. const small = this.TRANSLATE_SMALL;
  4023. const big = this.TRANSLATE_BIG;
  4024. return (0, _util.shadow)(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll], [["ctrl+z", "mac+meta+z"], proto.undo], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
  4025. args: [-small, 0],
  4026. checker: arrowChecker
  4027. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
  4028. args: [-big, 0],
  4029. checker: arrowChecker
  4030. }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
  4031. args: [small, 0],
  4032. checker: arrowChecker
  4033. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
  4034. args: [big, 0],
  4035. checker: arrowChecker
  4036. }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
  4037. args: [0, -small],
  4038. checker: arrowChecker
  4039. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
  4040. args: [0, -big],
  4041. checker: arrowChecker
  4042. }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
  4043. args: [0, small],
  4044. checker: arrowChecker
  4045. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
  4046. args: [0, big],
  4047. checker: arrowChecker
  4048. }]]));
  4049. }
  4050. constructor(container, viewer, eventBus, pdfDocument, pageColors) {
  4051. this.#container = container;
  4052. this.#viewer = viewer;
  4053. this.#eventBus = eventBus;
  4054. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  4055. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  4056. this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
  4057. this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
  4058. this.#annotationStorage = pdfDocument.annotationStorage;
  4059. this.#filterFactory = pdfDocument.filterFactory;
  4060. this.#pageColors = pageColors;
  4061. this.viewParameters = {
  4062. realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
  4063. rotation: 0
  4064. };
  4065. }
  4066. destroy() {
  4067. this.#removeKeyboardManager();
  4068. this.#removeFocusManager();
  4069. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  4070. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  4071. this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
  4072. this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
  4073. for (const layer of this.#allLayers.values()) {
  4074. layer.destroy();
  4075. }
  4076. this.#allLayers.clear();
  4077. this.#allEditors.clear();
  4078. this.#editorsToRescale.clear();
  4079. this.#activeEditor = null;
  4080. this.#selectedEditors.clear();
  4081. this.#commandManager.destroy();
  4082. }
  4083. get hcmFilter() {
  4084. return (0, _util.shadow)(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  4085. }
  4086. onPageChanging({
  4087. pageNumber
  4088. }) {
  4089. this.#currentPageIndex = pageNumber - 1;
  4090. }
  4091. focusMainContainer() {
  4092. this.#container.focus();
  4093. }
  4094. findParent(x, y) {
  4095. for (const layer of this.#allLayers.values()) {
  4096. const {
  4097. x: layerX,
  4098. y: layerY,
  4099. width,
  4100. height
  4101. } = layer.div.getBoundingClientRect();
  4102. if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
  4103. return layer;
  4104. }
  4105. }
  4106. return null;
  4107. }
  4108. disableUserSelect(value = false) {
  4109. this.#viewer.classList.toggle("noUserSelect", value);
  4110. }
  4111. addShouldRescale(editor) {
  4112. this.#editorsToRescale.add(editor);
  4113. }
  4114. removeShouldRescale(editor) {
  4115. this.#editorsToRescale.delete(editor);
  4116. }
  4117. onScaleChanging({
  4118. scale
  4119. }) {
  4120. this.commitOrRemove();
  4121. this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
  4122. for (const editor of this.#editorsToRescale) {
  4123. editor.onScaleChanging();
  4124. }
  4125. }
  4126. onRotationChanging({
  4127. pagesRotation
  4128. }) {
  4129. this.commitOrRemove();
  4130. this.viewParameters.rotation = pagesRotation;
  4131. }
  4132. addToAnnotationStorage(editor) {
  4133. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  4134. this.#annotationStorage.setValue(editor.id, editor);
  4135. }
  4136. }
  4137. #addFocusManager() {
  4138. window.addEventListener("focus", this.#boundFocus);
  4139. window.addEventListener("blur", this.#boundBlur);
  4140. }
  4141. #removeFocusManager() {
  4142. window.removeEventListener("focus", this.#boundFocus);
  4143. window.removeEventListener("blur", this.#boundBlur);
  4144. }
  4145. blur() {
  4146. if (!this.hasSelection) {
  4147. return;
  4148. }
  4149. const {
  4150. activeElement
  4151. } = document;
  4152. for (const editor of this.#selectedEditors) {
  4153. if (editor.div.contains(activeElement)) {
  4154. this.#lastActiveElement = [editor, activeElement];
  4155. editor._focusEventsAllowed = false;
  4156. break;
  4157. }
  4158. }
  4159. }
  4160. focus() {
  4161. if (!this.#lastActiveElement) {
  4162. return;
  4163. }
  4164. const [lastEditor, lastActiveElement] = this.#lastActiveElement;
  4165. this.#lastActiveElement = null;
  4166. lastActiveElement.addEventListener("focusin", () => {
  4167. lastEditor._focusEventsAllowed = true;
  4168. }, {
  4169. once: true
  4170. });
  4171. lastActiveElement.focus();
  4172. }
  4173. #addKeyboardManager() {
  4174. window.addEventListener("keydown", this.#boundKeydown, {
  4175. capture: true
  4176. });
  4177. }
  4178. #removeKeyboardManager() {
  4179. window.removeEventListener("keydown", this.#boundKeydown, {
  4180. capture: true
  4181. });
  4182. }
  4183. #addCopyPasteListeners() {
  4184. document.addEventListener("copy", this.#boundCopy);
  4185. document.addEventListener("cut", this.#boundCut);
  4186. document.addEventListener("paste", this.#boundPaste);
  4187. }
  4188. #removeCopyPasteListeners() {
  4189. document.removeEventListener("copy", this.#boundCopy);
  4190. document.removeEventListener("cut", this.#boundCut);
  4191. document.removeEventListener("paste", this.#boundPaste);
  4192. }
  4193. copy(event) {
  4194. event.preventDefault();
  4195. this.#activeEditor?.commitOrRemove();
  4196. if (!this.hasSelection) {
  4197. return;
  4198. }
  4199. const editors = [];
  4200. for (const editor of this.#selectedEditors) {
  4201. const serialized = editor.serialize(true);
  4202. if (serialized) {
  4203. editors.push(serialized);
  4204. }
  4205. }
  4206. if (editors.length === 0) {
  4207. return;
  4208. }
  4209. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  4210. }
  4211. cut(event) {
  4212. this.copy(event);
  4213. this.delete();
  4214. }
  4215. paste(event) {
  4216. event.preventDefault();
  4217. const {
  4218. clipboardData
  4219. } = event;
  4220. for (const item of clipboardData.items) {
  4221. for (const editorType of this.#editorTypes) {
  4222. if (editorType.isHandlingMimeForPasting(item.type)) {
  4223. editorType.paste(item, this.currentLayer);
  4224. return;
  4225. }
  4226. }
  4227. }
  4228. let data = clipboardData.getData("application/pdfjs");
  4229. if (!data) {
  4230. return;
  4231. }
  4232. try {
  4233. data = JSON.parse(data);
  4234. } catch (ex) {
  4235. (0, _util.warn)(`paste: "${ex.message}".`);
  4236. return;
  4237. }
  4238. if (!Array.isArray(data)) {
  4239. return;
  4240. }
  4241. this.unselectAll();
  4242. const layer = this.currentLayer;
  4243. try {
  4244. const newEditors = [];
  4245. for (const editor of data) {
  4246. const deserializedEditor = layer.deserialize(editor);
  4247. if (!deserializedEditor) {
  4248. return;
  4249. }
  4250. newEditors.push(deserializedEditor);
  4251. }
  4252. const cmd = () => {
  4253. for (const editor of newEditors) {
  4254. this.#addEditorToLayer(editor);
  4255. }
  4256. this.#selectEditors(newEditors);
  4257. };
  4258. const undo = () => {
  4259. for (const editor of newEditors) {
  4260. editor.remove();
  4261. }
  4262. };
  4263. this.addCommands({
  4264. cmd,
  4265. undo,
  4266. mustExec: true
  4267. });
  4268. } catch (ex) {
  4269. (0, _util.warn)(`paste: "${ex.message}".`);
  4270. }
  4271. }
  4272. keydown(event) {
  4273. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  4274. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  4275. }
  4276. }
  4277. onEditingAction(details) {
  4278. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  4279. this[details.name]();
  4280. }
  4281. }
  4282. #dispatchUpdateStates(details) {
  4283. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  4284. if (hasChanged) {
  4285. this.#eventBus.dispatch("annotationeditorstateschanged", {
  4286. source: this,
  4287. details: Object.assign(this.#previousStates, details)
  4288. });
  4289. }
  4290. }
  4291. #dispatchUpdateUI(details) {
  4292. this.#eventBus.dispatch("annotationeditorparamschanged", {
  4293. source: this,
  4294. details
  4295. });
  4296. }
  4297. setEditingState(isEditing) {
  4298. if (isEditing) {
  4299. this.#addFocusManager();
  4300. this.#addKeyboardManager();
  4301. this.#addCopyPasteListeners();
  4302. this.#dispatchUpdateStates({
  4303. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  4304. isEmpty: this.#isEmpty(),
  4305. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  4306. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  4307. hasSelectedEditor: false
  4308. });
  4309. } else {
  4310. this.#removeFocusManager();
  4311. this.#removeKeyboardManager();
  4312. this.#removeCopyPasteListeners();
  4313. this.#dispatchUpdateStates({
  4314. isEditing: false
  4315. });
  4316. this.disableUserSelect(false);
  4317. }
  4318. }
  4319. registerEditorTypes(types) {
  4320. if (this.#editorTypes) {
  4321. return;
  4322. }
  4323. this.#editorTypes = types;
  4324. for (const editorType of this.#editorTypes) {
  4325. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  4326. }
  4327. }
  4328. getId() {
  4329. return this.#idManager.getId();
  4330. }
  4331. get currentLayer() {
  4332. return this.#allLayers.get(this.#currentPageIndex);
  4333. }
  4334. getLayer(pageIndex) {
  4335. return this.#allLayers.get(pageIndex);
  4336. }
  4337. get currentPageIndex() {
  4338. return this.#currentPageIndex;
  4339. }
  4340. addLayer(layer) {
  4341. this.#allLayers.set(layer.pageIndex, layer);
  4342. if (this.#isEnabled) {
  4343. layer.enable();
  4344. } else {
  4345. layer.disable();
  4346. }
  4347. }
  4348. removeLayer(layer) {
  4349. this.#allLayers.delete(layer.pageIndex);
  4350. }
  4351. updateMode(mode, editId = null) {
  4352. if (this.#mode === mode) {
  4353. return;
  4354. }
  4355. this.#mode = mode;
  4356. if (mode === _util.AnnotationEditorType.NONE) {
  4357. this.setEditingState(false);
  4358. this.#disableAll();
  4359. return;
  4360. }
  4361. this.setEditingState(true);
  4362. this.#enableAll();
  4363. this.unselectAll();
  4364. for (const layer of this.#allLayers.values()) {
  4365. layer.updateMode(mode);
  4366. }
  4367. if (!editId) {
  4368. return;
  4369. }
  4370. for (const editor of this.#allEditors.values()) {
  4371. if (editor.annotationElementId === editId) {
  4372. this.setSelected(editor);
  4373. editor.enterInEditMode();
  4374. break;
  4375. }
  4376. }
  4377. }
  4378. updateToolbar(mode) {
  4379. if (mode === this.#mode) {
  4380. return;
  4381. }
  4382. this.#eventBus.dispatch("switchannotationeditormode", {
  4383. source: this,
  4384. mode
  4385. });
  4386. }
  4387. updateParams(type, value) {
  4388. if (!this.#editorTypes) {
  4389. return;
  4390. }
  4391. if (type === _util.AnnotationEditorParamsType.CREATE) {
  4392. this.currentLayer.addNewEditor(type);
  4393. return;
  4394. }
  4395. for (const editor of this.#selectedEditors) {
  4396. editor.updateParams(type, value);
  4397. }
  4398. for (const editorType of this.#editorTypes) {
  4399. editorType.updateDefaultParams(type, value);
  4400. }
  4401. }
  4402. enableWaiting(mustWait = false) {
  4403. if (this.#isWaiting === mustWait) {
  4404. return;
  4405. }
  4406. this.#isWaiting = mustWait;
  4407. for (const layer of this.#allLayers.values()) {
  4408. if (mustWait) {
  4409. layer.disableClick();
  4410. } else {
  4411. layer.enableClick();
  4412. }
  4413. layer.div.classList.toggle("waiting", mustWait);
  4414. }
  4415. }
  4416. #enableAll() {
  4417. if (!this.#isEnabled) {
  4418. this.#isEnabled = true;
  4419. for (const layer of this.#allLayers.values()) {
  4420. layer.enable();
  4421. }
  4422. }
  4423. }
  4424. #disableAll() {
  4425. this.unselectAll();
  4426. if (this.#isEnabled) {
  4427. this.#isEnabled = false;
  4428. for (const layer of this.#allLayers.values()) {
  4429. layer.disable();
  4430. }
  4431. }
  4432. }
  4433. getEditors(pageIndex) {
  4434. const editors = [];
  4435. for (const editor of this.#allEditors.values()) {
  4436. if (editor.pageIndex === pageIndex) {
  4437. editors.push(editor);
  4438. }
  4439. }
  4440. return editors;
  4441. }
  4442. getEditor(id) {
  4443. return this.#allEditors.get(id);
  4444. }
  4445. addEditor(editor) {
  4446. this.#allEditors.set(editor.id, editor);
  4447. }
  4448. removeEditor(editor) {
  4449. this.#allEditors.delete(editor.id);
  4450. this.unselect(editor);
  4451. if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
  4452. this.#annotationStorage?.remove(editor.id);
  4453. }
  4454. }
  4455. addDeletedAnnotationElement(editor) {
  4456. this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
  4457. editor.deleted = true;
  4458. }
  4459. isDeletedAnnotationElement(annotationElementId) {
  4460. return this.#deletedAnnotationsElementIds.has(annotationElementId);
  4461. }
  4462. removeDeletedAnnotationElement(editor) {
  4463. this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
  4464. editor.deleted = false;
  4465. }
  4466. #addEditorToLayer(editor) {
  4467. const layer = this.#allLayers.get(editor.pageIndex);
  4468. if (layer) {
  4469. layer.addOrRebuild(editor);
  4470. } else {
  4471. this.addEditor(editor);
  4472. }
  4473. }
  4474. setActiveEditor(editor) {
  4475. if (this.#activeEditor === editor) {
  4476. return;
  4477. }
  4478. this.#activeEditor = editor;
  4479. if (editor) {
  4480. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4481. }
  4482. }
  4483. toggleSelected(editor) {
  4484. if (this.#selectedEditors.has(editor)) {
  4485. this.#selectedEditors.delete(editor);
  4486. editor.unselect();
  4487. this.#dispatchUpdateStates({
  4488. hasSelectedEditor: this.hasSelection
  4489. });
  4490. return;
  4491. }
  4492. this.#selectedEditors.add(editor);
  4493. editor.select();
  4494. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4495. this.#dispatchUpdateStates({
  4496. hasSelectedEditor: true
  4497. });
  4498. }
  4499. setSelected(editor) {
  4500. for (const ed of this.#selectedEditors) {
  4501. if (ed !== editor) {
  4502. ed.unselect();
  4503. }
  4504. }
  4505. this.#selectedEditors.clear();
  4506. this.#selectedEditors.add(editor);
  4507. editor.select();
  4508. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  4509. this.#dispatchUpdateStates({
  4510. hasSelectedEditor: true
  4511. });
  4512. }
  4513. isSelected(editor) {
  4514. return this.#selectedEditors.has(editor);
  4515. }
  4516. unselect(editor) {
  4517. editor.unselect();
  4518. this.#selectedEditors.delete(editor);
  4519. this.#dispatchUpdateStates({
  4520. hasSelectedEditor: this.hasSelection
  4521. });
  4522. }
  4523. get hasSelection() {
  4524. return this.#selectedEditors.size !== 0;
  4525. }
  4526. undo() {
  4527. this.#commandManager.undo();
  4528. this.#dispatchUpdateStates({
  4529. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  4530. hasSomethingToRedo: true,
  4531. isEmpty: this.#isEmpty()
  4532. });
  4533. }
  4534. redo() {
  4535. this.#commandManager.redo();
  4536. this.#dispatchUpdateStates({
  4537. hasSomethingToUndo: true,
  4538. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  4539. isEmpty: this.#isEmpty()
  4540. });
  4541. }
  4542. addCommands(params) {
  4543. this.#commandManager.add(params);
  4544. this.#dispatchUpdateStates({
  4545. hasSomethingToUndo: true,
  4546. hasSomethingToRedo: false,
  4547. isEmpty: this.#isEmpty()
  4548. });
  4549. }
  4550. #isEmpty() {
  4551. if (this.#allEditors.size === 0) {
  4552. return true;
  4553. }
  4554. if (this.#allEditors.size === 1) {
  4555. for (const editor of this.#allEditors.values()) {
  4556. return editor.isEmpty();
  4557. }
  4558. }
  4559. return false;
  4560. }
  4561. delete() {
  4562. this.commitOrRemove();
  4563. if (!this.hasSelection) {
  4564. return;
  4565. }
  4566. const editors = [...this.#selectedEditors];
  4567. const cmd = () => {
  4568. for (const editor of editors) {
  4569. editor.remove();
  4570. }
  4571. };
  4572. const undo = () => {
  4573. for (const editor of editors) {
  4574. this.#addEditorToLayer(editor);
  4575. }
  4576. };
  4577. this.addCommands({
  4578. cmd,
  4579. undo,
  4580. mustExec: true
  4581. });
  4582. }
  4583. commitOrRemove() {
  4584. this.#activeEditor?.commitOrRemove();
  4585. }
  4586. hasSomethingToControl() {
  4587. return this.#activeEditor || this.hasSelection;
  4588. }
  4589. #selectEditors(editors) {
  4590. this.#selectedEditors.clear();
  4591. for (const editor of editors) {
  4592. if (editor.isEmpty()) {
  4593. continue;
  4594. }
  4595. this.#selectedEditors.add(editor);
  4596. editor.select();
  4597. }
  4598. this.#dispatchUpdateStates({
  4599. hasSelectedEditor: true
  4600. });
  4601. }
  4602. selectAll() {
  4603. for (const editor of this.#selectedEditors) {
  4604. editor.commit();
  4605. }
  4606. this.#selectEditors(this.#allEditors.values());
  4607. }
  4608. unselectAll() {
  4609. if (this.#activeEditor) {
  4610. this.#activeEditor.commitOrRemove();
  4611. return;
  4612. }
  4613. if (!this.hasSelection) {
  4614. return;
  4615. }
  4616. for (const editor of this.#selectedEditors) {
  4617. editor.unselect();
  4618. }
  4619. this.#selectedEditors.clear();
  4620. this.#dispatchUpdateStates({
  4621. hasSelectedEditor: false
  4622. });
  4623. }
  4624. translateSelectedEditors(x, y, noCommit = false) {
  4625. if (!noCommit) {
  4626. this.commitOrRemove();
  4627. }
  4628. if (!this.hasSelection) {
  4629. return;
  4630. }
  4631. this.#translation[0] += x;
  4632. this.#translation[1] += y;
  4633. const [totalX, totalY] = this.#translation;
  4634. const editors = [...this.#selectedEditors];
  4635. const TIME_TO_WAIT = 1000;
  4636. if (this.#translationTimeoutId) {
  4637. clearTimeout(this.#translationTimeoutId);
  4638. }
  4639. this.#translationTimeoutId = setTimeout(() => {
  4640. this.#translationTimeoutId = null;
  4641. this.#translation[0] = this.#translation[1] = 0;
  4642. this.addCommands({
  4643. cmd: () => {
  4644. for (const editor of editors) {
  4645. if (this.#allEditors.has(editor.id)) {
  4646. editor.translateInPage(totalX, totalY);
  4647. }
  4648. }
  4649. },
  4650. undo: () => {
  4651. for (const editor of editors) {
  4652. if (this.#allEditors.has(editor.id)) {
  4653. editor.translateInPage(-totalX, -totalY);
  4654. }
  4655. }
  4656. },
  4657. mustExec: false
  4658. });
  4659. }, TIME_TO_WAIT);
  4660. for (const editor of editors) {
  4661. editor.translateInPage(x, y);
  4662. }
  4663. }
  4664. setUpDragSession() {
  4665. if (!this.hasSelection) {
  4666. return;
  4667. }
  4668. this.disableUserSelect(true);
  4669. this.#draggingEditors = new Map();
  4670. for (const editor of this.#selectedEditors) {
  4671. this.#draggingEditors.set(editor, {
  4672. savedX: editor.x,
  4673. savedY: editor.y,
  4674. savedPageIndex: editor.parent.pageIndex,
  4675. newX: 0,
  4676. newY: 0,
  4677. newPageIndex: -1
  4678. });
  4679. }
  4680. }
  4681. endDragSession() {
  4682. if (!this.#draggingEditors) {
  4683. return false;
  4684. }
  4685. this.disableUserSelect(false);
  4686. const map = this.#draggingEditors;
  4687. this.#draggingEditors = null;
  4688. let mustBeAddedInUndoStack = false;
  4689. for (const [{
  4690. x,
  4691. y,
  4692. parent
  4693. }, value] of map) {
  4694. value.newX = x;
  4695. value.newY = y;
  4696. value.newPageIndex = parent.pageIndex;
  4697. mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || parent.pageIndex !== value.savedPageIndex;
  4698. }
  4699. if (!mustBeAddedInUndoStack) {
  4700. return false;
  4701. }
  4702. const move = (editor, x, y, pageIndex) => {
  4703. if (this.#allEditors.has(editor.id)) {
  4704. const parent = this.#allLayers.get(pageIndex);
  4705. if (parent) {
  4706. editor._setParentAndPosition(parent, x, y);
  4707. } else {
  4708. editor.pageIndex = pageIndex;
  4709. editor.x = x;
  4710. editor.y = y;
  4711. }
  4712. }
  4713. };
  4714. this.addCommands({
  4715. cmd: () => {
  4716. for (const [editor, {
  4717. newX,
  4718. newY,
  4719. newPageIndex
  4720. }] of map) {
  4721. move(editor, newX, newY, newPageIndex);
  4722. }
  4723. },
  4724. undo: () => {
  4725. for (const [editor, {
  4726. savedX,
  4727. savedY,
  4728. savedPageIndex
  4729. }] of map) {
  4730. move(editor, savedX, savedY, savedPageIndex);
  4731. }
  4732. },
  4733. mustExec: true
  4734. });
  4735. return true;
  4736. }
  4737. dragSelectedEditors(tx, ty) {
  4738. if (!this.#draggingEditors) {
  4739. return;
  4740. }
  4741. for (const editor of this.#draggingEditors.keys()) {
  4742. editor.drag(tx, ty);
  4743. }
  4744. }
  4745. rebuild(editor) {
  4746. if (editor.parent === null) {
  4747. const parent = this.getLayer(editor.pageIndex);
  4748. if (parent) {
  4749. parent.changeParent(editor);
  4750. parent.addOrRebuild(editor);
  4751. } else {
  4752. this.addEditor(editor);
  4753. this.addToAnnotationStorage(editor);
  4754. editor.rebuild();
  4755. }
  4756. } else {
  4757. editor.parent.addOrRebuild(editor);
  4758. }
  4759. }
  4760. isActive(editor) {
  4761. return this.#activeEditor === editor;
  4762. }
  4763. getActive() {
  4764. return this.#activeEditor;
  4765. }
  4766. getMode() {
  4767. return this.#mode;
  4768. }
  4769. get imageManager() {
  4770. return (0, _util.shadow)(this, "imageManager", new ImageManager());
  4771. }
  4772. }
  4773. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  4774. /***/ }),
  4775. /* 6 */
  4776. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4777. Object.defineProperty(exports, "__esModule", ({
  4778. value: true
  4779. }));
  4780. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMFilterFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  4781. exports.deprecated = deprecated;
  4782. exports.getColorValues = getColorValues;
  4783. exports.getCurrentTransform = getCurrentTransform;
  4784. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  4785. exports.getFilenameFromUrl = getFilenameFromUrl;
  4786. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  4787. exports.getRGB = getRGB;
  4788. exports.getXfaPageViewport = getXfaPageViewport;
  4789. exports.isDataScheme = isDataScheme;
  4790. exports.isPdfFile = isPdfFile;
  4791. exports.isValidFetchUrl = isValidFetchUrl;
  4792. exports.loadScript = loadScript;
  4793. exports.setLayerDimensions = setLayerDimensions;
  4794. var _base_factory = __w_pdfjs_require__(7);
  4795. var _util = __w_pdfjs_require__(1);
  4796. const SVG_NS = "http://www.w3.org/2000/svg";
  4797. const AnnotationPrefix = "pdfjs_internal_id_";
  4798. exports.AnnotationPrefix = AnnotationPrefix;
  4799. class PixelsPerInch {
  4800. static CSS = 96.0;
  4801. static PDF = 72.0;
  4802. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  4803. }
  4804. exports.PixelsPerInch = PixelsPerInch;
  4805. class DOMFilterFactory extends _base_factory.BaseFilterFactory {
  4806. #_cache;
  4807. #_defs;
  4808. #docId;
  4809. #document;
  4810. #hcmFilter;
  4811. #hcmKey;
  4812. #hcmUrl;
  4813. #hcmHighlightFilter;
  4814. #hcmHighlightKey;
  4815. #hcmHighlightUrl;
  4816. #id = 0;
  4817. constructor({
  4818. docId,
  4819. ownerDocument = globalThis.document
  4820. } = {}) {
  4821. super();
  4822. this.#docId = docId;
  4823. this.#document = ownerDocument;
  4824. }
  4825. get #cache() {
  4826. return this.#_cache ||= new Map();
  4827. }
  4828. get #defs() {
  4829. if (!this.#_defs) {
  4830. const div = this.#document.createElement("div");
  4831. const {
  4832. style
  4833. } = div;
  4834. style.visibility = "hidden";
  4835. style.contain = "strict";
  4836. style.width = style.height = 0;
  4837. style.position = "absolute";
  4838. style.top = style.left = 0;
  4839. style.zIndex = -1;
  4840. const svg = this.#document.createElementNS(SVG_NS, "svg");
  4841. svg.setAttribute("width", 0);
  4842. svg.setAttribute("height", 0);
  4843. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  4844. div.append(svg);
  4845. svg.append(this.#_defs);
  4846. this.#document.body.append(div);
  4847. }
  4848. return this.#_defs;
  4849. }
  4850. addFilter(maps) {
  4851. if (!maps) {
  4852. return "none";
  4853. }
  4854. let value = this.#cache.get(maps);
  4855. if (value) {
  4856. return value;
  4857. }
  4858. let tableR, tableG, tableB, key;
  4859. if (maps.length === 1) {
  4860. const mapR = maps[0];
  4861. const buffer = new Array(256);
  4862. for (let i = 0; i < 256; i++) {
  4863. buffer[i] = mapR[i] / 255;
  4864. }
  4865. key = tableR = tableG = tableB = buffer.join(",");
  4866. } else {
  4867. const [mapR, mapG, mapB] = maps;
  4868. const bufferR = new Array(256);
  4869. const bufferG = new Array(256);
  4870. const bufferB = new Array(256);
  4871. for (let i = 0; i < 256; i++) {
  4872. bufferR[i] = mapR[i] / 255;
  4873. bufferG[i] = mapG[i] / 255;
  4874. bufferB[i] = mapB[i] / 255;
  4875. }
  4876. tableR = bufferR.join(",");
  4877. tableG = bufferG.join(",");
  4878. tableB = bufferB.join(",");
  4879. key = `${tableR}${tableG}${tableB}`;
  4880. }
  4881. value = this.#cache.get(key);
  4882. if (value) {
  4883. this.#cache.set(maps, value);
  4884. return value;
  4885. }
  4886. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  4887. const url = `url(#${id})`;
  4888. this.#cache.set(maps, url);
  4889. this.#cache.set(key, url);
  4890. const filter = this.#createFilter(id);
  4891. this.#addTransferMapConversion(tableR, tableG, tableB, filter);
  4892. return url;
  4893. }
  4894. addHCMFilter(fgColor, bgColor) {
  4895. const key = `${fgColor}-${bgColor}`;
  4896. if (this.#hcmKey === key) {
  4897. return this.#hcmUrl;
  4898. }
  4899. this.#hcmKey = key;
  4900. this.#hcmUrl = "none";
  4901. this.#hcmFilter?.remove();
  4902. if (!fgColor || !bgColor) {
  4903. return this.#hcmUrl;
  4904. }
  4905. const fgRGB = this.#getRGB(fgColor);
  4906. fgColor = _util.Util.makeHexColor(...fgRGB);
  4907. const bgRGB = this.#getRGB(bgColor);
  4908. bgColor = _util.Util.makeHexColor(...bgRGB);
  4909. this.#defs.style.color = "";
  4910. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  4911. return this.#hcmUrl;
  4912. }
  4913. const map = new Array(256);
  4914. for (let i = 0; i <= 255; i++) {
  4915. const x = i / 255;
  4916. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  4917. }
  4918. const table = map.join(",");
  4919. const id = `g_${this.#docId}_hcm_filter`;
  4920. const filter = this.#hcmHighlightFilter = this.#createFilter(id);
  4921. this.#addTransferMapConversion(table, table, table, filter);
  4922. this.#addGrayConversion(filter);
  4923. const getSteps = (c, n) => {
  4924. const start = fgRGB[c] / 255;
  4925. const end = bgRGB[c] / 255;
  4926. const arr = new Array(n + 1);
  4927. for (let i = 0; i <= n; i++) {
  4928. arr[i] = start + i / n * (end - start);
  4929. }
  4930. return arr.join(",");
  4931. };
  4932. this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
  4933. this.#hcmUrl = `url(#${id})`;
  4934. return this.#hcmUrl;
  4935. }
  4936. addHighlightHCMFilter(fgColor, bgColor, newFgColor, newBgColor) {
  4937. const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
  4938. if (this.#hcmHighlightKey === key) {
  4939. return this.#hcmHighlightUrl;
  4940. }
  4941. this.#hcmHighlightKey = key;
  4942. this.#hcmHighlightUrl = "none";
  4943. this.#hcmHighlightFilter?.remove();
  4944. if (!fgColor || !bgColor) {
  4945. return this.#hcmHighlightUrl;
  4946. }
  4947. const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
  4948. let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
  4949. let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
  4950. let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
  4951. if (bgGray < fgGray) {
  4952. [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
  4953. }
  4954. this.#defs.style.color = "";
  4955. const getSteps = (fg, bg, n) => {
  4956. const arr = new Array(256);
  4957. const step = (bgGray - fgGray) / n;
  4958. const newStart = fg / 255;
  4959. const newStep = (bg - fg) / (255 * n);
  4960. let prev = 0;
  4961. for (let i = 0; i <= n; i++) {
  4962. const k = Math.round(fgGray + i * step);
  4963. const value = newStart + i * newStep;
  4964. for (let j = prev; j <= k; j++) {
  4965. arr[j] = value;
  4966. }
  4967. prev = k + 1;
  4968. }
  4969. for (let i = prev; i < 256; i++) {
  4970. arr[i] = arr[prev - 1];
  4971. }
  4972. return arr.join(",");
  4973. };
  4974. const id = `g_${this.#docId}_hcm_highlight_filter`;
  4975. const filter = this.#hcmHighlightFilter = this.#createFilter(id);
  4976. this.#addGrayConversion(filter);
  4977. this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
  4978. this.#hcmHighlightUrl = `url(#${id})`;
  4979. return this.#hcmHighlightUrl;
  4980. }
  4981. destroy(keepHCM = false) {
  4982. if (keepHCM && (this.#hcmUrl || this.#hcmHighlightUrl)) {
  4983. return;
  4984. }
  4985. if (this.#_defs) {
  4986. this.#_defs.parentNode.parentNode.remove();
  4987. this.#_defs = null;
  4988. }
  4989. if (this.#_cache) {
  4990. this.#_cache.clear();
  4991. this.#_cache = null;
  4992. }
  4993. this.#id = 0;
  4994. }
  4995. #addGrayConversion(filter) {
  4996. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  4997. feColorMatrix.setAttribute("type", "matrix");
  4998. feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
  4999. filter.append(feColorMatrix);
  5000. }
  5001. #createFilter(id) {
  5002. const filter = this.#document.createElementNS(SVG_NS, "filter");
  5003. filter.setAttribute("color-interpolation-filters", "sRGB");
  5004. filter.setAttribute("id", id);
  5005. this.#defs.append(filter);
  5006. return filter;
  5007. }
  5008. #appendFeFunc(feComponentTransfer, func, table) {
  5009. const feFunc = this.#document.createElementNS(SVG_NS, func);
  5010. feFunc.setAttribute("type", "discrete");
  5011. feFunc.setAttribute("tableValues", table);
  5012. feComponentTransfer.append(feFunc);
  5013. }
  5014. #addTransferMapConversion(rTable, gTable, bTable, filter) {
  5015. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  5016. filter.append(feComponentTransfer);
  5017. this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
  5018. this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
  5019. this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  5020. }
  5021. #getRGB(color) {
  5022. this.#defs.style.color = color;
  5023. return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  5024. }
  5025. }
  5026. exports.DOMFilterFactory = DOMFilterFactory;
  5027. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  5028. constructor({
  5029. ownerDocument = globalThis.document
  5030. } = {}) {
  5031. super();
  5032. this._document = ownerDocument;
  5033. }
  5034. _createCanvas(width, height) {
  5035. const canvas = this._document.createElement("canvas");
  5036. canvas.width = width;
  5037. canvas.height = height;
  5038. return canvas;
  5039. }
  5040. }
  5041. exports.DOMCanvasFactory = DOMCanvasFactory;
  5042. async function fetchData(url, asTypedArray = false) {
  5043. if (isValidFetchUrl(url, document.baseURI)) {
  5044. const response = await fetch(url);
  5045. if (!response.ok) {
  5046. throw new Error(response.statusText);
  5047. }
  5048. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  5049. }
  5050. return new Promise((resolve, reject) => {
  5051. const request = new XMLHttpRequest();
  5052. request.open("GET", url, true);
  5053. if (asTypedArray) {
  5054. request.responseType = "arraybuffer";
  5055. }
  5056. request.onreadystatechange = () => {
  5057. if (request.readyState !== XMLHttpRequest.DONE) {
  5058. return;
  5059. }
  5060. if (request.status === 200 || request.status === 0) {
  5061. let data;
  5062. if (asTypedArray && request.response) {
  5063. data = new Uint8Array(request.response);
  5064. } else if (!asTypedArray && request.responseText) {
  5065. data = (0, _util.stringToBytes)(request.responseText);
  5066. }
  5067. if (data) {
  5068. resolve(data);
  5069. return;
  5070. }
  5071. }
  5072. reject(new Error(request.statusText));
  5073. };
  5074. request.send(null);
  5075. });
  5076. }
  5077. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  5078. _fetchData(url, compressionType) {
  5079. return fetchData(url, this.isCompressed).then(data => {
  5080. return {
  5081. cMapData: data,
  5082. compressionType
  5083. };
  5084. });
  5085. }
  5086. }
  5087. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  5088. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  5089. _fetchData(url) {
  5090. return fetchData(url, true);
  5091. }
  5092. }
  5093. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  5094. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  5095. _createSVG(type) {
  5096. return document.createElementNS(SVG_NS, type);
  5097. }
  5098. }
  5099. exports.DOMSVGFactory = DOMSVGFactory;
  5100. class PageViewport {
  5101. constructor({
  5102. viewBox,
  5103. scale,
  5104. rotation,
  5105. offsetX = 0,
  5106. offsetY = 0,
  5107. dontFlip = false
  5108. }) {
  5109. this.viewBox = viewBox;
  5110. this.scale = scale;
  5111. this.rotation = rotation;
  5112. this.offsetX = offsetX;
  5113. this.offsetY = offsetY;
  5114. const centerX = (viewBox[2] + viewBox[0]) / 2;
  5115. const centerY = (viewBox[3] + viewBox[1]) / 2;
  5116. let rotateA, rotateB, rotateC, rotateD;
  5117. rotation %= 360;
  5118. if (rotation < 0) {
  5119. rotation += 360;
  5120. }
  5121. switch (rotation) {
  5122. case 180:
  5123. rotateA = -1;
  5124. rotateB = 0;
  5125. rotateC = 0;
  5126. rotateD = 1;
  5127. break;
  5128. case 90:
  5129. rotateA = 0;
  5130. rotateB = 1;
  5131. rotateC = 1;
  5132. rotateD = 0;
  5133. break;
  5134. case 270:
  5135. rotateA = 0;
  5136. rotateB = -1;
  5137. rotateC = -1;
  5138. rotateD = 0;
  5139. break;
  5140. case 0:
  5141. rotateA = 1;
  5142. rotateB = 0;
  5143. rotateC = 0;
  5144. rotateD = -1;
  5145. break;
  5146. default:
  5147. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  5148. }
  5149. if (dontFlip) {
  5150. rotateC = -rotateC;
  5151. rotateD = -rotateD;
  5152. }
  5153. let offsetCanvasX, offsetCanvasY;
  5154. let width, height;
  5155. if (rotateA === 0) {
  5156. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  5157. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  5158. width = (viewBox[3] - viewBox[1]) * scale;
  5159. height = (viewBox[2] - viewBox[0]) * scale;
  5160. } else {
  5161. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  5162. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  5163. width = (viewBox[2] - viewBox[0]) * scale;
  5164. height = (viewBox[3] - viewBox[1]) * scale;
  5165. }
  5166. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  5167. this.width = width;
  5168. this.height = height;
  5169. }
  5170. get rawDims() {
  5171. const {
  5172. viewBox
  5173. } = this;
  5174. return (0, _util.shadow)(this, "rawDims", {
  5175. pageWidth: viewBox[2] - viewBox[0],
  5176. pageHeight: viewBox[3] - viewBox[1],
  5177. pageX: viewBox[0],
  5178. pageY: viewBox[1]
  5179. });
  5180. }
  5181. clone({
  5182. scale = this.scale,
  5183. rotation = this.rotation,
  5184. offsetX = this.offsetX,
  5185. offsetY = this.offsetY,
  5186. dontFlip = false
  5187. } = {}) {
  5188. return new PageViewport({
  5189. viewBox: this.viewBox.slice(),
  5190. scale,
  5191. rotation,
  5192. offsetX,
  5193. offsetY,
  5194. dontFlip
  5195. });
  5196. }
  5197. convertToViewportPoint(x, y) {
  5198. return _util.Util.applyTransform([x, y], this.transform);
  5199. }
  5200. convertToViewportRectangle(rect) {
  5201. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  5202. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  5203. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  5204. }
  5205. convertToPdfPoint(x, y) {
  5206. return _util.Util.applyInverseTransform([x, y], this.transform);
  5207. }
  5208. }
  5209. exports.PageViewport = PageViewport;
  5210. class RenderingCancelledException extends _util.BaseException {
  5211. constructor(msg, extraDelay = 0) {
  5212. super(msg, "RenderingCancelledException");
  5213. this.extraDelay = extraDelay;
  5214. }
  5215. }
  5216. exports.RenderingCancelledException = RenderingCancelledException;
  5217. function isDataScheme(url) {
  5218. const ii = url.length;
  5219. let i = 0;
  5220. while (i < ii && url[i].trim() === "") {
  5221. i++;
  5222. }
  5223. return url.substring(i, i + 5).toLowerCase() === "data:";
  5224. }
  5225. function isPdfFile(filename) {
  5226. return typeof filename === "string" && /\.pdf$/i.test(filename);
  5227. }
  5228. function getFilenameFromUrl(url, onlyStripPath = false) {
  5229. if (!onlyStripPath) {
  5230. [url] = url.split(/[#?]/, 1);
  5231. }
  5232. return url.substring(url.lastIndexOf("/") + 1);
  5233. }
  5234. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  5235. if (typeof url !== "string") {
  5236. return defaultFilename;
  5237. }
  5238. if (isDataScheme(url)) {
  5239. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  5240. return defaultFilename;
  5241. }
  5242. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  5243. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  5244. const splitURI = reURI.exec(url);
  5245. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  5246. if (suggestedFilename) {
  5247. suggestedFilename = suggestedFilename[0];
  5248. if (suggestedFilename.includes("%")) {
  5249. try {
  5250. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  5251. } catch {}
  5252. }
  5253. }
  5254. return suggestedFilename || defaultFilename;
  5255. }
  5256. class StatTimer {
  5257. started = Object.create(null);
  5258. times = [];
  5259. time(name) {
  5260. if (name in this.started) {
  5261. (0, _util.warn)(`Timer is already running for ${name}`);
  5262. }
  5263. this.started[name] = Date.now();
  5264. }
  5265. timeEnd(name) {
  5266. if (!(name in this.started)) {
  5267. (0, _util.warn)(`Timer has not been started for ${name}`);
  5268. }
  5269. this.times.push({
  5270. name,
  5271. start: this.started[name],
  5272. end: Date.now()
  5273. });
  5274. delete this.started[name];
  5275. }
  5276. toString() {
  5277. const outBuf = [];
  5278. let longest = 0;
  5279. for (const {
  5280. name
  5281. } of this.times) {
  5282. longest = Math.max(name.length, longest);
  5283. }
  5284. for (const {
  5285. name,
  5286. start,
  5287. end
  5288. } of this.times) {
  5289. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  5290. }
  5291. return outBuf.join("");
  5292. }
  5293. }
  5294. exports.StatTimer = StatTimer;
  5295. function isValidFetchUrl(url, baseUrl) {
  5296. try {
  5297. const {
  5298. protocol
  5299. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  5300. return protocol === "http:" || protocol === "https:";
  5301. } catch {
  5302. return false;
  5303. }
  5304. }
  5305. function loadScript(src, removeScriptElement = false) {
  5306. return new Promise((resolve, reject) => {
  5307. const script = document.createElement("script");
  5308. script.src = src;
  5309. script.onload = function (evt) {
  5310. if (removeScriptElement) {
  5311. script.remove();
  5312. }
  5313. resolve(evt);
  5314. };
  5315. script.onerror = function () {
  5316. reject(new Error(`Cannot load script at: ${script.src}`));
  5317. };
  5318. (document.head || document.documentElement).append(script);
  5319. });
  5320. }
  5321. function deprecated(details) {
  5322. console.log("Deprecated API usage: " + details);
  5323. }
  5324. let pdfDateStringRegex;
  5325. class PDFDateString {
  5326. static toDateObject(input) {
  5327. if (!input || typeof input !== "string") {
  5328. return null;
  5329. }
  5330. pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  5331. const matches = pdfDateStringRegex.exec(input);
  5332. if (!matches) {
  5333. return null;
  5334. }
  5335. const year = parseInt(matches[1], 10);
  5336. let month = parseInt(matches[2], 10);
  5337. month = month >= 1 && month <= 12 ? month - 1 : 0;
  5338. let day = parseInt(matches[3], 10);
  5339. day = day >= 1 && day <= 31 ? day : 1;
  5340. let hour = parseInt(matches[4], 10);
  5341. hour = hour >= 0 && hour <= 23 ? hour : 0;
  5342. let minute = parseInt(matches[5], 10);
  5343. minute = minute >= 0 && minute <= 59 ? minute : 0;
  5344. let second = parseInt(matches[6], 10);
  5345. second = second >= 0 && second <= 59 ? second : 0;
  5346. const universalTimeRelation = matches[7] || "Z";
  5347. let offsetHour = parseInt(matches[8], 10);
  5348. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  5349. let offsetMinute = parseInt(matches[9], 10) || 0;
  5350. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  5351. if (universalTimeRelation === "-") {
  5352. hour += offsetHour;
  5353. minute += offsetMinute;
  5354. } else if (universalTimeRelation === "+") {
  5355. hour -= offsetHour;
  5356. minute -= offsetMinute;
  5357. }
  5358. return new Date(Date.UTC(year, month, day, hour, minute, second));
  5359. }
  5360. }
  5361. exports.PDFDateString = PDFDateString;
  5362. function getXfaPageViewport(xfaPage, {
  5363. scale = 1,
  5364. rotation = 0
  5365. }) {
  5366. const {
  5367. width,
  5368. height
  5369. } = xfaPage.attributes.style;
  5370. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  5371. return new PageViewport({
  5372. viewBox,
  5373. scale,
  5374. rotation
  5375. });
  5376. }
  5377. function getRGB(color) {
  5378. if (color.startsWith("#")) {
  5379. const colorRGB = parseInt(color.slice(1), 16);
  5380. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  5381. }
  5382. if (color.startsWith("rgb(")) {
  5383. return color.slice(4, -1).split(",").map(x => parseInt(x));
  5384. }
  5385. if (color.startsWith("rgba(")) {
  5386. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  5387. }
  5388. (0, _util.warn)(`Not a valid color format: "${color}"`);
  5389. return [0, 0, 0];
  5390. }
  5391. function getColorValues(colors) {
  5392. const span = document.createElement("span");
  5393. span.style.visibility = "hidden";
  5394. document.body.append(span);
  5395. for (const name of colors.keys()) {
  5396. span.style.color = name;
  5397. const computedColor = window.getComputedStyle(span).color;
  5398. colors.set(name, getRGB(computedColor));
  5399. }
  5400. span.remove();
  5401. }
  5402. function getCurrentTransform(ctx) {
  5403. const {
  5404. a,
  5405. b,
  5406. c,
  5407. d,
  5408. e,
  5409. f
  5410. } = ctx.getTransform();
  5411. return [a, b, c, d, e, f];
  5412. }
  5413. function getCurrentTransformInverse(ctx) {
  5414. const {
  5415. a,
  5416. b,
  5417. c,
  5418. d,
  5419. e,
  5420. f
  5421. } = ctx.getTransform().invertSelf();
  5422. return [a, b, c, d, e, f];
  5423. }
  5424. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  5425. if (viewport instanceof PageViewport) {
  5426. const {
  5427. pageWidth,
  5428. pageHeight
  5429. } = viewport.rawDims;
  5430. const {
  5431. style
  5432. } = div;
  5433. const useRound = _util.FeatureTest.isCSSRoundSupported;
  5434. const w = `var(--scale-factor) * ${pageWidth}px`,
  5435. h = `var(--scale-factor) * ${pageHeight}px`;
  5436. const widthStr = useRound ? `round(${w}, 1px)` : `calc(${w})`,
  5437. heightStr = useRound ? `round(${h}, 1px)` : `calc(${h})`;
  5438. if (!mustFlip || viewport.rotation % 180 === 0) {
  5439. style.width = widthStr;
  5440. style.height = heightStr;
  5441. } else {
  5442. style.width = heightStr;
  5443. style.height = widthStr;
  5444. }
  5445. }
  5446. if (mustRotate) {
  5447. div.setAttribute("data-main-rotation", viewport.rotation);
  5448. }
  5449. }
  5450. /***/ }),
  5451. /* 7 */
  5452. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5453. Object.defineProperty(exports, "__esModule", ({
  5454. value: true
  5455. }));
  5456. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseFilterFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  5457. var _util = __w_pdfjs_require__(1);
  5458. class BaseFilterFactory {
  5459. constructor() {
  5460. if (this.constructor === BaseFilterFactory) {
  5461. (0, _util.unreachable)("Cannot initialize BaseFilterFactory.");
  5462. }
  5463. }
  5464. addFilter(maps) {
  5465. return "none";
  5466. }
  5467. addHCMFilter(fgColor, bgColor) {
  5468. return "none";
  5469. }
  5470. addHighlightHCMFilter(fgColor, bgColor, newFgColor, newBgColor) {
  5471. return "none";
  5472. }
  5473. destroy(keepHCM = false) {}
  5474. }
  5475. exports.BaseFilterFactory = BaseFilterFactory;
  5476. class BaseCanvasFactory {
  5477. constructor() {
  5478. if (this.constructor === BaseCanvasFactory) {
  5479. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  5480. }
  5481. }
  5482. create(width, height) {
  5483. if (width <= 0 || height <= 0) {
  5484. throw new Error("Invalid canvas size");
  5485. }
  5486. const canvas = this._createCanvas(width, height);
  5487. return {
  5488. canvas,
  5489. context: canvas.getContext("2d")
  5490. };
  5491. }
  5492. reset(canvasAndContext, width, height) {
  5493. if (!canvasAndContext.canvas) {
  5494. throw new Error("Canvas is not specified");
  5495. }
  5496. if (width <= 0 || height <= 0) {
  5497. throw new Error("Invalid canvas size");
  5498. }
  5499. canvasAndContext.canvas.width = width;
  5500. canvasAndContext.canvas.height = height;
  5501. }
  5502. destroy(canvasAndContext) {
  5503. if (!canvasAndContext.canvas) {
  5504. throw new Error("Canvas is not specified");
  5505. }
  5506. canvasAndContext.canvas.width = 0;
  5507. canvasAndContext.canvas.height = 0;
  5508. canvasAndContext.canvas = null;
  5509. canvasAndContext.context = null;
  5510. }
  5511. _createCanvas(width, height) {
  5512. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  5513. }
  5514. }
  5515. exports.BaseCanvasFactory = BaseCanvasFactory;
  5516. class BaseCMapReaderFactory {
  5517. constructor({
  5518. baseUrl = null,
  5519. isCompressed = true
  5520. }) {
  5521. if (this.constructor === BaseCMapReaderFactory) {
  5522. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  5523. }
  5524. this.baseUrl = baseUrl;
  5525. this.isCompressed = isCompressed;
  5526. }
  5527. async fetch({
  5528. name
  5529. }) {
  5530. if (!this.baseUrl) {
  5531. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  5532. }
  5533. if (!name) {
  5534. throw new Error("CMap name must be specified.");
  5535. }
  5536. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  5537. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  5538. return this._fetchData(url, compressionType).catch(reason => {
  5539. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  5540. });
  5541. }
  5542. _fetchData(url, compressionType) {
  5543. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  5544. }
  5545. }
  5546. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  5547. class BaseStandardFontDataFactory {
  5548. constructor({
  5549. baseUrl = null
  5550. }) {
  5551. if (this.constructor === BaseStandardFontDataFactory) {
  5552. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  5553. }
  5554. this.baseUrl = baseUrl;
  5555. }
  5556. async fetch({
  5557. filename
  5558. }) {
  5559. if (!this.baseUrl) {
  5560. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  5561. }
  5562. if (!filename) {
  5563. throw new Error("Font filename must be specified.");
  5564. }
  5565. const url = `${this.baseUrl}${filename}`;
  5566. return this._fetchData(url).catch(reason => {
  5567. throw new Error(`Unable to load font data at: ${url}`);
  5568. });
  5569. }
  5570. _fetchData(url) {
  5571. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  5572. }
  5573. }
  5574. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  5575. class BaseSVGFactory {
  5576. constructor() {
  5577. if (this.constructor === BaseSVGFactory) {
  5578. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  5579. }
  5580. }
  5581. create(width, height, skipDimensions = false) {
  5582. if (width <= 0 || height <= 0) {
  5583. throw new Error("Invalid SVG dimensions");
  5584. }
  5585. const svg = this._createSVG("svg:svg");
  5586. svg.setAttribute("version", "1.1");
  5587. if (!skipDimensions) {
  5588. svg.setAttribute("width", `${width}px`);
  5589. svg.setAttribute("height", `${height}px`);
  5590. }
  5591. svg.setAttribute("preserveAspectRatio", "none");
  5592. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  5593. return svg;
  5594. }
  5595. createElement(type) {
  5596. if (typeof type !== "string") {
  5597. throw new Error("Invalid SVG element type");
  5598. }
  5599. return this._createSVG(type);
  5600. }
  5601. _createSVG(type) {
  5602. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  5603. }
  5604. }
  5605. exports.BaseSVGFactory = BaseSVGFactory;
  5606. /***/ }),
  5607. /* 8 */
  5608. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5609. Object.defineProperty(exports, "__esModule", ({
  5610. value: true
  5611. }));
  5612. exports.MurmurHash3_64 = void 0;
  5613. var _util = __w_pdfjs_require__(1);
  5614. const SEED = 0xc3d2e1f0;
  5615. const MASK_HIGH = 0xffff0000;
  5616. const MASK_LOW = 0xffff;
  5617. class MurmurHash3_64 {
  5618. constructor(seed) {
  5619. this.h1 = seed ? seed & 0xffffffff : SEED;
  5620. this.h2 = seed ? seed & 0xffffffff : SEED;
  5621. }
  5622. update(input) {
  5623. let data, length;
  5624. if (typeof input === "string") {
  5625. data = new Uint8Array(input.length * 2);
  5626. length = 0;
  5627. for (let i = 0, ii = input.length; i < ii; i++) {
  5628. const code = input.charCodeAt(i);
  5629. if (code <= 0xff) {
  5630. data[length++] = code;
  5631. } else {
  5632. data[length++] = code >>> 8;
  5633. data[length++] = code & 0xff;
  5634. }
  5635. }
  5636. } else if ((0, _util.isArrayBuffer)(input)) {
  5637. data = input.slice();
  5638. length = data.byteLength;
  5639. } else {
  5640. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  5641. }
  5642. const blockCounts = length >> 2;
  5643. const tailLength = length - blockCounts * 4;
  5644. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  5645. let k1 = 0,
  5646. k2 = 0;
  5647. let h1 = this.h1,
  5648. h2 = this.h2;
  5649. const C1 = 0xcc9e2d51,
  5650. C2 = 0x1b873593;
  5651. const C1_LOW = C1 & MASK_LOW,
  5652. C2_LOW = C2 & MASK_LOW;
  5653. for (let i = 0; i < blockCounts; i++) {
  5654. if (i & 1) {
  5655. k1 = dataUint32[i];
  5656. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  5657. k1 = k1 << 15 | k1 >>> 17;
  5658. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  5659. h1 ^= k1;
  5660. h1 = h1 << 13 | h1 >>> 19;
  5661. h1 = h1 * 5 + 0xe6546b64;
  5662. } else {
  5663. k2 = dataUint32[i];
  5664. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  5665. k2 = k2 << 15 | k2 >>> 17;
  5666. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  5667. h2 ^= k2;
  5668. h2 = h2 << 13 | h2 >>> 19;
  5669. h2 = h2 * 5 + 0xe6546b64;
  5670. }
  5671. }
  5672. k1 = 0;
  5673. switch (tailLength) {
  5674. case 3:
  5675. k1 ^= data[blockCounts * 4 + 2] << 16;
  5676. case 2:
  5677. k1 ^= data[blockCounts * 4 + 1] << 8;
  5678. case 1:
  5679. k1 ^= data[blockCounts * 4];
  5680. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  5681. k1 = k1 << 15 | k1 >>> 17;
  5682. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  5683. if (blockCounts & 1) {
  5684. h1 ^= k1;
  5685. } else {
  5686. h2 ^= k1;
  5687. }
  5688. }
  5689. this.h1 = h1;
  5690. this.h2 = h2;
  5691. }
  5692. hexdigest() {
  5693. let h1 = this.h1,
  5694. h2 = this.h2;
  5695. h1 ^= h2 >>> 1;
  5696. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  5697. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  5698. h1 ^= h2 >>> 1;
  5699. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  5700. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  5701. h1 ^= h2 >>> 1;
  5702. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  5703. }
  5704. }
  5705. exports.MurmurHash3_64 = MurmurHash3_64;
  5706. /***/ }),
  5707. /* 9 */
  5708. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5709. Object.defineProperty(exports, "__esModule", ({
  5710. value: true
  5711. }));
  5712. exports.FontLoader = exports.FontFaceObject = void 0;
  5713. var _util = __w_pdfjs_require__(1);
  5714. class FontLoader {
  5715. #systemFonts = new Set();
  5716. constructor({
  5717. ownerDocument = globalThis.document,
  5718. styleElement = null
  5719. }) {
  5720. this._document = ownerDocument;
  5721. this.nativeFontFaces = new Set();
  5722. this.styleElement = null;
  5723. this.loadingRequests = [];
  5724. this.loadTestFontId = 0;
  5725. }
  5726. addNativeFontFace(nativeFontFace) {
  5727. this.nativeFontFaces.add(nativeFontFace);
  5728. this._document.fonts.add(nativeFontFace);
  5729. }
  5730. removeNativeFontFace(nativeFontFace) {
  5731. this.nativeFontFaces.delete(nativeFontFace);
  5732. this._document.fonts.delete(nativeFontFace);
  5733. }
  5734. insertRule(rule) {
  5735. if (!this.styleElement) {
  5736. this.styleElement = this._document.createElement("style");
  5737. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  5738. }
  5739. const styleSheet = this.styleElement.sheet;
  5740. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5741. }
  5742. clear() {
  5743. for (const nativeFontFace of this.nativeFontFaces) {
  5744. this._document.fonts.delete(nativeFontFace);
  5745. }
  5746. this.nativeFontFaces.clear();
  5747. this.#systemFonts.clear();
  5748. if (this.styleElement) {
  5749. this.styleElement.remove();
  5750. this.styleElement = null;
  5751. }
  5752. }
  5753. async loadSystemFont(info) {
  5754. if (!info || this.#systemFonts.has(info.loadedName)) {
  5755. return;
  5756. }
  5757. (0, _util.assert)(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
  5758. if (this.isFontLoadingAPISupported) {
  5759. const {
  5760. loadedName,
  5761. src,
  5762. style
  5763. } = info;
  5764. const fontFace = new FontFace(loadedName, src, style);
  5765. this.addNativeFontFace(fontFace);
  5766. try {
  5767. await fontFace.load();
  5768. this.#systemFonts.add(loadedName);
  5769. } catch {
  5770. (0, _util.warn)(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
  5771. this.removeNativeFontFace(fontFace);
  5772. }
  5773. return;
  5774. }
  5775. (0, _util.unreachable)("Not implemented: loadSystemFont without the Font Loading API.");
  5776. }
  5777. async bind(font) {
  5778. if (font.attached || font.missingFile && !font.systemFontInfo) {
  5779. return;
  5780. }
  5781. font.attached = true;
  5782. if (font.systemFontInfo) {
  5783. await this.loadSystemFont(font.systemFontInfo);
  5784. return;
  5785. }
  5786. if (this.isFontLoadingAPISupported) {
  5787. const nativeFontFace = font.createNativeFontFace();
  5788. if (nativeFontFace) {
  5789. this.addNativeFontFace(nativeFontFace);
  5790. try {
  5791. await nativeFontFace.loaded;
  5792. } catch (ex) {
  5793. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  5794. font.disableFontFace = true;
  5795. throw ex;
  5796. }
  5797. }
  5798. return;
  5799. }
  5800. const rule = font.createFontFaceRule();
  5801. if (rule) {
  5802. this.insertRule(rule);
  5803. if (this.isSyncFontLoadingSupported) {
  5804. return;
  5805. }
  5806. await new Promise(resolve => {
  5807. const request = this._queueLoadingCallback(resolve);
  5808. this._prepareFontLoadEvent(font, request);
  5809. });
  5810. }
  5811. }
  5812. get isFontLoadingAPISupported() {
  5813. const hasFonts = !!this._document?.fonts;
  5814. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  5815. }
  5816. get isSyncFontLoadingSupported() {
  5817. let supported = false;
  5818. if (_util.isNodeJS) {
  5819. supported = true;
  5820. } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  5821. supported = true;
  5822. }
  5823. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  5824. }
  5825. _queueLoadingCallback(callback) {
  5826. function completeRequest() {
  5827. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  5828. request.done = true;
  5829. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  5830. const otherRequest = loadingRequests.shift();
  5831. setTimeout(otherRequest.callback, 0);
  5832. }
  5833. }
  5834. const {
  5835. loadingRequests
  5836. } = this;
  5837. const request = {
  5838. done: false,
  5839. complete: completeRequest,
  5840. callback
  5841. };
  5842. loadingRequests.push(request);
  5843. return request;
  5844. }
  5845. get _loadTestFont() {
  5846. const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  5847. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  5848. }
  5849. _prepareFontLoadEvent(font, request) {
  5850. function int32(data, offset) {
  5851. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  5852. }
  5853. function spliceString(s, offset, remove, insert) {
  5854. const chunk1 = s.substring(0, offset);
  5855. const chunk2 = s.substring(offset + remove);
  5856. return chunk1 + insert + chunk2;
  5857. }
  5858. let i, ii;
  5859. const canvas = this._document.createElement("canvas");
  5860. canvas.width = 1;
  5861. canvas.height = 1;
  5862. const ctx = canvas.getContext("2d");
  5863. let called = 0;
  5864. function isFontReady(name, callback) {
  5865. if (++called > 30) {
  5866. (0, _util.warn)("Load test font never loaded.");
  5867. callback();
  5868. return;
  5869. }
  5870. ctx.font = "30px " + name;
  5871. ctx.fillText(".", 0, 20);
  5872. const imageData = ctx.getImageData(0, 0, 1, 1);
  5873. if (imageData.data[3] > 0) {
  5874. callback();
  5875. return;
  5876. }
  5877. setTimeout(isFontReady.bind(null, name, callback));
  5878. }
  5879. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  5880. let data = this._loadTestFont;
  5881. const COMMENT_OFFSET = 976;
  5882. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  5883. const CFF_CHECKSUM_OFFSET = 16;
  5884. const XXXX_VALUE = 0x58585858;
  5885. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5886. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5887. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  5888. }
  5889. if (i < loadTestFontId.length) {
  5890. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  5891. }
  5892. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  5893. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  5894. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  5895. this.insertRule(rule);
  5896. const div = this._document.createElement("div");
  5897. div.style.visibility = "hidden";
  5898. div.style.width = div.style.height = "10px";
  5899. div.style.position = "absolute";
  5900. div.style.top = div.style.left = "0px";
  5901. for (const name of [font.loadedName, loadTestFontId]) {
  5902. const span = this._document.createElement("span");
  5903. span.textContent = "Hi";
  5904. span.style.fontFamily = name;
  5905. div.append(span);
  5906. }
  5907. this._document.body.append(div);
  5908. isFontReady(loadTestFontId, () => {
  5909. div.remove();
  5910. request.complete();
  5911. });
  5912. }
  5913. }
  5914. exports.FontLoader = FontLoader;
  5915. class FontFaceObject {
  5916. constructor(translatedData, {
  5917. isEvalSupported = true,
  5918. disableFontFace = false,
  5919. ignoreErrors = false,
  5920. inspectFont = null
  5921. }) {
  5922. this.compiledGlyphs = Object.create(null);
  5923. for (const i in translatedData) {
  5924. this[i] = translatedData[i];
  5925. }
  5926. this.isEvalSupported = isEvalSupported !== false;
  5927. this.disableFontFace = disableFontFace === true;
  5928. this.ignoreErrors = ignoreErrors === true;
  5929. this._inspectFont = inspectFont;
  5930. }
  5931. createNativeFontFace() {
  5932. if (!this.data || this.disableFontFace) {
  5933. return null;
  5934. }
  5935. let nativeFontFace;
  5936. if (!this.cssFontInfo) {
  5937. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5938. } else {
  5939. const css = {
  5940. weight: this.cssFontInfo.fontWeight
  5941. };
  5942. if (this.cssFontInfo.italicAngle) {
  5943. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  5944. }
  5945. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  5946. }
  5947. this._inspectFont?.(this);
  5948. return nativeFontFace;
  5949. }
  5950. createFontFaceRule() {
  5951. if (!this.data || this.disableFontFace) {
  5952. return null;
  5953. }
  5954. const data = (0, _util.bytesToString)(this.data);
  5955. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  5956. let rule;
  5957. if (!this.cssFontInfo) {
  5958. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  5959. } else {
  5960. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  5961. if (this.cssFontInfo.italicAngle) {
  5962. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  5963. }
  5964. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  5965. }
  5966. this._inspectFont?.(this, url);
  5967. return rule;
  5968. }
  5969. getPathGenerator(objs, character) {
  5970. if (this.compiledGlyphs[character] !== undefined) {
  5971. return this.compiledGlyphs[character];
  5972. }
  5973. let cmds;
  5974. try {
  5975. cmds = objs.get(this.loadedName + "_path_" + character);
  5976. } catch (ex) {
  5977. if (!this.ignoreErrors) {
  5978. throw ex;
  5979. }
  5980. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  5981. return this.compiledGlyphs[character] = function (c, size) {};
  5982. }
  5983. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  5984. const jsBuf = [];
  5985. for (const current of cmds) {
  5986. const args = current.args !== undefined ? current.args.join(",") : "";
  5987. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  5988. }
  5989. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  5990. }
  5991. return this.compiledGlyphs[character] = function (c, size) {
  5992. for (const current of cmds) {
  5993. if (current.cmd === "scale") {
  5994. current.args = [size, -size];
  5995. }
  5996. c[current.cmd].apply(c, current.args);
  5997. }
  5998. };
  5999. }
  6000. }
  6001. exports.FontFaceObject = FontFaceObject;
  6002. /***/ }),
  6003. /* 10 */
  6004. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6005. Object.defineProperty(exports, "__esModule", ({
  6006. value: true
  6007. }));
  6008. exports.NodeStandardFontDataFactory = exports.NodeFilterFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  6009. var _base_factory = __w_pdfjs_require__(7);
  6010. var _util = __w_pdfjs_require__(1);
  6011. ;
  6012. ;
  6013. const fetchData = function (url) {
  6014. return new Promise((resolve, reject) => {
  6015. const fs = require("fs");
  6016. fs.readFile(url, (error, data) => {
  6017. if (error || !data) {
  6018. reject(new Error(error));
  6019. return;
  6020. }
  6021. resolve(new Uint8Array(data));
  6022. });
  6023. });
  6024. };
  6025. class NodeFilterFactory extends _base_factory.BaseFilterFactory {}
  6026. exports.NodeFilterFactory = NodeFilterFactory;
  6027. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  6028. _createCanvas(width, height) {
  6029. const Canvas = require("canvas");
  6030. return Canvas.createCanvas(width, height);
  6031. }
  6032. }
  6033. exports.NodeCanvasFactory = NodeCanvasFactory;
  6034. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  6035. _fetchData(url, compressionType) {
  6036. return fetchData(url).then(data => {
  6037. return {
  6038. cMapData: data,
  6039. compressionType
  6040. };
  6041. });
  6042. }
  6043. }
  6044. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  6045. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  6046. _fetchData(url) {
  6047. return fetchData(url);
  6048. }
  6049. }
  6050. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  6051. /***/ }),
  6052. /* 11 */
  6053. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  6054. Object.defineProperty(exports, "__esModule", ({
  6055. value: true
  6056. }));
  6057. exports.CanvasGraphics = void 0;
  6058. var _util = __w_pdfjs_require__(1);
  6059. var _display_utils = __w_pdfjs_require__(6);
  6060. var _pattern_helper = __w_pdfjs_require__(12);
  6061. var _image_utils = __w_pdfjs_require__(13);
  6062. const MIN_FONT_SIZE = 16;
  6063. const MAX_FONT_SIZE = 100;
  6064. const MAX_GROUP_SIZE = 4096;
  6065. const EXECUTION_TIME = 15;
  6066. const EXECUTION_STEPS = 10;
  6067. const MAX_SIZE_TO_COMPILE = 1000;
  6068. const FULL_CHUNK_HEIGHT = 16;
  6069. function mirrorContextOperations(ctx, destCtx) {
  6070. if (ctx._removeMirroring) {
  6071. throw new Error("Context is already forwarding operations.");
  6072. }
  6073. ctx.__originalSave = ctx.save;
  6074. ctx.__originalRestore = ctx.restore;
  6075. ctx.__originalRotate = ctx.rotate;
  6076. ctx.__originalScale = ctx.scale;
  6077. ctx.__originalTranslate = ctx.translate;
  6078. ctx.__originalTransform = ctx.transform;
  6079. ctx.__originalSetTransform = ctx.setTransform;
  6080. ctx.__originalResetTransform = ctx.resetTransform;
  6081. ctx.__originalClip = ctx.clip;
  6082. ctx.__originalMoveTo = ctx.moveTo;
  6083. ctx.__originalLineTo = ctx.lineTo;
  6084. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  6085. ctx.__originalRect = ctx.rect;
  6086. ctx.__originalClosePath = ctx.closePath;
  6087. ctx.__originalBeginPath = ctx.beginPath;
  6088. ctx._removeMirroring = () => {
  6089. ctx.save = ctx.__originalSave;
  6090. ctx.restore = ctx.__originalRestore;
  6091. ctx.rotate = ctx.__originalRotate;
  6092. ctx.scale = ctx.__originalScale;
  6093. ctx.translate = ctx.__originalTranslate;
  6094. ctx.transform = ctx.__originalTransform;
  6095. ctx.setTransform = ctx.__originalSetTransform;
  6096. ctx.resetTransform = ctx.__originalResetTransform;
  6097. ctx.clip = ctx.__originalClip;
  6098. ctx.moveTo = ctx.__originalMoveTo;
  6099. ctx.lineTo = ctx.__originalLineTo;
  6100. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  6101. ctx.rect = ctx.__originalRect;
  6102. ctx.closePath = ctx.__originalClosePath;
  6103. ctx.beginPath = ctx.__originalBeginPath;
  6104. delete ctx._removeMirroring;
  6105. };
  6106. ctx.save = function ctxSave() {
  6107. destCtx.save();
  6108. this.__originalSave();
  6109. };
  6110. ctx.restore = function ctxRestore() {
  6111. destCtx.restore();
  6112. this.__originalRestore();
  6113. };
  6114. ctx.translate = function ctxTranslate(x, y) {
  6115. destCtx.translate(x, y);
  6116. this.__originalTranslate(x, y);
  6117. };
  6118. ctx.scale = function ctxScale(x, y) {
  6119. destCtx.scale(x, y);
  6120. this.__originalScale(x, y);
  6121. };
  6122. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6123. destCtx.transform(a, b, c, d, e, f);
  6124. this.__originalTransform(a, b, c, d, e, f);
  6125. };
  6126. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6127. destCtx.setTransform(a, b, c, d, e, f);
  6128. this.__originalSetTransform(a, b, c, d, e, f);
  6129. };
  6130. ctx.resetTransform = function ctxResetTransform() {
  6131. destCtx.resetTransform();
  6132. this.__originalResetTransform();
  6133. };
  6134. ctx.rotate = function ctxRotate(angle) {
  6135. destCtx.rotate(angle);
  6136. this.__originalRotate(angle);
  6137. };
  6138. ctx.clip = function ctxRotate(rule) {
  6139. destCtx.clip(rule);
  6140. this.__originalClip(rule);
  6141. };
  6142. ctx.moveTo = function (x, y) {
  6143. destCtx.moveTo(x, y);
  6144. this.__originalMoveTo(x, y);
  6145. };
  6146. ctx.lineTo = function (x, y) {
  6147. destCtx.lineTo(x, y);
  6148. this.__originalLineTo(x, y);
  6149. };
  6150. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  6151. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  6152. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  6153. };
  6154. ctx.rect = function (x, y, width, height) {
  6155. destCtx.rect(x, y, width, height);
  6156. this.__originalRect(x, y, width, height);
  6157. };
  6158. ctx.closePath = function () {
  6159. destCtx.closePath();
  6160. this.__originalClosePath();
  6161. };
  6162. ctx.beginPath = function () {
  6163. destCtx.beginPath();
  6164. this.__originalBeginPath();
  6165. };
  6166. }
  6167. class CachedCanvases {
  6168. constructor(canvasFactory) {
  6169. this.canvasFactory = canvasFactory;
  6170. this.cache = Object.create(null);
  6171. }
  6172. getCanvas(id, width, height) {
  6173. let canvasEntry;
  6174. if (this.cache[id] !== undefined) {
  6175. canvasEntry = this.cache[id];
  6176. this.canvasFactory.reset(canvasEntry, width, height);
  6177. } else {
  6178. canvasEntry = this.canvasFactory.create(width, height);
  6179. this.cache[id] = canvasEntry;
  6180. }
  6181. return canvasEntry;
  6182. }
  6183. delete(id) {
  6184. delete this.cache[id];
  6185. }
  6186. clear() {
  6187. for (const id in this.cache) {
  6188. const canvasEntry = this.cache[id];
  6189. this.canvasFactory.destroy(canvasEntry);
  6190. delete this.cache[id];
  6191. }
  6192. }
  6193. }
  6194. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  6195. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  6196. if (b === 0 && c === 0) {
  6197. const tlX = destX * a + tx;
  6198. const rTlX = Math.round(tlX);
  6199. const tlY = destY * d + ty;
  6200. const rTlY = Math.round(tlY);
  6201. const brX = (destX + destW) * a + tx;
  6202. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  6203. const brY = (destY + destH) * d + ty;
  6204. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  6205. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  6206. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  6207. ctx.setTransform(a, b, c, d, tx, ty);
  6208. return [rWidth, rHeight];
  6209. }
  6210. if (a === 0 && d === 0) {
  6211. const tlX = destY * c + tx;
  6212. const rTlX = Math.round(tlX);
  6213. const tlY = destX * b + ty;
  6214. const rTlY = Math.round(tlY);
  6215. const brX = (destY + destH) * c + tx;
  6216. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  6217. const brY = (destX + destW) * b + ty;
  6218. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  6219. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  6220. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  6221. ctx.setTransform(a, b, c, d, tx, ty);
  6222. return [rHeight, rWidth];
  6223. }
  6224. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  6225. const scaleX = Math.hypot(a, b);
  6226. const scaleY = Math.hypot(c, d);
  6227. return [scaleX * destW, scaleY * destH];
  6228. }
  6229. function compileType3Glyph(imgData) {
  6230. const {
  6231. width,
  6232. height
  6233. } = imgData;
  6234. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  6235. return null;
  6236. }
  6237. const POINT_TO_PROCESS_LIMIT = 1000;
  6238. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  6239. const width1 = width + 1;
  6240. let points = new Uint8Array(width1 * (height + 1));
  6241. let i, j, j0;
  6242. const lineSize = width + 7 & ~7;
  6243. let data = new Uint8Array(lineSize * height),
  6244. pos = 0;
  6245. for (const elem of imgData.data) {
  6246. let mask = 128;
  6247. while (mask > 0) {
  6248. data[pos++] = elem & mask ? 0 : 255;
  6249. mask >>= 1;
  6250. }
  6251. }
  6252. let count = 0;
  6253. pos = 0;
  6254. if (data[pos] !== 0) {
  6255. points[0] = 1;
  6256. ++count;
  6257. }
  6258. for (j = 1; j < width; j++) {
  6259. if (data[pos] !== data[pos + 1]) {
  6260. points[j] = data[pos] ? 2 : 1;
  6261. ++count;
  6262. }
  6263. pos++;
  6264. }
  6265. if (data[pos] !== 0) {
  6266. points[j] = 2;
  6267. ++count;
  6268. }
  6269. for (i = 1; i < height; i++) {
  6270. pos = i * lineSize;
  6271. j0 = i * width1;
  6272. if (data[pos - lineSize] !== data[pos]) {
  6273. points[j0] = data[pos] ? 1 : 8;
  6274. ++count;
  6275. }
  6276. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6277. for (j = 1; j < width; j++) {
  6278. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6279. if (POINT_TYPES[sum]) {
  6280. points[j0 + j] = POINT_TYPES[sum];
  6281. ++count;
  6282. }
  6283. pos++;
  6284. }
  6285. if (data[pos - lineSize] !== data[pos]) {
  6286. points[j0 + j] = data[pos] ? 2 : 4;
  6287. ++count;
  6288. }
  6289. if (count > POINT_TO_PROCESS_LIMIT) {
  6290. return null;
  6291. }
  6292. }
  6293. pos = lineSize * (height - 1);
  6294. j0 = i * width1;
  6295. if (data[pos] !== 0) {
  6296. points[j0] = 8;
  6297. ++count;
  6298. }
  6299. for (j = 1; j < width; j++) {
  6300. if (data[pos] !== data[pos + 1]) {
  6301. points[j0 + j] = data[pos] ? 4 : 8;
  6302. ++count;
  6303. }
  6304. pos++;
  6305. }
  6306. if (data[pos] !== 0) {
  6307. points[j0 + j] = 4;
  6308. ++count;
  6309. }
  6310. if (count > POINT_TO_PROCESS_LIMIT) {
  6311. return null;
  6312. }
  6313. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  6314. const path = new Path2D();
  6315. for (i = 0; count && i <= height; i++) {
  6316. let p = i * width1;
  6317. const end = p + width;
  6318. while (p < end && !points[p]) {
  6319. p++;
  6320. }
  6321. if (p === end) {
  6322. continue;
  6323. }
  6324. path.moveTo(p % width1, i);
  6325. const p0 = p;
  6326. let type = points[p];
  6327. do {
  6328. const step = steps[type];
  6329. do {
  6330. p += step;
  6331. } while (!points[p]);
  6332. const pp = points[p];
  6333. if (pp !== 5 && pp !== 10) {
  6334. type = pp;
  6335. points[p] = 0;
  6336. } else {
  6337. type = pp & 0x33 * type >> 4;
  6338. points[p] &= type >> 2 | type << 2;
  6339. }
  6340. path.lineTo(p % width1, p / width1 | 0);
  6341. if (!points[p]) {
  6342. --count;
  6343. }
  6344. } while (p0 !== p);
  6345. --i;
  6346. }
  6347. data = null;
  6348. points = null;
  6349. const drawOutline = function (c) {
  6350. c.save();
  6351. c.scale(1 / width, -1 / height);
  6352. c.translate(0, -height);
  6353. c.fill(path);
  6354. c.beginPath();
  6355. c.restore();
  6356. };
  6357. return drawOutline;
  6358. }
  6359. class CanvasExtraState {
  6360. constructor(width, height) {
  6361. this.alphaIsShape = false;
  6362. this.fontSize = 0;
  6363. this.fontSizeScale = 1;
  6364. this.textMatrix = _util.IDENTITY_MATRIX;
  6365. this.textMatrixScale = 1;
  6366. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  6367. this.leading = 0;
  6368. this.x = 0;
  6369. this.y = 0;
  6370. this.lineX = 0;
  6371. this.lineY = 0;
  6372. this.charSpacing = 0;
  6373. this.wordSpacing = 0;
  6374. this.textHScale = 1;
  6375. this.textRenderingMode = _util.TextRenderingMode.FILL;
  6376. this.textRise = 0;
  6377. this.fillColor = "#000000";
  6378. this.strokeColor = "#000000";
  6379. this.patternFill = false;
  6380. this.fillAlpha = 1;
  6381. this.strokeAlpha = 1;
  6382. this.lineWidth = 1;
  6383. this.activeSMask = null;
  6384. this.transferMaps = "none";
  6385. this.startNewPathAndClipBox([0, 0, width, height]);
  6386. }
  6387. clone() {
  6388. const clone = Object.create(this);
  6389. clone.clipBox = this.clipBox.slice();
  6390. return clone;
  6391. }
  6392. setCurrentPoint(x, y) {
  6393. this.x = x;
  6394. this.y = y;
  6395. }
  6396. updatePathMinMax(transform, x, y) {
  6397. [x, y] = _util.Util.applyTransform([x, y], transform);
  6398. this.minX = Math.min(this.minX, x);
  6399. this.minY = Math.min(this.minY, y);
  6400. this.maxX = Math.max(this.maxX, x);
  6401. this.maxY = Math.max(this.maxY, y);
  6402. }
  6403. updateRectMinMax(transform, rect) {
  6404. const p1 = _util.Util.applyTransform(rect, transform);
  6405. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  6406. this.minX = Math.min(this.minX, p1[0], p2[0]);
  6407. this.minY = Math.min(this.minY, p1[1], p2[1]);
  6408. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  6409. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  6410. }
  6411. updateScalingPathMinMax(transform, minMax) {
  6412. _util.Util.scaleMinMax(transform, minMax);
  6413. this.minX = Math.min(this.minX, minMax[0]);
  6414. this.maxX = Math.max(this.maxX, minMax[1]);
  6415. this.minY = Math.min(this.minY, minMax[2]);
  6416. this.maxY = Math.max(this.maxY, minMax[3]);
  6417. }
  6418. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  6419. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  6420. if (minMax) {
  6421. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  6422. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  6423. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  6424. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  6425. return;
  6426. }
  6427. this.updateRectMinMax(transform, box);
  6428. }
  6429. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  6430. const box = [this.minX, this.minY, this.maxX, this.maxY];
  6431. if (pathType === _pattern_helper.PathType.STROKE) {
  6432. if (!transform) {
  6433. (0, _util.unreachable)("Stroke bounding box must include transform.");
  6434. }
  6435. const scale = _util.Util.singularValueDecompose2dScale(transform);
  6436. const xStrokePad = scale[0] * this.lineWidth / 2;
  6437. const yStrokePad = scale[1] * this.lineWidth / 2;
  6438. box[0] -= xStrokePad;
  6439. box[1] -= yStrokePad;
  6440. box[2] += xStrokePad;
  6441. box[3] += yStrokePad;
  6442. }
  6443. return box;
  6444. }
  6445. updateClipFromPath() {
  6446. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  6447. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  6448. }
  6449. isEmptyClip() {
  6450. return this.minX === Infinity;
  6451. }
  6452. startNewPathAndClipBox(box) {
  6453. this.clipBox = box;
  6454. this.minX = Infinity;
  6455. this.minY = Infinity;
  6456. this.maxX = 0;
  6457. this.maxY = 0;
  6458. }
  6459. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  6460. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  6461. }
  6462. }
  6463. function putBinaryImageData(ctx, imgData) {
  6464. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  6465. ctx.putImageData(imgData, 0, 0);
  6466. return;
  6467. }
  6468. const height = imgData.height,
  6469. width = imgData.width;
  6470. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6471. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6472. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6473. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6474. let srcPos = 0,
  6475. destPos;
  6476. const src = imgData.data;
  6477. const dest = chunkImgData.data;
  6478. let i, j, thisChunkHeight, elemsInThisChunk;
  6479. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  6480. const srcLength = src.byteLength;
  6481. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  6482. const dest32DataLength = dest32.length;
  6483. const fullSrcDiff = width + 7 >> 3;
  6484. const white = 0xffffffff;
  6485. const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  6486. for (i = 0; i < totalChunks; i++) {
  6487. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6488. destPos = 0;
  6489. for (j = 0; j < thisChunkHeight; j++) {
  6490. const srcDiff = srcLength - srcPos;
  6491. let k = 0;
  6492. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6493. const kEndUnrolled = kEnd & ~7;
  6494. let mask = 0;
  6495. let srcByte = 0;
  6496. for (; k < kEndUnrolled; k += 8) {
  6497. srcByte = src[srcPos++];
  6498. dest32[destPos++] = srcByte & 128 ? white : black;
  6499. dest32[destPos++] = srcByte & 64 ? white : black;
  6500. dest32[destPos++] = srcByte & 32 ? white : black;
  6501. dest32[destPos++] = srcByte & 16 ? white : black;
  6502. dest32[destPos++] = srcByte & 8 ? white : black;
  6503. dest32[destPos++] = srcByte & 4 ? white : black;
  6504. dest32[destPos++] = srcByte & 2 ? white : black;
  6505. dest32[destPos++] = srcByte & 1 ? white : black;
  6506. }
  6507. for (; k < kEnd; k++) {
  6508. if (mask === 0) {
  6509. srcByte = src[srcPos++];
  6510. mask = 128;
  6511. }
  6512. dest32[destPos++] = srcByte & mask ? white : black;
  6513. mask >>= 1;
  6514. }
  6515. }
  6516. while (destPos < dest32DataLength) {
  6517. dest32[destPos++] = 0;
  6518. }
  6519. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6520. }
  6521. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  6522. j = 0;
  6523. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6524. for (i = 0; i < fullChunks; i++) {
  6525. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6526. srcPos += elemsInThisChunk;
  6527. ctx.putImageData(chunkImgData, 0, j);
  6528. j += FULL_CHUNK_HEIGHT;
  6529. }
  6530. if (i < totalChunks) {
  6531. elemsInThisChunk = width * partialChunkHeight * 4;
  6532. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6533. ctx.putImageData(chunkImgData, 0, j);
  6534. }
  6535. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  6536. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6537. elemsInThisChunk = width * thisChunkHeight;
  6538. for (i = 0; i < totalChunks; i++) {
  6539. if (i >= fullChunks) {
  6540. thisChunkHeight = partialChunkHeight;
  6541. elemsInThisChunk = width * thisChunkHeight;
  6542. }
  6543. destPos = 0;
  6544. for (j = elemsInThisChunk; j--;) {
  6545. dest[destPos++] = src[srcPos++];
  6546. dest[destPos++] = src[srcPos++];
  6547. dest[destPos++] = src[srcPos++];
  6548. dest[destPos++] = 255;
  6549. }
  6550. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6551. }
  6552. } else {
  6553. throw new Error(`bad image kind: ${imgData.kind}`);
  6554. }
  6555. }
  6556. function putBinaryImageMask(ctx, imgData) {
  6557. if (imgData.bitmap) {
  6558. ctx.drawImage(imgData.bitmap, 0, 0);
  6559. return;
  6560. }
  6561. const height = imgData.height,
  6562. width = imgData.width;
  6563. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6564. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6565. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6566. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6567. let srcPos = 0;
  6568. const src = imgData.data;
  6569. const dest = chunkImgData.data;
  6570. for (let i = 0; i < totalChunks; i++) {
  6571. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6572. ({
  6573. srcPos
  6574. } = (0, _image_utils.convertBlackAndWhiteToRGBA)({
  6575. src,
  6576. srcPos,
  6577. dest,
  6578. width,
  6579. height: thisChunkHeight,
  6580. nonBlackColor: 0
  6581. }));
  6582. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6583. }
  6584. }
  6585. function copyCtxState(sourceCtx, destCtx) {
  6586. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  6587. for (const property of properties) {
  6588. if (sourceCtx[property] !== undefined) {
  6589. destCtx[property] = sourceCtx[property];
  6590. }
  6591. }
  6592. if (sourceCtx.setLineDash !== undefined) {
  6593. destCtx.setLineDash(sourceCtx.getLineDash());
  6594. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6595. }
  6596. }
  6597. function resetCtxToDefault(ctx) {
  6598. ctx.strokeStyle = ctx.fillStyle = "#000000";
  6599. ctx.fillRule = "nonzero";
  6600. ctx.globalAlpha = 1;
  6601. ctx.lineWidth = 1;
  6602. ctx.lineCap = "butt";
  6603. ctx.lineJoin = "miter";
  6604. ctx.miterLimit = 10;
  6605. ctx.globalCompositeOperation = "source-over";
  6606. ctx.font = "10px sans-serif";
  6607. if (ctx.setLineDash !== undefined) {
  6608. ctx.setLineDash([]);
  6609. ctx.lineDashOffset = 0;
  6610. }
  6611. if (!_util.isNodeJS) {
  6612. const {
  6613. filter
  6614. } = ctx;
  6615. if (filter !== "none" && filter !== "") {
  6616. ctx.filter = "none";
  6617. }
  6618. }
  6619. }
  6620. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6621. const length = bytes.length;
  6622. for (let i = 3; i < length; i += 4) {
  6623. const alpha = bytes[i];
  6624. if (alpha === 0) {
  6625. bytes[i - 3] = r0;
  6626. bytes[i - 2] = g0;
  6627. bytes[i - 1] = b0;
  6628. } else if (alpha < 255) {
  6629. const alpha_ = 255 - alpha;
  6630. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  6631. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  6632. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  6633. }
  6634. }
  6635. }
  6636. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6637. const length = maskData.length;
  6638. const scale = 1 / 255;
  6639. for (let i = 3; i < length; i += 4) {
  6640. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6641. layerData[i] = layerData[i] * alpha * scale | 0;
  6642. }
  6643. }
  6644. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6645. const length = maskData.length;
  6646. for (let i = 3; i < length; i += 4) {
  6647. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  6648. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  6649. }
  6650. }
  6651. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  6652. const hasBackdrop = !!backdrop;
  6653. const r0 = hasBackdrop ? backdrop[0] : 0;
  6654. const g0 = hasBackdrop ? backdrop[1] : 0;
  6655. const b0 = hasBackdrop ? backdrop[2] : 0;
  6656. const composeFn = subtype === "Luminosity" ? composeSMaskLuminosity : composeSMaskAlpha;
  6657. const PIXELS_TO_PROCESS = 1048576;
  6658. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6659. for (let row = 0; row < height; row += chunkSize) {
  6660. const chunkHeight = Math.min(chunkSize, height - row);
  6661. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  6662. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  6663. if (hasBackdrop) {
  6664. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6665. }
  6666. composeFn(maskData.data, layerData.data, transferMap);
  6667. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  6668. }
  6669. }
  6670. function composeSMask(ctx, smask, layerCtx, layerBox) {
  6671. const layerOffsetX = layerBox[0];
  6672. const layerOffsetY = layerBox[1];
  6673. const layerWidth = layerBox[2] - layerOffsetX;
  6674. const layerHeight = layerBox[3] - layerOffsetY;
  6675. if (layerWidth === 0 || layerHeight === 0) {
  6676. return;
  6677. }
  6678. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  6679. ctx.save();
  6680. ctx.globalAlpha = 1;
  6681. ctx.globalCompositeOperation = "source-over";
  6682. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6683. ctx.drawImage(layerCtx.canvas, 0, 0);
  6684. ctx.restore();
  6685. }
  6686. function getImageSmoothingEnabled(transform, interpolate) {
  6687. const scale = _util.Util.singularValueDecompose2dScale(transform);
  6688. scale[0] = Math.fround(scale[0]);
  6689. scale[1] = Math.fround(scale[1]);
  6690. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  6691. if (interpolate !== undefined) {
  6692. return interpolate;
  6693. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  6694. return true;
  6695. }
  6696. return false;
  6697. }
  6698. const LINE_CAP_STYLES = ["butt", "round", "square"];
  6699. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  6700. const NORMAL_CLIP = {};
  6701. const EO_CLIP = {};
  6702. class CanvasGraphics {
  6703. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  6704. optionalContentConfig,
  6705. markedContentStack = null
  6706. }, annotationCanvasMap, pageColors) {
  6707. this.ctx = canvasCtx;
  6708. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6709. this.stateStack = [];
  6710. this.pendingClip = null;
  6711. this.pendingEOFill = false;
  6712. this.res = null;
  6713. this.xobjs = null;
  6714. this.commonObjs = commonObjs;
  6715. this.objs = objs;
  6716. this.canvasFactory = canvasFactory;
  6717. this.filterFactory = filterFactory;
  6718. this.groupStack = [];
  6719. this.processingType3 = null;
  6720. this.baseTransform = null;
  6721. this.baseTransformStack = [];
  6722. this.groupLevel = 0;
  6723. this.smaskStack = [];
  6724. this.smaskCounter = 0;
  6725. this.tempSMask = null;
  6726. this.suspendedCtx = null;
  6727. this.contentVisible = true;
  6728. this.markedContentStack = markedContentStack || [];
  6729. this.optionalContentConfig = optionalContentConfig;
  6730. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  6731. this.cachedPatterns = new Map();
  6732. this.annotationCanvasMap = annotationCanvasMap;
  6733. this.viewportScale = 1;
  6734. this.outputScaleX = 1;
  6735. this.outputScaleY = 1;
  6736. this.pageColors = pageColors;
  6737. this._cachedScaleForStroking = [-1, 0];
  6738. this._cachedGetSinglePixelWidth = null;
  6739. this._cachedBitmapsMap = new Map();
  6740. }
  6741. getObject(data, fallback = null) {
  6742. if (typeof data === "string") {
  6743. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  6744. }
  6745. return fallback;
  6746. }
  6747. beginDrawing({
  6748. transform,
  6749. viewport,
  6750. transparency = false,
  6751. background = null
  6752. }) {
  6753. const width = this.ctx.canvas.width;
  6754. const height = this.ctx.canvas.height;
  6755. const savedFillStyle = this.ctx.fillStyle;
  6756. this.ctx.fillStyle = background || "#ffffff";
  6757. this.ctx.fillRect(0, 0, width, height);
  6758. this.ctx.fillStyle = savedFillStyle;
  6759. if (transparency) {
  6760. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  6761. this.compositeCtx = this.ctx;
  6762. this.transparentCanvas = transparentCanvas.canvas;
  6763. this.ctx = transparentCanvas.context;
  6764. this.ctx.save();
  6765. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  6766. }
  6767. this.ctx.save();
  6768. resetCtxToDefault(this.ctx);
  6769. if (transform) {
  6770. this.ctx.transform(...transform);
  6771. this.outputScaleX = transform[0];
  6772. this.outputScaleY = transform[0];
  6773. }
  6774. this.ctx.transform(...viewport.transform);
  6775. this.viewportScale = viewport.scale;
  6776. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  6777. }
  6778. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  6779. const argsArray = operatorList.argsArray;
  6780. const fnArray = operatorList.fnArray;
  6781. let i = executionStartIdx || 0;
  6782. const argsArrayLen = argsArray.length;
  6783. if (argsArrayLen === i) {
  6784. return i;
  6785. }
  6786. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  6787. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6788. let steps = 0;
  6789. const commonObjs = this.commonObjs;
  6790. const objs = this.objs;
  6791. let fnId;
  6792. while (true) {
  6793. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6794. stepper.breakIt(i, continueCallback);
  6795. return i;
  6796. }
  6797. fnId = fnArray[i];
  6798. if (fnId !== _util.OPS.dependency) {
  6799. this[fnId].apply(this, argsArray[i]);
  6800. } else {
  6801. for (const depObjId of argsArray[i]) {
  6802. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  6803. if (!objsPool.has(depObjId)) {
  6804. objsPool.get(depObjId, continueCallback);
  6805. return i;
  6806. }
  6807. }
  6808. }
  6809. i++;
  6810. if (i === argsArrayLen) {
  6811. return i;
  6812. }
  6813. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6814. if (Date.now() > endTime) {
  6815. continueCallback();
  6816. return i;
  6817. }
  6818. steps = 0;
  6819. }
  6820. }
  6821. }
  6822. #restoreInitialState() {
  6823. while (this.stateStack.length || this.inSMaskMode) {
  6824. this.restore();
  6825. }
  6826. this.ctx.restore();
  6827. if (this.transparentCanvas) {
  6828. this.ctx = this.compositeCtx;
  6829. this.ctx.save();
  6830. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  6831. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6832. this.ctx.restore();
  6833. this.transparentCanvas = null;
  6834. }
  6835. }
  6836. endDrawing() {
  6837. this.#restoreInitialState();
  6838. this.cachedCanvases.clear();
  6839. this.cachedPatterns.clear();
  6840. for (const cache of this._cachedBitmapsMap.values()) {
  6841. for (const canvas of cache.values()) {
  6842. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  6843. canvas.width = canvas.height = 0;
  6844. }
  6845. }
  6846. cache.clear();
  6847. }
  6848. this._cachedBitmapsMap.clear();
  6849. this.#drawFilter();
  6850. }
  6851. #drawFilter() {
  6852. if (this.pageColors) {
  6853. const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
  6854. if (hcmFilterId !== "none") {
  6855. const savedFilter = this.ctx.filter;
  6856. this.ctx.filter = hcmFilterId;
  6857. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  6858. this.ctx.filter = savedFilter;
  6859. }
  6860. }
  6861. }
  6862. _scaleImage(img, inverseTransform) {
  6863. const width = img.width;
  6864. const height = img.height;
  6865. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  6866. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  6867. let paintWidth = width,
  6868. paintHeight = height;
  6869. let tmpCanvasId = "prescale1";
  6870. let tmpCanvas, tmpCtx;
  6871. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  6872. let newWidth = paintWidth,
  6873. newHeight = paintHeight;
  6874. if (widthScale > 2 && paintWidth > 1) {
  6875. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  6876. widthScale /= paintWidth / newWidth;
  6877. }
  6878. if (heightScale > 2 && paintHeight > 1) {
  6879. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  6880. heightScale /= paintHeight / newHeight;
  6881. }
  6882. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  6883. tmpCtx = tmpCanvas.context;
  6884. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  6885. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  6886. img = tmpCanvas.canvas;
  6887. paintWidth = newWidth;
  6888. paintHeight = newHeight;
  6889. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  6890. }
  6891. return {
  6892. img,
  6893. paintWidth,
  6894. paintHeight
  6895. };
  6896. }
  6897. _createMaskCanvas(img) {
  6898. const ctx = this.ctx;
  6899. const {
  6900. width,
  6901. height
  6902. } = img;
  6903. const fillColor = this.current.fillColor;
  6904. const isPatternFill = this.current.patternFill;
  6905. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6906. let cache, cacheKey, scaled, maskCanvas;
  6907. if ((img.bitmap || img.data) && img.count > 1) {
  6908. const mainKey = img.bitmap || img.data.buffer;
  6909. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  6910. cache = this._cachedBitmapsMap.get(mainKey);
  6911. if (!cache) {
  6912. cache = new Map();
  6913. this._cachedBitmapsMap.set(mainKey, cache);
  6914. }
  6915. const cachedImage = cache.get(cacheKey);
  6916. if (cachedImage && !isPatternFill) {
  6917. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  6918. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  6919. return {
  6920. canvas: cachedImage,
  6921. offsetX,
  6922. offsetY
  6923. };
  6924. }
  6925. scaled = cachedImage;
  6926. }
  6927. if (!scaled) {
  6928. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  6929. putBinaryImageMask(maskCanvas.context, img);
  6930. }
  6931. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  6932. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  6933. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  6934. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  6935. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  6936. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  6937. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  6938. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  6939. const fillCtx = fillCanvas.context;
  6940. const offsetX = Math.min(cord1[0], cord2[0]);
  6941. const offsetY = Math.min(cord1[1], cord2[1]);
  6942. fillCtx.translate(-offsetX, -offsetY);
  6943. fillCtx.transform(...maskToCanvas);
  6944. if (!scaled) {
  6945. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  6946. scaled = scaled.img;
  6947. if (cache && isPatternFill) {
  6948. cache.set(cacheKey, scaled);
  6949. }
  6950. }
  6951. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  6952. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  6953. fillCtx.globalCompositeOperation = "source-in";
  6954. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  6955. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  6956. fillCtx.fillRect(0, 0, width, height);
  6957. if (cache && !isPatternFill) {
  6958. this.cachedCanvases.delete("fillCanvas");
  6959. cache.set(cacheKey, fillCanvas.canvas);
  6960. }
  6961. return {
  6962. canvas: fillCanvas.canvas,
  6963. offsetX: Math.round(offsetX),
  6964. offsetY: Math.round(offsetY)
  6965. };
  6966. }
  6967. setLineWidth(width) {
  6968. if (width !== this.current.lineWidth) {
  6969. this._cachedScaleForStroking[0] = -1;
  6970. }
  6971. this.current.lineWidth = width;
  6972. this.ctx.lineWidth = width;
  6973. }
  6974. setLineCap(style) {
  6975. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6976. }
  6977. setLineJoin(style) {
  6978. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6979. }
  6980. setMiterLimit(limit) {
  6981. this.ctx.miterLimit = limit;
  6982. }
  6983. setDash(dashArray, dashPhase) {
  6984. const ctx = this.ctx;
  6985. if (ctx.setLineDash !== undefined) {
  6986. ctx.setLineDash(dashArray);
  6987. ctx.lineDashOffset = dashPhase;
  6988. }
  6989. }
  6990. setRenderingIntent(intent) {}
  6991. setFlatness(flatness) {}
  6992. setGState(states) {
  6993. for (const [key, value] of states) {
  6994. switch (key) {
  6995. case "LW":
  6996. this.setLineWidth(value);
  6997. break;
  6998. case "LC":
  6999. this.setLineCap(value);
  7000. break;
  7001. case "LJ":
  7002. this.setLineJoin(value);
  7003. break;
  7004. case "ML":
  7005. this.setMiterLimit(value);
  7006. break;
  7007. case "D":
  7008. this.setDash(value[0], value[1]);
  7009. break;
  7010. case "RI":
  7011. this.setRenderingIntent(value);
  7012. break;
  7013. case "FL":
  7014. this.setFlatness(value);
  7015. break;
  7016. case "Font":
  7017. this.setFont(value[0], value[1]);
  7018. break;
  7019. case "CA":
  7020. this.current.strokeAlpha = value;
  7021. break;
  7022. case "ca":
  7023. this.current.fillAlpha = value;
  7024. this.ctx.globalAlpha = value;
  7025. break;
  7026. case "BM":
  7027. this.ctx.globalCompositeOperation = value;
  7028. break;
  7029. case "SMask":
  7030. this.current.activeSMask = value ? this.tempSMask : null;
  7031. this.tempSMask = null;
  7032. this.checkSMaskState();
  7033. break;
  7034. case "TR":
  7035. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  7036. break;
  7037. }
  7038. }
  7039. }
  7040. get inSMaskMode() {
  7041. return !!this.suspendedCtx;
  7042. }
  7043. checkSMaskState() {
  7044. const inSMaskMode = this.inSMaskMode;
  7045. if (this.current.activeSMask && !inSMaskMode) {
  7046. this.beginSMaskMode();
  7047. } else if (!this.current.activeSMask && inSMaskMode) {
  7048. this.endSMaskMode();
  7049. }
  7050. }
  7051. beginSMaskMode() {
  7052. if (this.inSMaskMode) {
  7053. throw new Error("beginSMaskMode called while already in smask mode");
  7054. }
  7055. const drawnWidth = this.ctx.canvas.width;
  7056. const drawnHeight = this.ctx.canvas.height;
  7057. const cacheId = "smaskGroupAt" + this.groupLevel;
  7058. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  7059. this.suspendedCtx = this.ctx;
  7060. this.ctx = scratchCanvas.context;
  7061. const ctx = this.ctx;
  7062. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  7063. copyCtxState(this.suspendedCtx, ctx);
  7064. mirrorContextOperations(ctx, this.suspendedCtx);
  7065. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  7066. }
  7067. endSMaskMode() {
  7068. if (!this.inSMaskMode) {
  7069. throw new Error("endSMaskMode called while not in smask mode");
  7070. }
  7071. this.ctx._removeMirroring();
  7072. copyCtxState(this.ctx, this.suspendedCtx);
  7073. this.ctx = this.suspendedCtx;
  7074. this.suspendedCtx = null;
  7075. }
  7076. compose(dirtyBox) {
  7077. if (!this.current.activeSMask) {
  7078. return;
  7079. }
  7080. if (!dirtyBox) {
  7081. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  7082. } else {
  7083. dirtyBox[0] = Math.floor(dirtyBox[0]);
  7084. dirtyBox[1] = Math.floor(dirtyBox[1]);
  7085. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  7086. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  7087. }
  7088. const smask = this.current.activeSMask;
  7089. const suspendedCtx = this.suspendedCtx;
  7090. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  7091. this.ctx.save();
  7092. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7093. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  7094. this.ctx.restore();
  7095. }
  7096. save() {
  7097. if (this.inSMaskMode) {
  7098. copyCtxState(this.ctx, this.suspendedCtx);
  7099. this.suspendedCtx.save();
  7100. } else {
  7101. this.ctx.save();
  7102. }
  7103. const old = this.current;
  7104. this.stateStack.push(old);
  7105. this.current = old.clone();
  7106. }
  7107. restore() {
  7108. if (this.stateStack.length === 0 && this.inSMaskMode) {
  7109. this.endSMaskMode();
  7110. }
  7111. if (this.stateStack.length !== 0) {
  7112. this.current = this.stateStack.pop();
  7113. if (this.inSMaskMode) {
  7114. this.suspendedCtx.restore();
  7115. copyCtxState(this.suspendedCtx, this.ctx);
  7116. } else {
  7117. this.ctx.restore();
  7118. }
  7119. this.checkSMaskState();
  7120. this.pendingClip = null;
  7121. this._cachedScaleForStroking[0] = -1;
  7122. this._cachedGetSinglePixelWidth = null;
  7123. }
  7124. }
  7125. transform(a, b, c, d, e, f) {
  7126. this.ctx.transform(a, b, c, d, e, f);
  7127. this._cachedScaleForStroking[0] = -1;
  7128. this._cachedGetSinglePixelWidth = null;
  7129. }
  7130. constructPath(ops, args, minMax) {
  7131. const ctx = this.ctx;
  7132. const current = this.current;
  7133. let x = current.x,
  7134. y = current.y;
  7135. let startX, startY;
  7136. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  7137. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  7138. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  7139. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7140. switch (ops[i] | 0) {
  7141. case _util.OPS.rectangle:
  7142. x = args[j++];
  7143. y = args[j++];
  7144. const width = args[j++];
  7145. const height = args[j++];
  7146. const xw = x + width;
  7147. const yh = y + height;
  7148. ctx.moveTo(x, y);
  7149. if (width === 0 || height === 0) {
  7150. ctx.lineTo(xw, yh);
  7151. } else {
  7152. ctx.lineTo(xw, y);
  7153. ctx.lineTo(xw, yh);
  7154. ctx.lineTo(x, yh);
  7155. }
  7156. if (!isScalingMatrix) {
  7157. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  7158. }
  7159. ctx.closePath();
  7160. break;
  7161. case _util.OPS.moveTo:
  7162. x = args[j++];
  7163. y = args[j++];
  7164. ctx.moveTo(x, y);
  7165. if (!isScalingMatrix) {
  7166. current.updatePathMinMax(currentTransform, x, y);
  7167. }
  7168. break;
  7169. case _util.OPS.lineTo:
  7170. x = args[j++];
  7171. y = args[j++];
  7172. ctx.lineTo(x, y);
  7173. if (!isScalingMatrix) {
  7174. current.updatePathMinMax(currentTransform, x, y);
  7175. }
  7176. break;
  7177. case _util.OPS.curveTo:
  7178. startX = x;
  7179. startY = y;
  7180. x = args[j + 4];
  7181. y = args[j + 5];
  7182. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7183. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  7184. j += 6;
  7185. break;
  7186. case _util.OPS.curveTo2:
  7187. startX = x;
  7188. startY = y;
  7189. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7190. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  7191. x = args[j + 2];
  7192. y = args[j + 3];
  7193. j += 4;
  7194. break;
  7195. case _util.OPS.curveTo3:
  7196. startX = x;
  7197. startY = y;
  7198. x = args[j + 2];
  7199. y = args[j + 3];
  7200. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7201. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  7202. j += 4;
  7203. break;
  7204. case _util.OPS.closePath:
  7205. ctx.closePath();
  7206. break;
  7207. }
  7208. }
  7209. if (isScalingMatrix) {
  7210. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  7211. }
  7212. current.setCurrentPoint(x, y);
  7213. }
  7214. closePath() {
  7215. this.ctx.closePath();
  7216. }
  7217. stroke(consumePath = true) {
  7218. const ctx = this.ctx;
  7219. const strokeColor = this.current.strokeColor;
  7220. ctx.globalAlpha = this.current.strokeAlpha;
  7221. if (this.contentVisible) {
  7222. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  7223. ctx.save();
  7224. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  7225. this.rescaleAndStroke(false);
  7226. ctx.restore();
  7227. } else {
  7228. this.rescaleAndStroke(true);
  7229. }
  7230. }
  7231. if (consumePath) {
  7232. this.consumePath(this.current.getClippedPathBoundingBox());
  7233. }
  7234. ctx.globalAlpha = this.current.fillAlpha;
  7235. }
  7236. closeStroke() {
  7237. this.closePath();
  7238. this.stroke();
  7239. }
  7240. fill(consumePath = true) {
  7241. const ctx = this.ctx;
  7242. const fillColor = this.current.fillColor;
  7243. const isPatternFill = this.current.patternFill;
  7244. let needRestore = false;
  7245. if (isPatternFill) {
  7246. ctx.save();
  7247. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  7248. needRestore = true;
  7249. }
  7250. const intersect = this.current.getClippedPathBoundingBox();
  7251. if (this.contentVisible && intersect !== null) {
  7252. if (this.pendingEOFill) {
  7253. ctx.fill("evenodd");
  7254. this.pendingEOFill = false;
  7255. } else {
  7256. ctx.fill();
  7257. }
  7258. }
  7259. if (needRestore) {
  7260. ctx.restore();
  7261. }
  7262. if (consumePath) {
  7263. this.consumePath(intersect);
  7264. }
  7265. }
  7266. eoFill() {
  7267. this.pendingEOFill = true;
  7268. this.fill();
  7269. }
  7270. fillStroke() {
  7271. this.fill(false);
  7272. this.stroke(false);
  7273. this.consumePath();
  7274. }
  7275. eoFillStroke() {
  7276. this.pendingEOFill = true;
  7277. this.fillStroke();
  7278. }
  7279. closeFillStroke() {
  7280. this.closePath();
  7281. this.fillStroke();
  7282. }
  7283. closeEOFillStroke() {
  7284. this.pendingEOFill = true;
  7285. this.closePath();
  7286. this.fillStroke();
  7287. }
  7288. endPath() {
  7289. this.consumePath();
  7290. }
  7291. clip() {
  7292. this.pendingClip = NORMAL_CLIP;
  7293. }
  7294. eoClip() {
  7295. this.pendingClip = EO_CLIP;
  7296. }
  7297. beginText() {
  7298. this.current.textMatrix = _util.IDENTITY_MATRIX;
  7299. this.current.textMatrixScale = 1;
  7300. this.current.x = this.current.lineX = 0;
  7301. this.current.y = this.current.lineY = 0;
  7302. }
  7303. endText() {
  7304. const paths = this.pendingTextPaths;
  7305. const ctx = this.ctx;
  7306. if (paths === undefined) {
  7307. ctx.beginPath();
  7308. return;
  7309. }
  7310. ctx.save();
  7311. ctx.beginPath();
  7312. for (const path of paths) {
  7313. ctx.setTransform(...path.transform);
  7314. ctx.translate(path.x, path.y);
  7315. path.addToPath(ctx, path.fontSize);
  7316. }
  7317. ctx.restore();
  7318. ctx.clip();
  7319. ctx.beginPath();
  7320. delete this.pendingTextPaths;
  7321. }
  7322. setCharSpacing(spacing) {
  7323. this.current.charSpacing = spacing;
  7324. }
  7325. setWordSpacing(spacing) {
  7326. this.current.wordSpacing = spacing;
  7327. }
  7328. setHScale(scale) {
  7329. this.current.textHScale = scale / 100;
  7330. }
  7331. setLeading(leading) {
  7332. this.current.leading = -leading;
  7333. }
  7334. setFont(fontRefName, size) {
  7335. const fontObj = this.commonObjs.get(fontRefName);
  7336. const current = this.current;
  7337. if (!fontObj) {
  7338. throw new Error(`Can't find font for ${fontRefName}`);
  7339. }
  7340. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  7341. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7342. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  7343. }
  7344. if (size < 0) {
  7345. size = -size;
  7346. current.fontDirection = -1;
  7347. } else {
  7348. current.fontDirection = 1;
  7349. }
  7350. this.current.font = fontObj;
  7351. this.current.fontSize = size;
  7352. if (fontObj.isType3Font) {
  7353. return;
  7354. }
  7355. const name = fontObj.loadedName || "sans-serif";
  7356. const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
  7357. let bold = "normal";
  7358. if (fontObj.black) {
  7359. bold = "900";
  7360. } else if (fontObj.bold) {
  7361. bold = "bold";
  7362. }
  7363. const italic = fontObj.italic ? "italic" : "normal";
  7364. let browserFontSize = size;
  7365. if (size < MIN_FONT_SIZE) {
  7366. browserFontSize = MIN_FONT_SIZE;
  7367. } else if (size > MAX_FONT_SIZE) {
  7368. browserFontSize = MAX_FONT_SIZE;
  7369. }
  7370. this.current.fontSizeScale = size / browserFontSize;
  7371. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  7372. }
  7373. setTextRenderingMode(mode) {
  7374. this.current.textRenderingMode = mode;
  7375. }
  7376. setTextRise(rise) {
  7377. this.current.textRise = rise;
  7378. }
  7379. moveText(x, y) {
  7380. this.current.x = this.current.lineX += x;
  7381. this.current.y = this.current.lineY += y;
  7382. }
  7383. setLeadingMoveText(x, y) {
  7384. this.setLeading(-y);
  7385. this.moveText(x, y);
  7386. }
  7387. setTextMatrix(a, b, c, d, e, f) {
  7388. this.current.textMatrix = [a, b, c, d, e, f];
  7389. this.current.textMatrixScale = Math.hypot(a, b);
  7390. this.current.x = this.current.lineX = 0;
  7391. this.current.y = this.current.lineY = 0;
  7392. }
  7393. nextLine() {
  7394. this.moveText(0, this.current.leading);
  7395. }
  7396. paintChar(character, x, y, patternTransform) {
  7397. const ctx = this.ctx;
  7398. const current = this.current;
  7399. const font = current.font;
  7400. const textRenderingMode = current.textRenderingMode;
  7401. const fontSize = current.fontSize / current.fontSizeScale;
  7402. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  7403. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  7404. const patternFill = current.patternFill && !font.missingFile;
  7405. let addToPath;
  7406. if (font.disableFontFace || isAddToPathSet || patternFill) {
  7407. addToPath = font.getPathGenerator(this.commonObjs, character);
  7408. }
  7409. if (font.disableFontFace || patternFill) {
  7410. ctx.save();
  7411. ctx.translate(x, y);
  7412. ctx.beginPath();
  7413. addToPath(ctx, fontSize);
  7414. if (patternTransform) {
  7415. ctx.setTransform(...patternTransform);
  7416. }
  7417. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  7418. ctx.fill();
  7419. }
  7420. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  7421. ctx.stroke();
  7422. }
  7423. ctx.restore();
  7424. } else {
  7425. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  7426. ctx.fillText(character, x, y);
  7427. }
  7428. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  7429. ctx.strokeText(character, x, y);
  7430. }
  7431. }
  7432. if (isAddToPathSet) {
  7433. const paths = this.pendingTextPaths ||= [];
  7434. paths.push({
  7435. transform: (0, _display_utils.getCurrentTransform)(ctx),
  7436. x,
  7437. y,
  7438. fontSize,
  7439. addToPath
  7440. });
  7441. }
  7442. }
  7443. get isFontSubpixelAAEnabled() {
  7444. const {
  7445. context: ctx
  7446. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  7447. ctx.scale(1.5, 1);
  7448. ctx.fillText("I", 0, 10);
  7449. const data = ctx.getImageData(0, 0, 10, 10).data;
  7450. let enabled = false;
  7451. for (let i = 3; i < data.length; i += 4) {
  7452. if (data[i] > 0 && data[i] < 255) {
  7453. enabled = true;
  7454. break;
  7455. }
  7456. }
  7457. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  7458. }
  7459. showText(glyphs) {
  7460. const current = this.current;
  7461. const font = current.font;
  7462. if (font.isType3Font) {
  7463. return this.showType3Text(glyphs);
  7464. }
  7465. const fontSize = current.fontSize;
  7466. if (fontSize === 0) {
  7467. return undefined;
  7468. }
  7469. const ctx = this.ctx;
  7470. const fontSizeScale = current.fontSizeScale;
  7471. const charSpacing = current.charSpacing;
  7472. const wordSpacing = current.wordSpacing;
  7473. const fontDirection = current.fontDirection;
  7474. const textHScale = current.textHScale * fontDirection;
  7475. const glyphsLength = glyphs.length;
  7476. const vertical = font.vertical;
  7477. const spacingDir = vertical ? 1 : -1;
  7478. const defaultVMetrics = font.defaultVMetrics;
  7479. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  7480. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  7481. ctx.save();
  7482. ctx.transform(...current.textMatrix);
  7483. ctx.translate(current.x, current.y + current.textRise);
  7484. if (fontDirection > 0) {
  7485. ctx.scale(textHScale, -1);
  7486. } else {
  7487. ctx.scale(textHScale, 1);
  7488. }
  7489. let patternTransform;
  7490. if (current.patternFill) {
  7491. ctx.save();
  7492. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  7493. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  7494. ctx.restore();
  7495. ctx.fillStyle = pattern;
  7496. }
  7497. let lineWidth = current.lineWidth;
  7498. const scale = current.textMatrixScale;
  7499. if (scale === 0 || lineWidth === 0) {
  7500. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  7501. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  7502. lineWidth = this.getSinglePixelWidth();
  7503. }
  7504. } else {
  7505. lineWidth /= scale;
  7506. }
  7507. if (fontSizeScale !== 1.0) {
  7508. ctx.scale(fontSizeScale, fontSizeScale);
  7509. lineWidth /= fontSizeScale;
  7510. }
  7511. ctx.lineWidth = lineWidth;
  7512. if (font.isInvalidPDFjsFont) {
  7513. const chars = [];
  7514. let width = 0;
  7515. for (const glyph of glyphs) {
  7516. chars.push(glyph.unicode);
  7517. width += glyph.width;
  7518. }
  7519. ctx.fillText(chars.join(""), 0, 0);
  7520. current.x += width * widthAdvanceScale * textHScale;
  7521. ctx.restore();
  7522. this.compose();
  7523. return undefined;
  7524. }
  7525. let x = 0,
  7526. i;
  7527. for (i = 0; i < glyphsLength; ++i) {
  7528. const glyph = glyphs[i];
  7529. if (typeof glyph === "number") {
  7530. x += spacingDir * glyph * fontSize / 1000;
  7531. continue;
  7532. }
  7533. let restoreNeeded = false;
  7534. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7535. const character = glyph.fontChar;
  7536. const accent = glyph.accent;
  7537. let scaledX, scaledY;
  7538. let width = glyph.width;
  7539. if (vertical) {
  7540. const vmetric = glyph.vmetric || defaultVMetrics;
  7541. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  7542. const vy = vmetric[2] * widthAdvanceScale;
  7543. width = vmetric ? -vmetric[0] : width;
  7544. scaledX = vx / fontSizeScale;
  7545. scaledY = (x + vy) / fontSizeScale;
  7546. } else {
  7547. scaledX = x / fontSizeScale;
  7548. scaledY = 0;
  7549. }
  7550. if (font.remeasure && width > 0) {
  7551. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7552. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7553. const characterScaleX = width / measuredWidth;
  7554. restoreNeeded = true;
  7555. ctx.save();
  7556. ctx.scale(characterScaleX, 1);
  7557. scaledX /= characterScaleX;
  7558. } else if (width !== measuredWidth) {
  7559. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7560. }
  7561. }
  7562. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  7563. if (simpleFillText && !accent) {
  7564. ctx.fillText(character, scaledX, scaledY);
  7565. } else {
  7566. this.paintChar(character, scaledX, scaledY, patternTransform);
  7567. if (accent) {
  7568. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  7569. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  7570. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  7571. }
  7572. }
  7573. }
  7574. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  7575. x += charWidth;
  7576. if (restoreNeeded) {
  7577. ctx.restore();
  7578. }
  7579. }
  7580. if (vertical) {
  7581. current.y -= x;
  7582. } else {
  7583. current.x += x * textHScale;
  7584. }
  7585. ctx.restore();
  7586. this.compose();
  7587. return undefined;
  7588. }
  7589. showType3Text(glyphs) {
  7590. const ctx = this.ctx;
  7591. const current = this.current;
  7592. const font = current.font;
  7593. const fontSize = current.fontSize;
  7594. const fontDirection = current.fontDirection;
  7595. const spacingDir = font.vertical ? 1 : -1;
  7596. const charSpacing = current.charSpacing;
  7597. const wordSpacing = current.wordSpacing;
  7598. const textHScale = current.textHScale * fontDirection;
  7599. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  7600. const glyphsLength = glyphs.length;
  7601. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  7602. let i, glyph, width, spacingLength;
  7603. if (isTextInvisible || fontSize === 0) {
  7604. return;
  7605. }
  7606. this._cachedScaleForStroking[0] = -1;
  7607. this._cachedGetSinglePixelWidth = null;
  7608. ctx.save();
  7609. ctx.transform(...current.textMatrix);
  7610. ctx.translate(current.x, current.y);
  7611. ctx.scale(textHScale, fontDirection);
  7612. for (i = 0; i < glyphsLength; ++i) {
  7613. glyph = glyphs[i];
  7614. if (typeof glyph === "number") {
  7615. spacingLength = spacingDir * glyph * fontSize / 1000;
  7616. this.ctx.translate(spacingLength, 0);
  7617. current.x += spacingLength * textHScale;
  7618. continue;
  7619. }
  7620. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7621. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  7622. if (!operatorList) {
  7623. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  7624. continue;
  7625. }
  7626. if (this.contentVisible) {
  7627. this.processingType3 = glyph;
  7628. this.save();
  7629. ctx.scale(fontSize, fontSize);
  7630. ctx.transform(...fontMatrix);
  7631. this.executeOperatorList(operatorList);
  7632. this.restore();
  7633. }
  7634. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  7635. width = transformed[0] * fontSize + spacing;
  7636. ctx.translate(width, 0);
  7637. current.x += width * textHScale;
  7638. }
  7639. ctx.restore();
  7640. this.processingType3 = null;
  7641. }
  7642. setCharWidth(xWidth, yWidth) {}
  7643. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7644. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7645. this.ctx.clip();
  7646. this.endPath();
  7647. }
  7648. getColorN_Pattern(IR) {
  7649. let pattern;
  7650. if (IR[0] === "TilingPattern") {
  7651. const color = IR[1];
  7652. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  7653. const canvasGraphicsFactory = {
  7654. createCanvasGraphics: ctx => {
  7655. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  7656. optionalContentConfig: this.optionalContentConfig,
  7657. markedContentStack: this.markedContentStack
  7658. });
  7659. }
  7660. };
  7661. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7662. } else {
  7663. pattern = this._getPattern(IR[1], IR[2]);
  7664. }
  7665. return pattern;
  7666. }
  7667. setStrokeColorN() {
  7668. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7669. }
  7670. setFillColorN() {
  7671. this.current.fillColor = this.getColorN_Pattern(arguments);
  7672. this.current.patternFill = true;
  7673. }
  7674. setStrokeRGBColor(r, g, b) {
  7675. const color = _util.Util.makeHexColor(r, g, b);
  7676. this.ctx.strokeStyle = color;
  7677. this.current.strokeColor = color;
  7678. }
  7679. setFillRGBColor(r, g, b) {
  7680. const color = _util.Util.makeHexColor(r, g, b);
  7681. this.ctx.fillStyle = color;
  7682. this.current.fillColor = color;
  7683. this.current.patternFill = false;
  7684. }
  7685. _getPattern(objId, matrix = null) {
  7686. let pattern;
  7687. if (this.cachedPatterns.has(objId)) {
  7688. pattern = this.cachedPatterns.get(objId);
  7689. } else {
  7690. pattern = (0, _pattern_helper.getShadingPattern)(this.getObject(objId));
  7691. this.cachedPatterns.set(objId, pattern);
  7692. }
  7693. if (matrix) {
  7694. pattern.matrix = matrix;
  7695. }
  7696. return pattern;
  7697. }
  7698. shadingFill(objId) {
  7699. if (!this.contentVisible) {
  7700. return;
  7701. }
  7702. const ctx = this.ctx;
  7703. this.save();
  7704. const pattern = this._getPattern(objId);
  7705. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  7706. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  7707. if (inv) {
  7708. const {
  7709. width,
  7710. height
  7711. } = ctx.canvas;
  7712. const [x0, y0, x1, y1] = _util.Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
  7713. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7714. } else {
  7715. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7716. }
  7717. this.compose(this.current.getClippedPathBoundingBox());
  7718. this.restore();
  7719. }
  7720. beginInlineImage() {
  7721. (0, _util.unreachable)("Should not call beginInlineImage");
  7722. }
  7723. beginImageData() {
  7724. (0, _util.unreachable)("Should not call beginImageData");
  7725. }
  7726. paintFormXObjectBegin(matrix, bbox) {
  7727. if (!this.contentVisible) {
  7728. return;
  7729. }
  7730. this.save();
  7731. this.baseTransformStack.push(this.baseTransform);
  7732. if (Array.isArray(matrix) && matrix.length === 6) {
  7733. this.transform(...matrix);
  7734. }
  7735. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  7736. if (bbox) {
  7737. const width = bbox[2] - bbox[0];
  7738. const height = bbox[3] - bbox[1];
  7739. this.ctx.rect(bbox[0], bbox[1], width, height);
  7740. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  7741. this.clip();
  7742. this.endPath();
  7743. }
  7744. }
  7745. paintFormXObjectEnd() {
  7746. if (!this.contentVisible) {
  7747. return;
  7748. }
  7749. this.restore();
  7750. this.baseTransform = this.baseTransformStack.pop();
  7751. }
  7752. beginGroup(group) {
  7753. if (!this.contentVisible) {
  7754. return;
  7755. }
  7756. this.save();
  7757. if (this.inSMaskMode) {
  7758. this.endSMaskMode();
  7759. this.current.activeSMask = null;
  7760. }
  7761. const currentCtx = this.ctx;
  7762. if (!group.isolated) {
  7763. (0, _util.info)("TODO: Support non-isolated groups.");
  7764. }
  7765. if (group.knockout) {
  7766. (0, _util.warn)("Knockout groups not supported.");
  7767. }
  7768. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  7769. if (group.matrix) {
  7770. currentCtx.transform(...group.matrix);
  7771. }
  7772. if (!group.bbox) {
  7773. throw new Error("Bounding box is required.");
  7774. }
  7775. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  7776. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  7777. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  7778. const offsetX = Math.floor(bounds[0]);
  7779. const offsetY = Math.floor(bounds[1]);
  7780. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7781. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7782. let scaleX = 1,
  7783. scaleY = 1;
  7784. if (drawnWidth > MAX_GROUP_SIZE) {
  7785. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7786. drawnWidth = MAX_GROUP_SIZE;
  7787. }
  7788. if (drawnHeight > MAX_GROUP_SIZE) {
  7789. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7790. drawnHeight = MAX_GROUP_SIZE;
  7791. }
  7792. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  7793. let cacheId = "groupAt" + this.groupLevel;
  7794. if (group.smask) {
  7795. cacheId += "_smask_" + this.smaskCounter++ % 2;
  7796. }
  7797. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  7798. const groupCtx = scratchCanvas.context;
  7799. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7800. groupCtx.translate(-offsetX, -offsetY);
  7801. groupCtx.transform(...currentTransform);
  7802. if (group.smask) {
  7803. this.smaskStack.push({
  7804. canvas: scratchCanvas.canvas,
  7805. context: groupCtx,
  7806. offsetX,
  7807. offsetY,
  7808. scaleX,
  7809. scaleY,
  7810. subtype: group.smask.subtype,
  7811. backdrop: group.smask.backdrop,
  7812. transferMap: group.smask.transferMap || null,
  7813. startTransformInverse: null
  7814. });
  7815. } else {
  7816. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7817. currentCtx.translate(offsetX, offsetY);
  7818. currentCtx.scale(scaleX, scaleY);
  7819. currentCtx.save();
  7820. }
  7821. copyCtxState(currentCtx, groupCtx);
  7822. this.ctx = groupCtx;
  7823. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  7824. this.groupStack.push(currentCtx);
  7825. this.groupLevel++;
  7826. }
  7827. endGroup(group) {
  7828. if (!this.contentVisible) {
  7829. return;
  7830. }
  7831. this.groupLevel--;
  7832. const groupCtx = this.ctx;
  7833. const ctx = this.groupStack.pop();
  7834. this.ctx = ctx;
  7835. this.ctx.imageSmoothingEnabled = false;
  7836. if (group.smask) {
  7837. this.tempSMask = this.smaskStack.pop();
  7838. this.restore();
  7839. } else {
  7840. this.ctx.restore();
  7841. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  7842. this.restore();
  7843. this.ctx.save();
  7844. this.ctx.setTransform(...currentMtx);
  7845. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  7846. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7847. this.ctx.restore();
  7848. this.compose(dirtyBox);
  7849. }
  7850. }
  7851. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  7852. this.#restoreInitialState();
  7853. resetCtxToDefault(this.ctx);
  7854. this.ctx.save();
  7855. this.save();
  7856. if (this.baseTransform) {
  7857. this.ctx.setTransform(...this.baseTransform);
  7858. }
  7859. if (Array.isArray(rect) && rect.length === 4) {
  7860. const width = rect[2] - rect[0];
  7861. const height = rect[3] - rect[1];
  7862. if (hasOwnCanvas && this.annotationCanvasMap) {
  7863. transform = transform.slice();
  7864. transform[4] -= rect[0];
  7865. transform[5] -= rect[1];
  7866. rect = rect.slice();
  7867. rect[0] = rect[1] = 0;
  7868. rect[2] = width;
  7869. rect[3] = height;
  7870. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  7871. const {
  7872. viewportScale
  7873. } = this;
  7874. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  7875. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  7876. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  7877. const {
  7878. canvas,
  7879. context
  7880. } = this.annotationCanvas;
  7881. this.annotationCanvasMap.set(id, canvas);
  7882. this.annotationCanvas.savedCtx = this.ctx;
  7883. this.ctx = context;
  7884. this.ctx.save();
  7885. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  7886. resetCtxToDefault(this.ctx);
  7887. } else {
  7888. resetCtxToDefault(this.ctx);
  7889. this.ctx.rect(rect[0], rect[1], width, height);
  7890. this.ctx.clip();
  7891. this.endPath();
  7892. }
  7893. }
  7894. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  7895. this.transform(...transform);
  7896. this.transform(...matrix);
  7897. }
  7898. endAnnotation() {
  7899. if (this.annotationCanvas) {
  7900. this.ctx.restore();
  7901. this.#drawFilter();
  7902. this.ctx = this.annotationCanvas.savedCtx;
  7903. delete this.annotationCanvas.savedCtx;
  7904. delete this.annotationCanvas;
  7905. }
  7906. }
  7907. paintImageMaskXObject(img) {
  7908. if (!this.contentVisible) {
  7909. return;
  7910. }
  7911. const count = img.count;
  7912. img = this.getObject(img.data, img);
  7913. img.count = count;
  7914. const ctx = this.ctx;
  7915. const glyph = this.processingType3;
  7916. if (glyph) {
  7917. if (glyph.compiled === undefined) {
  7918. glyph.compiled = compileType3Glyph(img);
  7919. }
  7920. if (glyph.compiled) {
  7921. glyph.compiled(ctx);
  7922. return;
  7923. }
  7924. }
  7925. const mask = this._createMaskCanvas(img);
  7926. const maskCanvas = mask.canvas;
  7927. ctx.save();
  7928. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7929. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  7930. ctx.restore();
  7931. this.compose();
  7932. }
  7933. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  7934. if (!this.contentVisible) {
  7935. return;
  7936. }
  7937. img = this.getObject(img.data, img);
  7938. const ctx = this.ctx;
  7939. ctx.save();
  7940. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  7941. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  7942. const mask = this._createMaskCanvas(img);
  7943. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  7944. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  7945. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  7946. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  7947. ctx.drawImage(mask.canvas, x, y);
  7948. }
  7949. ctx.restore();
  7950. this.compose();
  7951. }
  7952. paintImageMaskXObjectGroup(images) {
  7953. if (!this.contentVisible) {
  7954. return;
  7955. }
  7956. const ctx = this.ctx;
  7957. const fillColor = this.current.fillColor;
  7958. const isPatternFill = this.current.patternFill;
  7959. for (const image of images) {
  7960. const {
  7961. data,
  7962. width,
  7963. height,
  7964. transform
  7965. } = image;
  7966. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  7967. const maskCtx = maskCanvas.context;
  7968. maskCtx.save();
  7969. const img = this.getObject(data, image);
  7970. putBinaryImageMask(maskCtx, img);
  7971. maskCtx.globalCompositeOperation = "source-in";
  7972. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  7973. maskCtx.fillRect(0, 0, width, height);
  7974. maskCtx.restore();
  7975. ctx.save();
  7976. ctx.transform(...transform);
  7977. ctx.scale(1, -1);
  7978. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  7979. ctx.restore();
  7980. }
  7981. this.compose();
  7982. }
  7983. paintImageXObject(objId) {
  7984. if (!this.contentVisible) {
  7985. return;
  7986. }
  7987. const imgData = this.getObject(objId);
  7988. if (!imgData) {
  7989. (0, _util.warn)("Dependent image isn't ready yet");
  7990. return;
  7991. }
  7992. this.paintInlineImageXObject(imgData);
  7993. }
  7994. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  7995. if (!this.contentVisible) {
  7996. return;
  7997. }
  7998. const imgData = this.getObject(objId);
  7999. if (!imgData) {
  8000. (0, _util.warn)("Dependent image isn't ready yet");
  8001. return;
  8002. }
  8003. const width = imgData.width;
  8004. const height = imgData.height;
  8005. const map = [];
  8006. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  8007. map.push({
  8008. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  8009. x: 0,
  8010. y: 0,
  8011. w: width,
  8012. h: height
  8013. });
  8014. }
  8015. this.paintInlineImageXObjectGroup(imgData, map);
  8016. }
  8017. applyTransferMapsToCanvas(ctx) {
  8018. if (this.current.transferMaps !== "none") {
  8019. ctx.filter = this.current.transferMaps;
  8020. ctx.drawImage(ctx.canvas, 0, 0);
  8021. ctx.filter = "none";
  8022. }
  8023. return ctx.canvas;
  8024. }
  8025. applyTransferMapsToBitmap(imgData) {
  8026. if (this.current.transferMaps === "none") {
  8027. return imgData.bitmap;
  8028. }
  8029. const {
  8030. bitmap,
  8031. width,
  8032. height
  8033. } = imgData;
  8034. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  8035. const tmpCtx = tmpCanvas.context;
  8036. tmpCtx.filter = this.current.transferMaps;
  8037. tmpCtx.drawImage(bitmap, 0, 0);
  8038. tmpCtx.filter = "none";
  8039. return tmpCanvas.canvas;
  8040. }
  8041. paintInlineImageXObject(imgData) {
  8042. if (!this.contentVisible) {
  8043. return;
  8044. }
  8045. const width = imgData.width;
  8046. const height = imgData.height;
  8047. const ctx = this.ctx;
  8048. this.save();
  8049. if (!_util.isNodeJS) {
  8050. const {
  8051. filter
  8052. } = ctx;
  8053. if (filter !== "none" && filter !== "") {
  8054. ctx.filter = "none";
  8055. }
  8056. }
  8057. ctx.scale(1 / width, -1 / height);
  8058. let imgToPaint;
  8059. if (imgData.bitmap) {
  8060. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  8061. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  8062. imgToPaint = imgData;
  8063. } else {
  8064. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  8065. const tmpCtx = tmpCanvas.context;
  8066. putBinaryImageData(tmpCtx, imgData);
  8067. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  8068. }
  8069. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  8070. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  8071. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  8072. this.compose();
  8073. this.restore();
  8074. }
  8075. paintInlineImageXObjectGroup(imgData, map) {
  8076. if (!this.contentVisible) {
  8077. return;
  8078. }
  8079. const ctx = this.ctx;
  8080. let imgToPaint;
  8081. if (imgData.bitmap) {
  8082. imgToPaint = imgData.bitmap;
  8083. } else {
  8084. const w = imgData.width;
  8085. const h = imgData.height;
  8086. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  8087. const tmpCtx = tmpCanvas.context;
  8088. putBinaryImageData(tmpCtx, imgData);
  8089. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  8090. }
  8091. for (const entry of map) {
  8092. ctx.save();
  8093. ctx.transform(...entry.transform);
  8094. ctx.scale(1, -1);
  8095. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8096. ctx.restore();
  8097. }
  8098. this.compose();
  8099. }
  8100. paintSolidColorImageMask() {
  8101. if (!this.contentVisible) {
  8102. return;
  8103. }
  8104. this.ctx.fillRect(0, 0, 1, 1);
  8105. this.compose();
  8106. }
  8107. markPoint(tag) {}
  8108. markPointProps(tag, properties) {}
  8109. beginMarkedContent(tag) {
  8110. this.markedContentStack.push({
  8111. visible: true
  8112. });
  8113. }
  8114. beginMarkedContentProps(tag, properties) {
  8115. if (tag === "OC") {
  8116. this.markedContentStack.push({
  8117. visible: this.optionalContentConfig.isVisible(properties)
  8118. });
  8119. } else {
  8120. this.markedContentStack.push({
  8121. visible: true
  8122. });
  8123. }
  8124. this.contentVisible = this.isContentVisible();
  8125. }
  8126. endMarkedContent() {
  8127. this.markedContentStack.pop();
  8128. this.contentVisible = this.isContentVisible();
  8129. }
  8130. beginCompat() {}
  8131. endCompat() {}
  8132. consumePath(clipBox) {
  8133. const isEmpty = this.current.isEmptyClip();
  8134. if (this.pendingClip) {
  8135. this.current.updateClipFromPath();
  8136. }
  8137. if (!this.pendingClip) {
  8138. this.compose(clipBox);
  8139. }
  8140. const ctx = this.ctx;
  8141. if (this.pendingClip) {
  8142. if (!isEmpty) {
  8143. if (this.pendingClip === EO_CLIP) {
  8144. ctx.clip("evenodd");
  8145. } else {
  8146. ctx.clip();
  8147. }
  8148. }
  8149. this.pendingClip = null;
  8150. }
  8151. this.current.startNewPathAndClipBox(this.current.clipBox);
  8152. ctx.beginPath();
  8153. }
  8154. getSinglePixelWidth() {
  8155. if (!this._cachedGetSinglePixelWidth) {
  8156. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  8157. if (m[1] === 0 && m[2] === 0) {
  8158. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  8159. } else {
  8160. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  8161. const normX = Math.hypot(m[0], m[2]);
  8162. const normY = Math.hypot(m[1], m[3]);
  8163. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  8164. }
  8165. }
  8166. return this._cachedGetSinglePixelWidth;
  8167. }
  8168. getScaleForStroking() {
  8169. if (this._cachedScaleForStroking[0] === -1) {
  8170. const {
  8171. lineWidth
  8172. } = this.current;
  8173. const {
  8174. a,
  8175. b,
  8176. c,
  8177. d
  8178. } = this.ctx.getTransform();
  8179. let scaleX, scaleY;
  8180. if (b === 0 && c === 0) {
  8181. const normX = Math.abs(a);
  8182. const normY = Math.abs(d);
  8183. if (normX === normY) {
  8184. if (lineWidth === 0) {
  8185. scaleX = scaleY = 1 / normX;
  8186. } else {
  8187. const scaledLineWidth = normX * lineWidth;
  8188. scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
  8189. }
  8190. } else if (lineWidth === 0) {
  8191. scaleX = 1 / normX;
  8192. scaleY = 1 / normY;
  8193. } else {
  8194. const scaledXLineWidth = normX * lineWidth;
  8195. const scaledYLineWidth = normY * lineWidth;
  8196. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  8197. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  8198. }
  8199. } else {
  8200. const absDet = Math.abs(a * d - b * c);
  8201. const normX = Math.hypot(a, b);
  8202. const normY = Math.hypot(c, d);
  8203. if (lineWidth === 0) {
  8204. scaleX = normY / absDet;
  8205. scaleY = normX / absDet;
  8206. } else {
  8207. const baseArea = lineWidth * absDet;
  8208. scaleX = normY > baseArea ? normY / baseArea : 1;
  8209. scaleY = normX > baseArea ? normX / baseArea : 1;
  8210. }
  8211. }
  8212. this._cachedScaleForStroking[0] = scaleX;
  8213. this._cachedScaleForStroking[1] = scaleY;
  8214. }
  8215. return this._cachedScaleForStroking;
  8216. }
  8217. rescaleAndStroke(saveRestore) {
  8218. const {
  8219. ctx
  8220. } = this;
  8221. const {
  8222. lineWidth
  8223. } = this.current;
  8224. const [scaleX, scaleY] = this.getScaleForStroking();
  8225. ctx.lineWidth = lineWidth || 1;
  8226. if (scaleX === 1 && scaleY === 1) {
  8227. ctx.stroke();
  8228. return;
  8229. }
  8230. const dashes = ctx.getLineDash();
  8231. if (saveRestore) {
  8232. ctx.save();
  8233. }
  8234. ctx.scale(scaleX, scaleY);
  8235. if (dashes.length > 0) {
  8236. const scale = Math.max(scaleX, scaleY);
  8237. ctx.setLineDash(dashes.map(x => x / scale));
  8238. ctx.lineDashOffset /= scale;
  8239. }
  8240. ctx.stroke();
  8241. if (saveRestore) {
  8242. ctx.restore();
  8243. }
  8244. }
  8245. isContentVisible() {
  8246. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  8247. if (!this.markedContentStack[i].visible) {
  8248. return false;
  8249. }
  8250. }
  8251. return true;
  8252. }
  8253. }
  8254. exports.CanvasGraphics = CanvasGraphics;
  8255. for (const op in _util.OPS) {
  8256. if (CanvasGraphics.prototype[op] !== undefined) {
  8257. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  8258. }
  8259. }
  8260. /***/ }),
  8261. /* 12 */
  8262. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8263. Object.defineProperty(exports, "__esModule", ({
  8264. value: true
  8265. }));
  8266. exports.TilingPattern = exports.PathType = void 0;
  8267. exports.getShadingPattern = getShadingPattern;
  8268. var _util = __w_pdfjs_require__(1);
  8269. var _display_utils = __w_pdfjs_require__(6);
  8270. const PathType = {
  8271. FILL: "Fill",
  8272. STROKE: "Stroke",
  8273. SHADING: "Shading"
  8274. };
  8275. exports.PathType = PathType;
  8276. function applyBoundingBox(ctx, bbox) {
  8277. if (!bbox) {
  8278. return;
  8279. }
  8280. const width = bbox[2] - bbox[0];
  8281. const height = bbox[3] - bbox[1];
  8282. const region = new Path2D();
  8283. region.rect(bbox[0], bbox[1], width, height);
  8284. ctx.clip(region);
  8285. }
  8286. class BaseShadingPattern {
  8287. constructor() {
  8288. if (this.constructor === BaseShadingPattern) {
  8289. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  8290. }
  8291. }
  8292. getPattern() {
  8293. (0, _util.unreachable)("Abstract method `getPattern` called.");
  8294. }
  8295. }
  8296. class RadialAxialShadingPattern extends BaseShadingPattern {
  8297. constructor(IR) {
  8298. super();
  8299. this._type = IR[1];
  8300. this._bbox = IR[2];
  8301. this._colorStops = IR[3];
  8302. this._p0 = IR[4];
  8303. this._p1 = IR[5];
  8304. this._r0 = IR[6];
  8305. this._r1 = IR[7];
  8306. this.matrix = null;
  8307. }
  8308. _createGradient(ctx) {
  8309. let grad;
  8310. if (this._type === "axial") {
  8311. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  8312. } else if (this._type === "radial") {
  8313. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  8314. }
  8315. for (const colorStop of this._colorStops) {
  8316. grad.addColorStop(colorStop[0], colorStop[1]);
  8317. }
  8318. return grad;
  8319. }
  8320. getPattern(ctx, owner, inverse, pathType) {
  8321. let pattern;
  8322. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  8323. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  8324. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  8325. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  8326. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  8327. const tmpCtx = tmpCanvas.context;
  8328. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  8329. tmpCtx.beginPath();
  8330. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  8331. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  8332. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  8333. tmpCtx.transform(...owner.baseTransform);
  8334. if (this.matrix) {
  8335. tmpCtx.transform(...this.matrix);
  8336. }
  8337. applyBoundingBox(tmpCtx, this._bbox);
  8338. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  8339. tmpCtx.fill();
  8340. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  8341. const domMatrix = new DOMMatrix(inverse);
  8342. pattern.setTransform(domMatrix);
  8343. } else {
  8344. applyBoundingBox(ctx, this._bbox);
  8345. pattern = this._createGradient(ctx);
  8346. }
  8347. return pattern;
  8348. }
  8349. }
  8350. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  8351. const coords = context.coords,
  8352. colors = context.colors;
  8353. const bytes = data.data,
  8354. rowSize = data.width * 4;
  8355. let tmp;
  8356. if (coords[p1 + 1] > coords[p2 + 1]) {
  8357. tmp = p1;
  8358. p1 = p2;
  8359. p2 = tmp;
  8360. tmp = c1;
  8361. c1 = c2;
  8362. c2 = tmp;
  8363. }
  8364. if (coords[p2 + 1] > coords[p3 + 1]) {
  8365. tmp = p2;
  8366. p2 = p3;
  8367. p3 = tmp;
  8368. tmp = c2;
  8369. c2 = c3;
  8370. c3 = tmp;
  8371. }
  8372. if (coords[p1 + 1] > coords[p2 + 1]) {
  8373. tmp = p1;
  8374. p1 = p2;
  8375. p2 = tmp;
  8376. tmp = c1;
  8377. c1 = c2;
  8378. c2 = tmp;
  8379. }
  8380. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  8381. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  8382. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  8383. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  8384. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  8385. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  8386. if (y1 >= y3) {
  8387. return;
  8388. }
  8389. const c1r = colors[c1],
  8390. c1g = colors[c1 + 1],
  8391. c1b = colors[c1 + 2];
  8392. const c2r = colors[c2],
  8393. c2g = colors[c2 + 1],
  8394. c2b = colors[c2 + 2];
  8395. const c3r = colors[c3],
  8396. c3g = colors[c3 + 1],
  8397. c3b = colors[c3 + 2];
  8398. const minY = Math.round(y1),
  8399. maxY = Math.round(y3);
  8400. let xa, car, cag, cab;
  8401. let xb, cbr, cbg, cbb;
  8402. for (let y = minY; y <= maxY; y++) {
  8403. if (y < y2) {
  8404. const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
  8405. xa = x1 - (x1 - x2) * k;
  8406. car = c1r - (c1r - c2r) * k;
  8407. cag = c1g - (c1g - c2g) * k;
  8408. cab = c1b - (c1b - c2b) * k;
  8409. } else {
  8410. let k;
  8411. if (y > y3) {
  8412. k = 1;
  8413. } else if (y2 === y3) {
  8414. k = 0;
  8415. } else {
  8416. k = (y2 - y) / (y2 - y3);
  8417. }
  8418. xa = x2 - (x2 - x3) * k;
  8419. car = c2r - (c2r - c3r) * k;
  8420. cag = c2g - (c2g - c3g) * k;
  8421. cab = c2b - (c2b - c3b) * k;
  8422. }
  8423. let k;
  8424. if (y < y1) {
  8425. k = 0;
  8426. } else if (y > y3) {
  8427. k = 1;
  8428. } else {
  8429. k = (y1 - y) / (y1 - y3);
  8430. }
  8431. xb = x1 - (x1 - x3) * k;
  8432. cbr = c1r - (c1r - c3r) * k;
  8433. cbg = c1g - (c1g - c3g) * k;
  8434. cbb = c1b - (c1b - c3b) * k;
  8435. const x1_ = Math.round(Math.min(xa, xb));
  8436. const x2_ = Math.round(Math.max(xa, xb));
  8437. let j = rowSize * y + x1_ * 4;
  8438. for (let x = x1_; x <= x2_; x++) {
  8439. k = (xa - x) / (xa - xb);
  8440. if (k < 0) {
  8441. k = 0;
  8442. } else if (k > 1) {
  8443. k = 1;
  8444. }
  8445. bytes[j++] = car - (car - cbr) * k | 0;
  8446. bytes[j++] = cag - (cag - cbg) * k | 0;
  8447. bytes[j++] = cab - (cab - cbb) * k | 0;
  8448. bytes[j++] = 255;
  8449. }
  8450. }
  8451. }
  8452. function drawFigure(data, figure, context) {
  8453. const ps = figure.coords;
  8454. const cs = figure.colors;
  8455. let i, ii;
  8456. switch (figure.type) {
  8457. case "lattice":
  8458. const verticesPerRow = figure.verticesPerRow;
  8459. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  8460. const cols = verticesPerRow - 1;
  8461. for (i = 0; i < rows; i++) {
  8462. let q = i * verticesPerRow;
  8463. for (let j = 0; j < cols; j++, q++) {
  8464. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  8465. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  8466. }
  8467. }
  8468. break;
  8469. case "triangles":
  8470. for (i = 0, ii = ps.length; i < ii; i += 3) {
  8471. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  8472. }
  8473. break;
  8474. default:
  8475. throw new Error("illegal figure");
  8476. }
  8477. }
  8478. class MeshShadingPattern extends BaseShadingPattern {
  8479. constructor(IR) {
  8480. super();
  8481. this._coords = IR[2];
  8482. this._colors = IR[3];
  8483. this._figures = IR[4];
  8484. this._bounds = IR[5];
  8485. this._bbox = IR[7];
  8486. this._background = IR[8];
  8487. this.matrix = null;
  8488. }
  8489. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  8490. const EXPECTED_SCALE = 1.1;
  8491. const MAX_PATTERN_SIZE = 3000;
  8492. const BORDER_SIZE = 2;
  8493. const offsetX = Math.floor(this._bounds[0]);
  8494. const offsetY = Math.floor(this._bounds[1]);
  8495. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  8496. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  8497. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  8498. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  8499. const scaleX = boundsWidth / width;
  8500. const scaleY = boundsHeight / height;
  8501. const context = {
  8502. coords: this._coords,
  8503. colors: this._colors,
  8504. offsetX: -offsetX,
  8505. offsetY: -offsetY,
  8506. scaleX: 1 / scaleX,
  8507. scaleY: 1 / scaleY
  8508. };
  8509. const paddedWidth = width + BORDER_SIZE * 2;
  8510. const paddedHeight = height + BORDER_SIZE * 2;
  8511. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  8512. const tmpCtx = tmpCanvas.context;
  8513. const data = tmpCtx.createImageData(width, height);
  8514. if (backgroundColor) {
  8515. const bytes = data.data;
  8516. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  8517. bytes[i] = backgroundColor[0];
  8518. bytes[i + 1] = backgroundColor[1];
  8519. bytes[i + 2] = backgroundColor[2];
  8520. bytes[i + 3] = 255;
  8521. }
  8522. }
  8523. for (const figure of this._figures) {
  8524. drawFigure(data, figure, context);
  8525. }
  8526. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  8527. const canvas = tmpCanvas.canvas;
  8528. return {
  8529. canvas,
  8530. offsetX: offsetX - BORDER_SIZE * scaleX,
  8531. offsetY: offsetY - BORDER_SIZE * scaleY,
  8532. scaleX,
  8533. scaleY
  8534. };
  8535. }
  8536. getPattern(ctx, owner, inverse, pathType) {
  8537. applyBoundingBox(ctx, this._bbox);
  8538. let scale;
  8539. if (pathType === PathType.SHADING) {
  8540. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  8541. } else {
  8542. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  8543. if (this.matrix) {
  8544. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  8545. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  8546. }
  8547. }
  8548. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  8549. if (pathType !== PathType.SHADING) {
  8550. ctx.setTransform(...owner.baseTransform);
  8551. if (this.matrix) {
  8552. ctx.transform(...this.matrix);
  8553. }
  8554. }
  8555. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  8556. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  8557. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  8558. }
  8559. }
  8560. class DummyShadingPattern extends BaseShadingPattern {
  8561. getPattern() {
  8562. return "hotpink";
  8563. }
  8564. }
  8565. function getShadingPattern(IR) {
  8566. switch (IR[0]) {
  8567. case "RadialAxial":
  8568. return new RadialAxialShadingPattern(IR);
  8569. case "Mesh":
  8570. return new MeshShadingPattern(IR);
  8571. case "Dummy":
  8572. return new DummyShadingPattern();
  8573. }
  8574. throw new Error(`Unknown IR type: ${IR[0]}`);
  8575. }
  8576. const PaintType = {
  8577. COLORED: 1,
  8578. UNCOLORED: 2
  8579. };
  8580. class TilingPattern {
  8581. static MAX_PATTERN_SIZE = 3000;
  8582. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  8583. this.operatorList = IR[2];
  8584. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  8585. this.bbox = IR[4];
  8586. this.xstep = IR[5];
  8587. this.ystep = IR[6];
  8588. this.paintType = IR[7];
  8589. this.tilingType = IR[8];
  8590. this.color = color;
  8591. this.ctx = ctx;
  8592. this.canvasGraphicsFactory = canvasGraphicsFactory;
  8593. this.baseTransform = baseTransform;
  8594. }
  8595. createPatternCanvas(owner) {
  8596. const operatorList = this.operatorList;
  8597. const bbox = this.bbox;
  8598. const xstep = this.xstep;
  8599. const ystep = this.ystep;
  8600. const paintType = this.paintType;
  8601. const tilingType = this.tilingType;
  8602. const color = this.color;
  8603. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  8604. (0, _util.info)("TilingType: " + tilingType);
  8605. const x0 = bbox[0],
  8606. y0 = bbox[1],
  8607. x1 = bbox[2],
  8608. y1 = bbox[3];
  8609. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  8610. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  8611. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  8612. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  8613. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  8614. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  8615. const tmpCtx = tmpCanvas.context;
  8616. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  8617. graphics.groupLevel = owner.groupLevel;
  8618. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  8619. let adjustedX0 = x0;
  8620. let adjustedY0 = y0;
  8621. let adjustedX1 = x1;
  8622. let adjustedY1 = y1;
  8623. if (x0 < 0) {
  8624. adjustedX0 = 0;
  8625. adjustedX1 += Math.abs(x0);
  8626. }
  8627. if (y0 < 0) {
  8628. adjustedY0 = 0;
  8629. adjustedY1 += Math.abs(y0);
  8630. }
  8631. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  8632. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  8633. tmpCtx.save();
  8634. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  8635. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  8636. graphics.executeOperatorList(operatorList);
  8637. graphics.endDrawing();
  8638. return {
  8639. canvas: tmpCanvas.canvas,
  8640. scaleX: dimx.scale,
  8641. scaleY: dimy.scale,
  8642. offsetX: adjustedX0,
  8643. offsetY: adjustedY0
  8644. };
  8645. }
  8646. getSizeAndScale(step, realOutputSize, scale) {
  8647. step = Math.abs(step);
  8648. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  8649. let size = Math.ceil(step * scale);
  8650. if (size >= maxSize) {
  8651. size = maxSize;
  8652. } else {
  8653. scale = size / step;
  8654. }
  8655. return {
  8656. scale,
  8657. size
  8658. };
  8659. }
  8660. clipBbox(graphics, x0, y0, x1, y1) {
  8661. const bboxWidth = x1 - x0;
  8662. const bboxHeight = y1 - y0;
  8663. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  8664. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  8665. graphics.clip();
  8666. graphics.endPath();
  8667. }
  8668. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  8669. const context = graphics.ctx,
  8670. current = graphics.current;
  8671. switch (paintType) {
  8672. case PaintType.COLORED:
  8673. const ctx = this.ctx;
  8674. context.fillStyle = ctx.fillStyle;
  8675. context.strokeStyle = ctx.strokeStyle;
  8676. current.fillColor = ctx.fillStyle;
  8677. current.strokeColor = ctx.strokeStyle;
  8678. break;
  8679. case PaintType.UNCOLORED:
  8680. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  8681. context.fillStyle = cssColor;
  8682. context.strokeStyle = cssColor;
  8683. current.fillColor = cssColor;
  8684. current.strokeColor = cssColor;
  8685. break;
  8686. default:
  8687. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  8688. }
  8689. }
  8690. getPattern(ctx, owner, inverse, pathType) {
  8691. let matrix = inverse;
  8692. if (pathType !== PathType.SHADING) {
  8693. matrix = _util.Util.transform(matrix, owner.baseTransform);
  8694. if (this.matrix) {
  8695. matrix = _util.Util.transform(matrix, this.matrix);
  8696. }
  8697. }
  8698. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  8699. let domMatrix = new DOMMatrix(matrix);
  8700. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  8701. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  8702. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  8703. pattern.setTransform(domMatrix);
  8704. return pattern;
  8705. }
  8706. }
  8707. exports.TilingPattern = TilingPattern;
  8708. /***/ }),
  8709. /* 13 */
  8710. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8711. Object.defineProperty(exports, "__esModule", ({
  8712. value: true
  8713. }));
  8714. exports.convertBlackAndWhiteToRGBA = convertBlackAndWhiteToRGBA;
  8715. exports.convertToRGBA = convertToRGBA;
  8716. exports.grayToRGBA = grayToRGBA;
  8717. var _util = __w_pdfjs_require__(1);
  8718. function convertToRGBA(params) {
  8719. switch (params.kind) {
  8720. case _util.ImageKind.GRAYSCALE_1BPP:
  8721. return convertBlackAndWhiteToRGBA(params);
  8722. case _util.ImageKind.RGB_24BPP:
  8723. return convertRGBToRGBA(params);
  8724. }
  8725. return null;
  8726. }
  8727. function convertBlackAndWhiteToRGBA({
  8728. src,
  8729. srcPos = 0,
  8730. dest,
  8731. width,
  8732. height,
  8733. nonBlackColor = 0xffffffff,
  8734. inverseDecode = false
  8735. }) {
  8736. const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  8737. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  8738. const widthInSource = width >> 3;
  8739. const widthRemainder = width & 7;
  8740. const srcLength = src.length;
  8741. dest = new Uint32Array(dest.buffer);
  8742. let destPos = 0;
  8743. for (let i = 0; i < height; i++) {
  8744. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  8745. const elem = srcPos < srcLength ? src[srcPos] : 255;
  8746. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  8747. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  8748. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  8749. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  8750. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  8751. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  8752. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  8753. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  8754. }
  8755. if (widthRemainder === 0) {
  8756. continue;
  8757. }
  8758. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  8759. for (let j = 0; j < widthRemainder; j++) {
  8760. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  8761. }
  8762. }
  8763. return {
  8764. srcPos,
  8765. destPos
  8766. };
  8767. }
  8768. function convertRGBToRGBA({
  8769. src,
  8770. srcPos = 0,
  8771. dest,
  8772. destPos = 0,
  8773. width,
  8774. height
  8775. }) {
  8776. let i = 0;
  8777. const len32 = src.length >> 2;
  8778. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  8779. if (_util.FeatureTest.isLittleEndian) {
  8780. for (; i < len32 - 2; i += 3, destPos += 4) {
  8781. const s1 = src32[i];
  8782. const s2 = src32[i + 1];
  8783. const s3 = src32[i + 2];
  8784. dest[destPos] = s1 | 0xff000000;
  8785. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  8786. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  8787. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  8788. }
  8789. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  8790. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  8791. }
  8792. } else {
  8793. for (; i < len32 - 2; i += 3, destPos += 4) {
  8794. const s1 = src32[i];
  8795. const s2 = src32[i + 1];
  8796. const s3 = src32[i + 2];
  8797. dest[destPos] = s1 | 0xff;
  8798. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  8799. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  8800. dest[destPos + 3] = s3 << 8 | 0xff;
  8801. }
  8802. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  8803. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  8804. }
  8805. }
  8806. return {
  8807. srcPos,
  8808. destPos
  8809. };
  8810. }
  8811. function grayToRGBA(src, dest) {
  8812. if (_util.FeatureTest.isLittleEndian) {
  8813. for (let i = 0, ii = src.length; i < ii; i++) {
  8814. dest[i] = src[i] * 0x10101 | 0xff000000;
  8815. }
  8816. } else {
  8817. for (let i = 0, ii = src.length; i < ii; i++) {
  8818. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  8819. }
  8820. }
  8821. }
  8822. /***/ }),
  8823. /* 14 */
  8824. /***/ ((__unused_webpack_module, exports) => {
  8825. Object.defineProperty(exports, "__esModule", ({
  8826. value: true
  8827. }));
  8828. exports.GlobalWorkerOptions = void 0;
  8829. const GlobalWorkerOptions = Object.create(null);
  8830. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  8831. GlobalWorkerOptions.workerPort = null;
  8832. GlobalWorkerOptions.workerSrc = "";
  8833. /***/ }),
  8834. /* 15 */
  8835. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8836. Object.defineProperty(exports, "__esModule", ({
  8837. value: true
  8838. }));
  8839. exports.MessageHandler = void 0;
  8840. var _util = __w_pdfjs_require__(1);
  8841. const CallbackKind = {
  8842. UNKNOWN: 0,
  8843. DATA: 1,
  8844. ERROR: 2
  8845. };
  8846. const StreamKind = {
  8847. UNKNOWN: 0,
  8848. CANCEL: 1,
  8849. CANCEL_COMPLETE: 2,
  8850. CLOSE: 3,
  8851. ENQUEUE: 4,
  8852. ERROR: 5,
  8853. PULL: 6,
  8854. PULL_COMPLETE: 7,
  8855. START_COMPLETE: 8
  8856. };
  8857. function wrapReason(reason) {
  8858. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  8859. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  8860. }
  8861. switch (reason.name) {
  8862. case "AbortException":
  8863. return new _util.AbortException(reason.message);
  8864. case "MissingPDFException":
  8865. return new _util.MissingPDFException(reason.message);
  8866. case "PasswordException":
  8867. return new _util.PasswordException(reason.message, reason.code);
  8868. case "UnexpectedResponseException":
  8869. return new _util.UnexpectedResponseException(reason.message, reason.status);
  8870. case "UnknownErrorException":
  8871. return new _util.UnknownErrorException(reason.message, reason.details);
  8872. default:
  8873. return new _util.UnknownErrorException(reason.message, reason.toString());
  8874. }
  8875. }
  8876. class MessageHandler {
  8877. constructor(sourceName, targetName, comObj) {
  8878. this.sourceName = sourceName;
  8879. this.targetName = targetName;
  8880. this.comObj = comObj;
  8881. this.callbackId = 1;
  8882. this.streamId = 1;
  8883. this.streamSinks = Object.create(null);
  8884. this.streamControllers = Object.create(null);
  8885. this.callbackCapabilities = Object.create(null);
  8886. this.actionHandler = Object.create(null);
  8887. this._onComObjOnMessage = event => {
  8888. const data = event.data;
  8889. if (data.targetName !== this.sourceName) {
  8890. return;
  8891. }
  8892. if (data.stream) {
  8893. this.#processStreamMessage(data);
  8894. return;
  8895. }
  8896. if (data.callback) {
  8897. const callbackId = data.callbackId;
  8898. const capability = this.callbackCapabilities[callbackId];
  8899. if (!capability) {
  8900. throw new Error(`Cannot resolve callback ${callbackId}`);
  8901. }
  8902. delete this.callbackCapabilities[callbackId];
  8903. if (data.callback === CallbackKind.DATA) {
  8904. capability.resolve(data.data);
  8905. } else if (data.callback === CallbackKind.ERROR) {
  8906. capability.reject(wrapReason(data.reason));
  8907. } else {
  8908. throw new Error("Unexpected callback case");
  8909. }
  8910. return;
  8911. }
  8912. const action = this.actionHandler[data.action];
  8913. if (!action) {
  8914. throw new Error(`Unknown action from worker: ${data.action}`);
  8915. }
  8916. if (data.callbackId) {
  8917. const cbSourceName = this.sourceName;
  8918. const cbTargetName = data.sourceName;
  8919. new Promise(function (resolve) {
  8920. resolve(action(data.data));
  8921. }).then(function (result) {
  8922. comObj.postMessage({
  8923. sourceName: cbSourceName,
  8924. targetName: cbTargetName,
  8925. callback: CallbackKind.DATA,
  8926. callbackId: data.callbackId,
  8927. data: result
  8928. });
  8929. }, function (reason) {
  8930. comObj.postMessage({
  8931. sourceName: cbSourceName,
  8932. targetName: cbTargetName,
  8933. callback: CallbackKind.ERROR,
  8934. callbackId: data.callbackId,
  8935. reason: wrapReason(reason)
  8936. });
  8937. });
  8938. return;
  8939. }
  8940. if (data.streamId) {
  8941. this.#createStreamSink(data);
  8942. return;
  8943. }
  8944. action(data.data);
  8945. };
  8946. comObj.addEventListener("message", this._onComObjOnMessage);
  8947. }
  8948. on(actionName, handler) {
  8949. const ah = this.actionHandler;
  8950. if (ah[actionName]) {
  8951. throw new Error(`There is already an actionName called "${actionName}"`);
  8952. }
  8953. ah[actionName] = handler;
  8954. }
  8955. send(actionName, data, transfers) {
  8956. this.comObj.postMessage({
  8957. sourceName: this.sourceName,
  8958. targetName: this.targetName,
  8959. action: actionName,
  8960. data
  8961. }, transfers);
  8962. }
  8963. sendWithPromise(actionName, data, transfers) {
  8964. const callbackId = this.callbackId++;
  8965. const capability = new _util.PromiseCapability();
  8966. this.callbackCapabilities[callbackId] = capability;
  8967. try {
  8968. this.comObj.postMessage({
  8969. sourceName: this.sourceName,
  8970. targetName: this.targetName,
  8971. action: actionName,
  8972. callbackId,
  8973. data
  8974. }, transfers);
  8975. } catch (ex) {
  8976. capability.reject(ex);
  8977. }
  8978. return capability.promise;
  8979. }
  8980. sendWithStream(actionName, data, queueingStrategy, transfers) {
  8981. const streamId = this.streamId++,
  8982. sourceName = this.sourceName,
  8983. targetName = this.targetName,
  8984. comObj = this.comObj;
  8985. return new ReadableStream({
  8986. start: controller => {
  8987. const startCapability = new _util.PromiseCapability();
  8988. this.streamControllers[streamId] = {
  8989. controller,
  8990. startCall: startCapability,
  8991. pullCall: null,
  8992. cancelCall: null,
  8993. isClosed: false
  8994. };
  8995. comObj.postMessage({
  8996. sourceName,
  8997. targetName,
  8998. action: actionName,
  8999. streamId,
  9000. data,
  9001. desiredSize: controller.desiredSize
  9002. }, transfers);
  9003. return startCapability.promise;
  9004. },
  9005. pull: controller => {
  9006. const pullCapability = new _util.PromiseCapability();
  9007. this.streamControllers[streamId].pullCall = pullCapability;
  9008. comObj.postMessage({
  9009. sourceName,
  9010. targetName,
  9011. stream: StreamKind.PULL,
  9012. streamId,
  9013. desiredSize: controller.desiredSize
  9014. });
  9015. return pullCapability.promise;
  9016. },
  9017. cancel: reason => {
  9018. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  9019. const cancelCapability = new _util.PromiseCapability();
  9020. this.streamControllers[streamId].cancelCall = cancelCapability;
  9021. this.streamControllers[streamId].isClosed = true;
  9022. comObj.postMessage({
  9023. sourceName,
  9024. targetName,
  9025. stream: StreamKind.CANCEL,
  9026. streamId,
  9027. reason: wrapReason(reason)
  9028. });
  9029. return cancelCapability.promise;
  9030. }
  9031. }, queueingStrategy);
  9032. }
  9033. #createStreamSink(data) {
  9034. const streamId = data.streamId,
  9035. sourceName = this.sourceName,
  9036. targetName = data.sourceName,
  9037. comObj = this.comObj;
  9038. const self = this,
  9039. action = this.actionHandler[data.action];
  9040. const streamSink = {
  9041. enqueue(chunk, size = 1, transfers) {
  9042. if (this.isCancelled) {
  9043. return;
  9044. }
  9045. const lastDesiredSize = this.desiredSize;
  9046. this.desiredSize -= size;
  9047. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  9048. this.sinkCapability = new _util.PromiseCapability();
  9049. this.ready = this.sinkCapability.promise;
  9050. }
  9051. comObj.postMessage({
  9052. sourceName,
  9053. targetName,
  9054. stream: StreamKind.ENQUEUE,
  9055. streamId,
  9056. chunk
  9057. }, transfers);
  9058. },
  9059. close() {
  9060. if (this.isCancelled) {
  9061. return;
  9062. }
  9063. this.isCancelled = true;
  9064. comObj.postMessage({
  9065. sourceName,
  9066. targetName,
  9067. stream: StreamKind.CLOSE,
  9068. streamId
  9069. });
  9070. delete self.streamSinks[streamId];
  9071. },
  9072. error(reason) {
  9073. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  9074. if (this.isCancelled) {
  9075. return;
  9076. }
  9077. this.isCancelled = true;
  9078. comObj.postMessage({
  9079. sourceName,
  9080. targetName,
  9081. stream: StreamKind.ERROR,
  9082. streamId,
  9083. reason: wrapReason(reason)
  9084. });
  9085. },
  9086. sinkCapability: new _util.PromiseCapability(),
  9087. onPull: null,
  9088. onCancel: null,
  9089. isCancelled: false,
  9090. desiredSize: data.desiredSize,
  9091. ready: null
  9092. };
  9093. streamSink.sinkCapability.resolve();
  9094. streamSink.ready = streamSink.sinkCapability.promise;
  9095. this.streamSinks[streamId] = streamSink;
  9096. new Promise(function (resolve) {
  9097. resolve(action(data.data, streamSink));
  9098. }).then(function () {
  9099. comObj.postMessage({
  9100. sourceName,
  9101. targetName,
  9102. stream: StreamKind.START_COMPLETE,
  9103. streamId,
  9104. success: true
  9105. });
  9106. }, function (reason) {
  9107. comObj.postMessage({
  9108. sourceName,
  9109. targetName,
  9110. stream: StreamKind.START_COMPLETE,
  9111. streamId,
  9112. reason: wrapReason(reason)
  9113. });
  9114. });
  9115. }
  9116. #processStreamMessage(data) {
  9117. const streamId = data.streamId,
  9118. sourceName = this.sourceName,
  9119. targetName = data.sourceName,
  9120. comObj = this.comObj;
  9121. const streamController = this.streamControllers[streamId],
  9122. streamSink = this.streamSinks[streamId];
  9123. switch (data.stream) {
  9124. case StreamKind.START_COMPLETE:
  9125. if (data.success) {
  9126. streamController.startCall.resolve();
  9127. } else {
  9128. streamController.startCall.reject(wrapReason(data.reason));
  9129. }
  9130. break;
  9131. case StreamKind.PULL_COMPLETE:
  9132. if (data.success) {
  9133. streamController.pullCall.resolve();
  9134. } else {
  9135. streamController.pullCall.reject(wrapReason(data.reason));
  9136. }
  9137. break;
  9138. case StreamKind.PULL:
  9139. if (!streamSink) {
  9140. comObj.postMessage({
  9141. sourceName,
  9142. targetName,
  9143. stream: StreamKind.PULL_COMPLETE,
  9144. streamId,
  9145. success: true
  9146. });
  9147. break;
  9148. }
  9149. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  9150. streamSink.sinkCapability.resolve();
  9151. }
  9152. streamSink.desiredSize = data.desiredSize;
  9153. new Promise(function (resolve) {
  9154. resolve(streamSink.onPull?.());
  9155. }).then(function () {
  9156. comObj.postMessage({
  9157. sourceName,
  9158. targetName,
  9159. stream: StreamKind.PULL_COMPLETE,
  9160. streamId,
  9161. success: true
  9162. });
  9163. }, function (reason) {
  9164. comObj.postMessage({
  9165. sourceName,
  9166. targetName,
  9167. stream: StreamKind.PULL_COMPLETE,
  9168. streamId,
  9169. reason: wrapReason(reason)
  9170. });
  9171. });
  9172. break;
  9173. case StreamKind.ENQUEUE:
  9174. (0, _util.assert)(streamController, "enqueue should have stream controller");
  9175. if (streamController.isClosed) {
  9176. break;
  9177. }
  9178. streamController.controller.enqueue(data.chunk);
  9179. break;
  9180. case StreamKind.CLOSE:
  9181. (0, _util.assert)(streamController, "close should have stream controller");
  9182. if (streamController.isClosed) {
  9183. break;
  9184. }
  9185. streamController.isClosed = true;
  9186. streamController.controller.close();
  9187. this.#deleteStreamController(streamController, streamId);
  9188. break;
  9189. case StreamKind.ERROR:
  9190. (0, _util.assert)(streamController, "error should have stream controller");
  9191. streamController.controller.error(wrapReason(data.reason));
  9192. this.#deleteStreamController(streamController, streamId);
  9193. break;
  9194. case StreamKind.CANCEL_COMPLETE:
  9195. if (data.success) {
  9196. streamController.cancelCall.resolve();
  9197. } else {
  9198. streamController.cancelCall.reject(wrapReason(data.reason));
  9199. }
  9200. this.#deleteStreamController(streamController, streamId);
  9201. break;
  9202. case StreamKind.CANCEL:
  9203. if (!streamSink) {
  9204. break;
  9205. }
  9206. new Promise(function (resolve) {
  9207. resolve(streamSink.onCancel?.(wrapReason(data.reason)));
  9208. }).then(function () {
  9209. comObj.postMessage({
  9210. sourceName,
  9211. targetName,
  9212. stream: StreamKind.CANCEL_COMPLETE,
  9213. streamId,
  9214. success: true
  9215. });
  9216. }, function (reason) {
  9217. comObj.postMessage({
  9218. sourceName,
  9219. targetName,
  9220. stream: StreamKind.CANCEL_COMPLETE,
  9221. streamId,
  9222. reason: wrapReason(reason)
  9223. });
  9224. });
  9225. streamSink.sinkCapability.reject(wrapReason(data.reason));
  9226. streamSink.isCancelled = true;
  9227. delete this.streamSinks[streamId];
  9228. break;
  9229. default:
  9230. throw new Error("Unexpected stream case");
  9231. }
  9232. }
  9233. async #deleteStreamController(streamController, streamId) {
  9234. await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
  9235. delete this.streamControllers[streamId];
  9236. }
  9237. destroy() {
  9238. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  9239. }
  9240. }
  9241. exports.MessageHandler = MessageHandler;
  9242. /***/ }),
  9243. /* 16 */
  9244. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9245. Object.defineProperty(exports, "__esModule", ({
  9246. value: true
  9247. }));
  9248. exports.Metadata = void 0;
  9249. var _util = __w_pdfjs_require__(1);
  9250. class Metadata {
  9251. #metadataMap;
  9252. #data;
  9253. constructor({
  9254. parsedData,
  9255. rawData
  9256. }) {
  9257. this.#metadataMap = parsedData;
  9258. this.#data = rawData;
  9259. }
  9260. getRaw() {
  9261. return this.#data;
  9262. }
  9263. get(name) {
  9264. return this.#metadataMap.get(name) ?? null;
  9265. }
  9266. getAll() {
  9267. return (0, _util.objectFromMap)(this.#metadataMap);
  9268. }
  9269. has(name) {
  9270. return this.#metadataMap.has(name);
  9271. }
  9272. }
  9273. exports.Metadata = Metadata;
  9274. /***/ }),
  9275. /* 17 */
  9276. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9277. Object.defineProperty(exports, "__esModule", ({
  9278. value: true
  9279. }));
  9280. exports.OptionalContentConfig = void 0;
  9281. var _util = __w_pdfjs_require__(1);
  9282. var _murmurhash = __w_pdfjs_require__(8);
  9283. const INTERNAL = Symbol("INTERNAL");
  9284. class OptionalContentGroup {
  9285. #visible = true;
  9286. constructor(name, intent) {
  9287. this.name = name;
  9288. this.intent = intent;
  9289. }
  9290. get visible() {
  9291. return this.#visible;
  9292. }
  9293. _setVisible(internal, visible) {
  9294. if (internal !== INTERNAL) {
  9295. (0, _util.unreachable)("Internal method `_setVisible` called.");
  9296. }
  9297. this.#visible = visible;
  9298. }
  9299. }
  9300. class OptionalContentConfig {
  9301. #cachedGetHash = null;
  9302. #groups = new Map();
  9303. #initialHash = null;
  9304. #order = null;
  9305. constructor(data) {
  9306. this.name = null;
  9307. this.creator = null;
  9308. if (data === null) {
  9309. return;
  9310. }
  9311. this.name = data.name;
  9312. this.creator = data.creator;
  9313. this.#order = data.order;
  9314. for (const group of data.groups) {
  9315. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  9316. }
  9317. if (data.baseState === "OFF") {
  9318. for (const group of this.#groups.values()) {
  9319. group._setVisible(INTERNAL, false);
  9320. }
  9321. }
  9322. for (const on of data.on) {
  9323. this.#groups.get(on)._setVisible(INTERNAL, true);
  9324. }
  9325. for (const off of data.off) {
  9326. this.#groups.get(off)._setVisible(INTERNAL, false);
  9327. }
  9328. this.#initialHash = this.getHash();
  9329. }
  9330. #evaluateVisibilityExpression(array) {
  9331. const length = array.length;
  9332. if (length < 2) {
  9333. return true;
  9334. }
  9335. const operator = array[0];
  9336. for (let i = 1; i < length; i++) {
  9337. const element = array[i];
  9338. let state;
  9339. if (Array.isArray(element)) {
  9340. state = this.#evaluateVisibilityExpression(element);
  9341. } else if (this.#groups.has(element)) {
  9342. state = this.#groups.get(element).visible;
  9343. } else {
  9344. (0, _util.warn)(`Optional content group not found: ${element}`);
  9345. return true;
  9346. }
  9347. switch (operator) {
  9348. case "And":
  9349. if (!state) {
  9350. return false;
  9351. }
  9352. break;
  9353. case "Or":
  9354. if (state) {
  9355. return true;
  9356. }
  9357. break;
  9358. case "Not":
  9359. return !state;
  9360. default:
  9361. return true;
  9362. }
  9363. }
  9364. return operator === "And";
  9365. }
  9366. isVisible(group) {
  9367. if (this.#groups.size === 0) {
  9368. return true;
  9369. }
  9370. if (!group) {
  9371. (0, _util.warn)("Optional content group not defined.");
  9372. return true;
  9373. }
  9374. if (group.type === "OCG") {
  9375. if (!this.#groups.has(group.id)) {
  9376. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  9377. return true;
  9378. }
  9379. return this.#groups.get(group.id).visible;
  9380. } else if (group.type === "OCMD") {
  9381. if (group.expression) {
  9382. return this.#evaluateVisibilityExpression(group.expression);
  9383. }
  9384. if (!group.policy || group.policy === "AnyOn") {
  9385. for (const id of group.ids) {
  9386. if (!this.#groups.has(id)) {
  9387. (0, _util.warn)(`Optional content group not found: ${id}`);
  9388. return true;
  9389. }
  9390. if (this.#groups.get(id).visible) {
  9391. return true;
  9392. }
  9393. }
  9394. return false;
  9395. } else if (group.policy === "AllOn") {
  9396. for (const id of group.ids) {
  9397. if (!this.#groups.has(id)) {
  9398. (0, _util.warn)(`Optional content group not found: ${id}`);
  9399. return true;
  9400. }
  9401. if (!this.#groups.get(id).visible) {
  9402. return false;
  9403. }
  9404. }
  9405. return true;
  9406. } else if (group.policy === "AnyOff") {
  9407. for (const id of group.ids) {
  9408. if (!this.#groups.has(id)) {
  9409. (0, _util.warn)(`Optional content group not found: ${id}`);
  9410. return true;
  9411. }
  9412. if (!this.#groups.get(id).visible) {
  9413. return true;
  9414. }
  9415. }
  9416. return false;
  9417. } else if (group.policy === "AllOff") {
  9418. for (const id of group.ids) {
  9419. if (!this.#groups.has(id)) {
  9420. (0, _util.warn)(`Optional content group not found: ${id}`);
  9421. return true;
  9422. }
  9423. if (this.#groups.get(id).visible) {
  9424. return false;
  9425. }
  9426. }
  9427. return true;
  9428. }
  9429. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  9430. return true;
  9431. }
  9432. (0, _util.warn)(`Unknown group type ${group.type}.`);
  9433. return true;
  9434. }
  9435. setVisibility(id, visible = true) {
  9436. if (!this.#groups.has(id)) {
  9437. (0, _util.warn)(`Optional content group not found: ${id}`);
  9438. return;
  9439. }
  9440. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  9441. this.#cachedGetHash = null;
  9442. }
  9443. get hasInitialVisibility() {
  9444. return this.#initialHash === null || this.getHash() === this.#initialHash;
  9445. }
  9446. getOrder() {
  9447. if (!this.#groups.size) {
  9448. return null;
  9449. }
  9450. if (this.#order) {
  9451. return this.#order.slice();
  9452. }
  9453. return [...this.#groups.keys()];
  9454. }
  9455. getGroups() {
  9456. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  9457. }
  9458. getGroup(id) {
  9459. return this.#groups.get(id) || null;
  9460. }
  9461. getHash() {
  9462. if (this.#cachedGetHash !== null) {
  9463. return this.#cachedGetHash;
  9464. }
  9465. const hash = new _murmurhash.MurmurHash3_64();
  9466. for (const [id, group] of this.#groups) {
  9467. hash.update(`${id}:${group.visible}`);
  9468. }
  9469. return this.#cachedGetHash = hash.hexdigest();
  9470. }
  9471. }
  9472. exports.OptionalContentConfig = OptionalContentConfig;
  9473. /***/ }),
  9474. /* 18 */
  9475. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9476. Object.defineProperty(exports, "__esModule", ({
  9477. value: true
  9478. }));
  9479. exports.PDFDataTransportStream = void 0;
  9480. var _util = __w_pdfjs_require__(1);
  9481. var _display_utils = __w_pdfjs_require__(6);
  9482. class PDFDataTransportStream {
  9483. constructor({
  9484. length,
  9485. initialData,
  9486. progressiveDone = false,
  9487. contentDispositionFilename = null,
  9488. disableRange = false,
  9489. disableStream = false
  9490. }, pdfDataRangeTransport) {
  9491. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  9492. this._queuedChunks = [];
  9493. this._progressiveDone = progressiveDone;
  9494. this._contentDispositionFilename = contentDispositionFilename;
  9495. if (initialData?.length > 0) {
  9496. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  9497. this._queuedChunks.push(buffer);
  9498. }
  9499. this._pdfDataRangeTransport = pdfDataRangeTransport;
  9500. this._isStreamingSupported = !disableStream;
  9501. this._isRangeSupported = !disableRange;
  9502. this._contentLength = length;
  9503. this._fullRequestReader = null;
  9504. this._rangeReaders = [];
  9505. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  9506. this._onReceiveData({
  9507. begin,
  9508. chunk
  9509. });
  9510. });
  9511. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  9512. this._onProgress({
  9513. loaded,
  9514. total
  9515. });
  9516. });
  9517. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  9518. this._onReceiveData({
  9519. chunk
  9520. });
  9521. });
  9522. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  9523. this._onProgressiveDone();
  9524. });
  9525. this._pdfDataRangeTransport.transportReady();
  9526. }
  9527. _onReceiveData({
  9528. begin,
  9529. chunk
  9530. }) {
  9531. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  9532. if (begin === undefined) {
  9533. if (this._fullRequestReader) {
  9534. this._fullRequestReader._enqueue(buffer);
  9535. } else {
  9536. this._queuedChunks.push(buffer);
  9537. }
  9538. } else {
  9539. const found = this._rangeReaders.some(function (rangeReader) {
  9540. if (rangeReader._begin !== begin) {
  9541. return false;
  9542. }
  9543. rangeReader._enqueue(buffer);
  9544. return true;
  9545. });
  9546. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  9547. }
  9548. }
  9549. get _progressiveDataLength() {
  9550. return this._fullRequestReader?._loaded ?? 0;
  9551. }
  9552. _onProgress(evt) {
  9553. if (evt.total === undefined) {
  9554. this._rangeReaders[0]?.onProgress?.({
  9555. loaded: evt.loaded
  9556. });
  9557. } else {
  9558. this._fullRequestReader?.onProgress?.({
  9559. loaded: evt.loaded,
  9560. total: evt.total
  9561. });
  9562. }
  9563. }
  9564. _onProgressiveDone() {
  9565. this._fullRequestReader?.progressiveDone();
  9566. this._progressiveDone = true;
  9567. }
  9568. _removeRangeReader(reader) {
  9569. const i = this._rangeReaders.indexOf(reader);
  9570. if (i >= 0) {
  9571. this._rangeReaders.splice(i, 1);
  9572. }
  9573. }
  9574. getFullReader() {
  9575. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  9576. const queuedChunks = this._queuedChunks;
  9577. this._queuedChunks = null;
  9578. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  9579. }
  9580. getRangeReader(begin, end) {
  9581. if (end <= this._progressiveDataLength) {
  9582. return null;
  9583. }
  9584. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  9585. this._pdfDataRangeTransport.requestDataRange(begin, end);
  9586. this._rangeReaders.push(reader);
  9587. return reader;
  9588. }
  9589. cancelAllRequests(reason) {
  9590. this._fullRequestReader?.cancel(reason);
  9591. for (const reader of this._rangeReaders.slice(0)) {
  9592. reader.cancel(reason);
  9593. }
  9594. this._pdfDataRangeTransport.abort();
  9595. }
  9596. }
  9597. exports.PDFDataTransportStream = PDFDataTransportStream;
  9598. class PDFDataTransportStreamReader {
  9599. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  9600. this._stream = stream;
  9601. this._done = progressiveDone || false;
  9602. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  9603. this._queuedChunks = queuedChunks || [];
  9604. this._loaded = 0;
  9605. for (const chunk of this._queuedChunks) {
  9606. this._loaded += chunk.byteLength;
  9607. }
  9608. this._requests = [];
  9609. this._headersReady = Promise.resolve();
  9610. stream._fullRequestReader = this;
  9611. this.onProgress = null;
  9612. }
  9613. _enqueue(chunk) {
  9614. if (this._done) {
  9615. return;
  9616. }
  9617. if (this._requests.length > 0) {
  9618. const requestCapability = this._requests.shift();
  9619. requestCapability.resolve({
  9620. value: chunk,
  9621. done: false
  9622. });
  9623. } else {
  9624. this._queuedChunks.push(chunk);
  9625. }
  9626. this._loaded += chunk.byteLength;
  9627. }
  9628. get headersReady() {
  9629. return this._headersReady;
  9630. }
  9631. get filename() {
  9632. return this._filename;
  9633. }
  9634. get isRangeSupported() {
  9635. return this._stream._isRangeSupported;
  9636. }
  9637. get isStreamingSupported() {
  9638. return this._stream._isStreamingSupported;
  9639. }
  9640. get contentLength() {
  9641. return this._stream._contentLength;
  9642. }
  9643. async read() {
  9644. if (this._queuedChunks.length > 0) {
  9645. const chunk = this._queuedChunks.shift();
  9646. return {
  9647. value: chunk,
  9648. done: false
  9649. };
  9650. }
  9651. if (this._done) {
  9652. return {
  9653. value: undefined,
  9654. done: true
  9655. };
  9656. }
  9657. const requestCapability = new _util.PromiseCapability();
  9658. this._requests.push(requestCapability);
  9659. return requestCapability.promise;
  9660. }
  9661. cancel(reason) {
  9662. this._done = true;
  9663. for (const requestCapability of this._requests) {
  9664. requestCapability.resolve({
  9665. value: undefined,
  9666. done: true
  9667. });
  9668. }
  9669. this._requests.length = 0;
  9670. }
  9671. progressiveDone() {
  9672. if (this._done) {
  9673. return;
  9674. }
  9675. this._done = true;
  9676. }
  9677. }
  9678. class PDFDataTransportStreamRangeReader {
  9679. constructor(stream, begin, end) {
  9680. this._stream = stream;
  9681. this._begin = begin;
  9682. this._end = end;
  9683. this._queuedChunk = null;
  9684. this._requests = [];
  9685. this._done = false;
  9686. this.onProgress = null;
  9687. }
  9688. _enqueue(chunk) {
  9689. if (this._done) {
  9690. return;
  9691. }
  9692. if (this._requests.length === 0) {
  9693. this._queuedChunk = chunk;
  9694. } else {
  9695. const requestsCapability = this._requests.shift();
  9696. requestsCapability.resolve({
  9697. value: chunk,
  9698. done: false
  9699. });
  9700. for (const requestCapability of this._requests) {
  9701. requestCapability.resolve({
  9702. value: undefined,
  9703. done: true
  9704. });
  9705. }
  9706. this._requests.length = 0;
  9707. }
  9708. this._done = true;
  9709. this._stream._removeRangeReader(this);
  9710. }
  9711. get isStreamingSupported() {
  9712. return false;
  9713. }
  9714. async read() {
  9715. if (this._queuedChunk) {
  9716. const chunk = this._queuedChunk;
  9717. this._queuedChunk = null;
  9718. return {
  9719. value: chunk,
  9720. done: false
  9721. };
  9722. }
  9723. if (this._done) {
  9724. return {
  9725. value: undefined,
  9726. done: true
  9727. };
  9728. }
  9729. const requestCapability = new _util.PromiseCapability();
  9730. this._requests.push(requestCapability);
  9731. return requestCapability.promise;
  9732. }
  9733. cancel(reason) {
  9734. this._done = true;
  9735. for (const requestCapability of this._requests) {
  9736. requestCapability.resolve({
  9737. value: undefined,
  9738. done: true
  9739. });
  9740. }
  9741. this._requests.length = 0;
  9742. this._stream._removeRangeReader(this);
  9743. }
  9744. }
  9745. /***/ }),
  9746. /* 19 */
  9747. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9748. Object.defineProperty(exports, "__esModule", ({
  9749. value: true
  9750. }));
  9751. exports.PDFFetchStream = void 0;
  9752. var _util = __w_pdfjs_require__(1);
  9753. var _network_utils = __w_pdfjs_require__(20);
  9754. ;
  9755. function createFetchOptions(headers, withCredentials, abortController) {
  9756. return {
  9757. method: "GET",
  9758. headers,
  9759. signal: abortController.signal,
  9760. mode: "cors",
  9761. credentials: withCredentials ? "include" : "same-origin",
  9762. redirect: "follow"
  9763. };
  9764. }
  9765. function createHeaders(httpHeaders) {
  9766. const headers = new Headers();
  9767. for (const property in httpHeaders) {
  9768. const value = httpHeaders[property];
  9769. if (value === undefined) {
  9770. continue;
  9771. }
  9772. headers.append(property, value);
  9773. }
  9774. return headers;
  9775. }
  9776. function getArrayBuffer(val) {
  9777. if (val instanceof Uint8Array) {
  9778. return val.buffer;
  9779. }
  9780. if (val instanceof ArrayBuffer) {
  9781. return val;
  9782. }
  9783. (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`);
  9784. return new Uint8Array(val).buffer;
  9785. }
  9786. class PDFFetchStream {
  9787. constructor(source) {
  9788. this.source = source;
  9789. this.isHttp = /^https?:/i.test(source.url);
  9790. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  9791. this._fullRequestReader = null;
  9792. this._rangeRequestReaders = [];
  9793. }
  9794. get _progressiveDataLength() {
  9795. return this._fullRequestReader?._loaded ?? 0;
  9796. }
  9797. getFullReader() {
  9798. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  9799. this._fullRequestReader = new PDFFetchStreamReader(this);
  9800. return this._fullRequestReader;
  9801. }
  9802. getRangeReader(begin, end) {
  9803. if (end <= this._progressiveDataLength) {
  9804. return null;
  9805. }
  9806. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  9807. this._rangeRequestReaders.push(reader);
  9808. return reader;
  9809. }
  9810. cancelAllRequests(reason) {
  9811. this._fullRequestReader?.cancel(reason);
  9812. for (const reader of this._rangeRequestReaders.slice(0)) {
  9813. reader.cancel(reason);
  9814. }
  9815. }
  9816. }
  9817. exports.PDFFetchStream = PDFFetchStream;
  9818. class PDFFetchStreamReader {
  9819. constructor(stream) {
  9820. this._stream = stream;
  9821. this._reader = null;
  9822. this._loaded = 0;
  9823. this._filename = null;
  9824. const source = stream.source;
  9825. this._withCredentials = source.withCredentials || false;
  9826. this._contentLength = source.length;
  9827. this._headersCapability = new _util.PromiseCapability();
  9828. this._disableRange = source.disableRange || false;
  9829. this._rangeChunkSize = source.rangeChunkSize;
  9830. if (!this._rangeChunkSize && !this._disableRange) {
  9831. this._disableRange = true;
  9832. }
  9833. this._abortController = new AbortController();
  9834. this._isStreamingSupported = !source.disableStream;
  9835. this._isRangeSupported = !source.disableRange;
  9836. this._headers = createHeaders(this._stream.httpHeaders);
  9837. const url = source.url;
  9838. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  9839. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  9840. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  9841. }
  9842. this._reader = response.body.getReader();
  9843. this._headersCapability.resolve();
  9844. const getResponseHeader = name => {
  9845. return response.headers.get(name);
  9846. };
  9847. const {
  9848. allowRangeRequests,
  9849. suggestedLength
  9850. } = (0, _network_utils.validateRangeRequestCapabilities)({
  9851. getResponseHeader,
  9852. isHttp: this._stream.isHttp,
  9853. rangeChunkSize: this._rangeChunkSize,
  9854. disableRange: this._disableRange
  9855. });
  9856. this._isRangeSupported = allowRangeRequests;
  9857. this._contentLength = suggestedLength || this._contentLength;
  9858. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  9859. if (!this._isStreamingSupported && this._isRangeSupported) {
  9860. this.cancel(new _util.AbortException("Streaming is disabled."));
  9861. }
  9862. }).catch(this._headersCapability.reject);
  9863. this.onProgress = null;
  9864. }
  9865. get headersReady() {
  9866. return this._headersCapability.promise;
  9867. }
  9868. get filename() {
  9869. return this._filename;
  9870. }
  9871. get contentLength() {
  9872. return this._contentLength;
  9873. }
  9874. get isRangeSupported() {
  9875. return this._isRangeSupported;
  9876. }
  9877. get isStreamingSupported() {
  9878. return this._isStreamingSupported;
  9879. }
  9880. async read() {
  9881. await this._headersCapability.promise;
  9882. const {
  9883. value,
  9884. done
  9885. } = await this._reader.read();
  9886. if (done) {
  9887. return {
  9888. value,
  9889. done
  9890. };
  9891. }
  9892. this._loaded += value.byteLength;
  9893. this.onProgress?.({
  9894. loaded: this._loaded,
  9895. total: this._contentLength
  9896. });
  9897. return {
  9898. value: getArrayBuffer(value),
  9899. done: false
  9900. };
  9901. }
  9902. cancel(reason) {
  9903. this._reader?.cancel(reason);
  9904. this._abortController.abort();
  9905. }
  9906. }
  9907. class PDFFetchStreamRangeReader {
  9908. constructor(stream, begin, end) {
  9909. this._stream = stream;
  9910. this._reader = null;
  9911. this._loaded = 0;
  9912. const source = stream.source;
  9913. this._withCredentials = source.withCredentials || false;
  9914. this._readCapability = new _util.PromiseCapability();
  9915. this._isStreamingSupported = !source.disableStream;
  9916. this._abortController = new AbortController();
  9917. this._headers = createHeaders(this._stream.httpHeaders);
  9918. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  9919. const url = source.url;
  9920. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  9921. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  9922. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  9923. }
  9924. this._readCapability.resolve();
  9925. this._reader = response.body.getReader();
  9926. }).catch(this._readCapability.reject);
  9927. this.onProgress = null;
  9928. }
  9929. get isStreamingSupported() {
  9930. return this._isStreamingSupported;
  9931. }
  9932. async read() {
  9933. await this._readCapability.promise;
  9934. const {
  9935. value,
  9936. done
  9937. } = await this._reader.read();
  9938. if (done) {
  9939. return {
  9940. value,
  9941. done
  9942. };
  9943. }
  9944. this._loaded += value.byteLength;
  9945. this.onProgress?.({
  9946. loaded: this._loaded
  9947. });
  9948. return {
  9949. value: getArrayBuffer(value),
  9950. done: false
  9951. };
  9952. }
  9953. cancel(reason) {
  9954. this._reader?.cancel(reason);
  9955. this._abortController.abort();
  9956. }
  9957. }
  9958. /***/ }),
  9959. /* 20 */
  9960. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9961. Object.defineProperty(exports, "__esModule", ({
  9962. value: true
  9963. }));
  9964. exports.createResponseStatusError = createResponseStatusError;
  9965. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  9966. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  9967. exports.validateResponseStatus = validateResponseStatus;
  9968. var _util = __w_pdfjs_require__(1);
  9969. var _content_disposition = __w_pdfjs_require__(21);
  9970. var _display_utils = __w_pdfjs_require__(6);
  9971. function validateRangeRequestCapabilities({
  9972. getResponseHeader,
  9973. isHttp,
  9974. rangeChunkSize,
  9975. disableRange
  9976. }) {
  9977. const returnValues = {
  9978. allowRangeRequests: false,
  9979. suggestedLength: undefined
  9980. };
  9981. const length = parseInt(getResponseHeader("Content-Length"), 10);
  9982. if (!Number.isInteger(length)) {
  9983. return returnValues;
  9984. }
  9985. returnValues.suggestedLength = length;
  9986. if (length <= 2 * rangeChunkSize) {
  9987. return returnValues;
  9988. }
  9989. if (disableRange || !isHttp) {
  9990. return returnValues;
  9991. }
  9992. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  9993. return returnValues;
  9994. }
  9995. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  9996. if (contentEncoding !== "identity") {
  9997. return returnValues;
  9998. }
  9999. returnValues.allowRangeRequests = true;
  10000. return returnValues;
  10001. }
  10002. function extractFilenameFromHeader(getResponseHeader) {
  10003. const contentDisposition = getResponseHeader("Content-Disposition");
  10004. if (contentDisposition) {
  10005. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  10006. if (filename.includes("%")) {
  10007. try {
  10008. filename = decodeURIComponent(filename);
  10009. } catch {}
  10010. }
  10011. if ((0, _display_utils.isPdfFile)(filename)) {
  10012. return filename;
  10013. }
  10014. }
  10015. return null;
  10016. }
  10017. function createResponseStatusError(status, url) {
  10018. if (status === 404 || status === 0 && url.startsWith("file:")) {
  10019. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  10020. }
  10021. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  10022. }
  10023. function validateResponseStatus(status) {
  10024. return status === 200 || status === 206;
  10025. }
  10026. /***/ }),
  10027. /* 21 */
  10028. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10029. Object.defineProperty(exports, "__esModule", ({
  10030. value: true
  10031. }));
  10032. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  10033. var _util = __w_pdfjs_require__(1);
  10034. function getFilenameFromContentDispositionHeader(contentDisposition) {
  10035. let needsEncodingFixup = true;
  10036. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  10037. if (tmp) {
  10038. tmp = tmp[1];
  10039. let filename = rfc2616unquote(tmp);
  10040. filename = unescape(filename);
  10041. filename = rfc5987decode(filename);
  10042. filename = rfc2047decode(filename);
  10043. return fixupEncoding(filename);
  10044. }
  10045. tmp = rfc2231getparam(contentDisposition);
  10046. if (tmp) {
  10047. const filename = rfc2047decode(tmp);
  10048. return fixupEncoding(filename);
  10049. }
  10050. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  10051. if (tmp) {
  10052. tmp = tmp[1];
  10053. let filename = rfc2616unquote(tmp);
  10054. filename = rfc2047decode(filename);
  10055. return fixupEncoding(filename);
  10056. }
  10057. function toParamRegExp(attributePattern, flags) {
  10058. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  10059. }
  10060. function textdecode(encoding, value) {
  10061. if (encoding) {
  10062. if (!/^[\x00-\xFF]+$/.test(value)) {
  10063. return value;
  10064. }
  10065. try {
  10066. const decoder = new TextDecoder(encoding, {
  10067. fatal: true
  10068. });
  10069. const buffer = (0, _util.stringToBytes)(value);
  10070. value = decoder.decode(buffer);
  10071. needsEncodingFixup = false;
  10072. } catch {}
  10073. }
  10074. return value;
  10075. }
  10076. function fixupEncoding(value) {
  10077. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  10078. value = textdecode("utf-8", value);
  10079. if (needsEncodingFixup) {
  10080. value = textdecode("iso-8859-1", value);
  10081. }
  10082. }
  10083. return value;
  10084. }
  10085. function rfc2231getparam(contentDispositionStr) {
  10086. const matches = [];
  10087. let match;
  10088. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  10089. while ((match = iter.exec(contentDispositionStr)) !== null) {
  10090. let [, n, quot, part] = match;
  10091. n = parseInt(n, 10);
  10092. if (n in matches) {
  10093. if (n === 0) {
  10094. break;
  10095. }
  10096. continue;
  10097. }
  10098. matches[n] = [quot, part];
  10099. }
  10100. const parts = [];
  10101. for (let n = 0; n < matches.length; ++n) {
  10102. if (!(n in matches)) {
  10103. break;
  10104. }
  10105. let [quot, part] = matches[n];
  10106. part = rfc2616unquote(part);
  10107. if (quot) {
  10108. part = unescape(part);
  10109. if (n === 0) {
  10110. part = rfc5987decode(part);
  10111. }
  10112. }
  10113. parts.push(part);
  10114. }
  10115. return parts.join("");
  10116. }
  10117. function rfc2616unquote(value) {
  10118. if (value.startsWith('"')) {
  10119. const parts = value.slice(1).split('\\"');
  10120. for (let i = 0; i < parts.length; ++i) {
  10121. const quotindex = parts[i].indexOf('"');
  10122. if (quotindex !== -1) {
  10123. parts[i] = parts[i].slice(0, quotindex);
  10124. parts.length = i + 1;
  10125. }
  10126. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  10127. }
  10128. value = parts.join('"');
  10129. }
  10130. return value;
  10131. }
  10132. function rfc5987decode(extvalue) {
  10133. const encodingend = extvalue.indexOf("'");
  10134. if (encodingend === -1) {
  10135. return extvalue;
  10136. }
  10137. const encoding = extvalue.slice(0, encodingend);
  10138. const langvalue = extvalue.slice(encodingend + 1);
  10139. const value = langvalue.replace(/^[^']*'/, "");
  10140. return textdecode(encoding, value);
  10141. }
  10142. function rfc2047decode(value) {
  10143. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  10144. return value;
  10145. }
  10146. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  10147. if (encoding === "q" || encoding === "Q") {
  10148. text = text.replaceAll("_", " ");
  10149. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  10150. return String.fromCharCode(parseInt(hex, 16));
  10151. });
  10152. return textdecode(charset, text);
  10153. }
  10154. try {
  10155. text = atob(text);
  10156. } catch {}
  10157. return textdecode(charset, text);
  10158. });
  10159. }
  10160. return "";
  10161. }
  10162. /***/ }),
  10163. /* 22 */
  10164. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10165. Object.defineProperty(exports, "__esModule", ({
  10166. value: true
  10167. }));
  10168. exports.PDFNetworkStream = void 0;
  10169. var _util = __w_pdfjs_require__(1);
  10170. var _network_utils = __w_pdfjs_require__(20);
  10171. ;
  10172. const OK_RESPONSE = 200;
  10173. const PARTIAL_CONTENT_RESPONSE = 206;
  10174. function getArrayBuffer(xhr) {
  10175. const data = xhr.response;
  10176. if (typeof data !== "string") {
  10177. return data;
  10178. }
  10179. return (0, _util.stringToBytes)(data).buffer;
  10180. }
  10181. class NetworkManager {
  10182. constructor(url, args = {}) {
  10183. this.url = url;
  10184. this.isHttp = /^https?:/i.test(url);
  10185. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  10186. this.withCredentials = args.withCredentials || false;
  10187. this.currXhrId = 0;
  10188. this.pendingRequests = Object.create(null);
  10189. }
  10190. requestRange(begin, end, listeners) {
  10191. const args = {
  10192. begin,
  10193. end
  10194. };
  10195. for (const prop in listeners) {
  10196. args[prop] = listeners[prop];
  10197. }
  10198. return this.request(args);
  10199. }
  10200. requestFull(listeners) {
  10201. return this.request(listeners);
  10202. }
  10203. request(args) {
  10204. const xhr = new XMLHttpRequest();
  10205. const xhrId = this.currXhrId++;
  10206. const pendingRequest = this.pendingRequests[xhrId] = {
  10207. xhr
  10208. };
  10209. xhr.open("GET", this.url);
  10210. xhr.withCredentials = this.withCredentials;
  10211. for (const property in this.httpHeaders) {
  10212. const value = this.httpHeaders[property];
  10213. if (value === undefined) {
  10214. continue;
  10215. }
  10216. xhr.setRequestHeader(property, value);
  10217. }
  10218. if (this.isHttp && "begin" in args && "end" in args) {
  10219. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  10220. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  10221. } else {
  10222. pendingRequest.expectedStatus = OK_RESPONSE;
  10223. }
  10224. xhr.responseType = "arraybuffer";
  10225. if (args.onError) {
  10226. xhr.onerror = function (evt) {
  10227. args.onError(xhr.status);
  10228. };
  10229. }
  10230. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  10231. xhr.onprogress = this.onProgress.bind(this, xhrId);
  10232. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  10233. pendingRequest.onDone = args.onDone;
  10234. pendingRequest.onError = args.onError;
  10235. pendingRequest.onProgress = args.onProgress;
  10236. xhr.send(null);
  10237. return xhrId;
  10238. }
  10239. onProgress(xhrId, evt) {
  10240. const pendingRequest = this.pendingRequests[xhrId];
  10241. if (!pendingRequest) {
  10242. return;
  10243. }
  10244. pendingRequest.onProgress?.(evt);
  10245. }
  10246. onStateChange(xhrId, evt) {
  10247. const pendingRequest = this.pendingRequests[xhrId];
  10248. if (!pendingRequest) {
  10249. return;
  10250. }
  10251. const xhr = pendingRequest.xhr;
  10252. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  10253. pendingRequest.onHeadersReceived();
  10254. delete pendingRequest.onHeadersReceived;
  10255. }
  10256. if (xhr.readyState !== 4) {
  10257. return;
  10258. }
  10259. if (!(xhrId in this.pendingRequests)) {
  10260. return;
  10261. }
  10262. delete this.pendingRequests[xhrId];
  10263. if (xhr.status === 0 && this.isHttp) {
  10264. pendingRequest.onError?.(xhr.status);
  10265. return;
  10266. }
  10267. const xhrStatus = xhr.status || OK_RESPONSE;
  10268. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  10269. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  10270. pendingRequest.onError?.(xhr.status);
  10271. return;
  10272. }
  10273. const chunk = getArrayBuffer(xhr);
  10274. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  10275. const rangeHeader = xhr.getResponseHeader("Content-Range");
  10276. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  10277. pendingRequest.onDone({
  10278. begin: parseInt(matches[1], 10),
  10279. chunk
  10280. });
  10281. } else if (chunk) {
  10282. pendingRequest.onDone({
  10283. begin: 0,
  10284. chunk
  10285. });
  10286. } else {
  10287. pendingRequest.onError?.(xhr.status);
  10288. }
  10289. }
  10290. getRequestXhr(xhrId) {
  10291. return this.pendingRequests[xhrId].xhr;
  10292. }
  10293. isPendingRequest(xhrId) {
  10294. return xhrId in this.pendingRequests;
  10295. }
  10296. abortRequest(xhrId) {
  10297. const xhr = this.pendingRequests[xhrId].xhr;
  10298. delete this.pendingRequests[xhrId];
  10299. xhr.abort();
  10300. }
  10301. }
  10302. class PDFNetworkStream {
  10303. constructor(source) {
  10304. this._source = source;
  10305. this._manager = new NetworkManager(source.url, {
  10306. httpHeaders: source.httpHeaders,
  10307. withCredentials: source.withCredentials
  10308. });
  10309. this._rangeChunkSize = source.rangeChunkSize;
  10310. this._fullRequestReader = null;
  10311. this._rangeRequestReaders = [];
  10312. }
  10313. _onRangeRequestReaderClosed(reader) {
  10314. const i = this._rangeRequestReaders.indexOf(reader);
  10315. if (i >= 0) {
  10316. this._rangeRequestReaders.splice(i, 1);
  10317. }
  10318. }
  10319. getFullReader() {
  10320. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  10321. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  10322. return this._fullRequestReader;
  10323. }
  10324. getRangeReader(begin, end) {
  10325. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  10326. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  10327. this._rangeRequestReaders.push(reader);
  10328. return reader;
  10329. }
  10330. cancelAllRequests(reason) {
  10331. this._fullRequestReader?.cancel(reason);
  10332. for (const reader of this._rangeRequestReaders.slice(0)) {
  10333. reader.cancel(reason);
  10334. }
  10335. }
  10336. }
  10337. exports.PDFNetworkStream = PDFNetworkStream;
  10338. class PDFNetworkStreamFullRequestReader {
  10339. constructor(manager, source) {
  10340. this._manager = manager;
  10341. const args = {
  10342. onHeadersReceived: this._onHeadersReceived.bind(this),
  10343. onDone: this._onDone.bind(this),
  10344. onError: this._onError.bind(this),
  10345. onProgress: this._onProgress.bind(this)
  10346. };
  10347. this._url = source.url;
  10348. this._fullRequestId = manager.requestFull(args);
  10349. this._headersReceivedCapability = new _util.PromiseCapability();
  10350. this._disableRange = source.disableRange || false;
  10351. this._contentLength = source.length;
  10352. this._rangeChunkSize = source.rangeChunkSize;
  10353. if (!this._rangeChunkSize && !this._disableRange) {
  10354. this._disableRange = true;
  10355. }
  10356. this._isStreamingSupported = false;
  10357. this._isRangeSupported = false;
  10358. this._cachedChunks = [];
  10359. this._requests = [];
  10360. this._done = false;
  10361. this._storedError = undefined;
  10362. this._filename = null;
  10363. this.onProgress = null;
  10364. }
  10365. _onHeadersReceived() {
  10366. const fullRequestXhrId = this._fullRequestId;
  10367. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  10368. const getResponseHeader = name => {
  10369. return fullRequestXhr.getResponseHeader(name);
  10370. };
  10371. const {
  10372. allowRangeRequests,
  10373. suggestedLength
  10374. } = (0, _network_utils.validateRangeRequestCapabilities)({
  10375. getResponseHeader,
  10376. isHttp: this._manager.isHttp,
  10377. rangeChunkSize: this._rangeChunkSize,
  10378. disableRange: this._disableRange
  10379. });
  10380. if (allowRangeRequests) {
  10381. this._isRangeSupported = true;
  10382. }
  10383. this._contentLength = suggestedLength || this._contentLength;
  10384. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  10385. if (this._isRangeSupported) {
  10386. this._manager.abortRequest(fullRequestXhrId);
  10387. }
  10388. this._headersReceivedCapability.resolve();
  10389. }
  10390. _onDone(data) {
  10391. if (data) {
  10392. if (this._requests.length > 0) {
  10393. const requestCapability = this._requests.shift();
  10394. requestCapability.resolve({
  10395. value: data.chunk,
  10396. done: false
  10397. });
  10398. } else {
  10399. this._cachedChunks.push(data.chunk);
  10400. }
  10401. }
  10402. this._done = true;
  10403. if (this._cachedChunks.length > 0) {
  10404. return;
  10405. }
  10406. for (const requestCapability of this._requests) {
  10407. requestCapability.resolve({
  10408. value: undefined,
  10409. done: true
  10410. });
  10411. }
  10412. this._requests.length = 0;
  10413. }
  10414. _onError(status) {
  10415. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  10416. this._headersReceivedCapability.reject(this._storedError);
  10417. for (const requestCapability of this._requests) {
  10418. requestCapability.reject(this._storedError);
  10419. }
  10420. this._requests.length = 0;
  10421. this._cachedChunks.length = 0;
  10422. }
  10423. _onProgress(evt) {
  10424. this.onProgress?.({
  10425. loaded: evt.loaded,
  10426. total: evt.lengthComputable ? evt.total : this._contentLength
  10427. });
  10428. }
  10429. get filename() {
  10430. return this._filename;
  10431. }
  10432. get isRangeSupported() {
  10433. return this._isRangeSupported;
  10434. }
  10435. get isStreamingSupported() {
  10436. return this._isStreamingSupported;
  10437. }
  10438. get contentLength() {
  10439. return this._contentLength;
  10440. }
  10441. get headersReady() {
  10442. return this._headersReceivedCapability.promise;
  10443. }
  10444. async read() {
  10445. if (this._storedError) {
  10446. throw this._storedError;
  10447. }
  10448. if (this._cachedChunks.length > 0) {
  10449. const chunk = this._cachedChunks.shift();
  10450. return {
  10451. value: chunk,
  10452. done: false
  10453. };
  10454. }
  10455. if (this._done) {
  10456. return {
  10457. value: undefined,
  10458. done: true
  10459. };
  10460. }
  10461. const requestCapability = new _util.PromiseCapability();
  10462. this._requests.push(requestCapability);
  10463. return requestCapability.promise;
  10464. }
  10465. cancel(reason) {
  10466. this._done = true;
  10467. this._headersReceivedCapability.reject(reason);
  10468. for (const requestCapability of this._requests) {
  10469. requestCapability.resolve({
  10470. value: undefined,
  10471. done: true
  10472. });
  10473. }
  10474. this._requests.length = 0;
  10475. if (this._manager.isPendingRequest(this._fullRequestId)) {
  10476. this._manager.abortRequest(this._fullRequestId);
  10477. }
  10478. this._fullRequestReader = null;
  10479. }
  10480. }
  10481. class PDFNetworkStreamRangeRequestReader {
  10482. constructor(manager, begin, end) {
  10483. this._manager = manager;
  10484. const args = {
  10485. onDone: this._onDone.bind(this),
  10486. onError: this._onError.bind(this),
  10487. onProgress: this._onProgress.bind(this)
  10488. };
  10489. this._url = manager.url;
  10490. this._requestId = manager.requestRange(begin, end, args);
  10491. this._requests = [];
  10492. this._queuedChunk = null;
  10493. this._done = false;
  10494. this._storedError = undefined;
  10495. this.onProgress = null;
  10496. this.onClosed = null;
  10497. }
  10498. _close() {
  10499. this.onClosed?.(this);
  10500. }
  10501. _onDone(data) {
  10502. const chunk = data.chunk;
  10503. if (this._requests.length > 0) {
  10504. const requestCapability = this._requests.shift();
  10505. requestCapability.resolve({
  10506. value: chunk,
  10507. done: false
  10508. });
  10509. } else {
  10510. this._queuedChunk = chunk;
  10511. }
  10512. this._done = true;
  10513. for (const requestCapability of this._requests) {
  10514. requestCapability.resolve({
  10515. value: undefined,
  10516. done: true
  10517. });
  10518. }
  10519. this._requests.length = 0;
  10520. this._close();
  10521. }
  10522. _onError(status) {
  10523. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  10524. for (const requestCapability of this._requests) {
  10525. requestCapability.reject(this._storedError);
  10526. }
  10527. this._requests.length = 0;
  10528. this._queuedChunk = null;
  10529. }
  10530. _onProgress(evt) {
  10531. if (!this.isStreamingSupported) {
  10532. this.onProgress?.({
  10533. loaded: evt.loaded
  10534. });
  10535. }
  10536. }
  10537. get isStreamingSupported() {
  10538. return false;
  10539. }
  10540. async read() {
  10541. if (this._storedError) {
  10542. throw this._storedError;
  10543. }
  10544. if (this._queuedChunk !== null) {
  10545. const chunk = this._queuedChunk;
  10546. this._queuedChunk = null;
  10547. return {
  10548. value: chunk,
  10549. done: false
  10550. };
  10551. }
  10552. if (this._done) {
  10553. return {
  10554. value: undefined,
  10555. done: true
  10556. };
  10557. }
  10558. const requestCapability = new _util.PromiseCapability();
  10559. this._requests.push(requestCapability);
  10560. return requestCapability.promise;
  10561. }
  10562. cancel(reason) {
  10563. this._done = true;
  10564. for (const requestCapability of this._requests) {
  10565. requestCapability.resolve({
  10566. value: undefined,
  10567. done: true
  10568. });
  10569. }
  10570. this._requests.length = 0;
  10571. if (this._manager.isPendingRequest(this._requestId)) {
  10572. this._manager.abortRequest(this._requestId);
  10573. }
  10574. this._close();
  10575. }
  10576. }
  10577. /***/ }),
  10578. /* 23 */
  10579. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10580. Object.defineProperty(exports, "__esModule", ({
  10581. value: true
  10582. }));
  10583. exports.PDFNodeStream = void 0;
  10584. var _util = __w_pdfjs_require__(1);
  10585. var _network_utils = __w_pdfjs_require__(20);
  10586. ;
  10587. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  10588. function parseUrl(sourceUrl) {
  10589. const url = require("url");
  10590. const parsedUrl = url.parse(sourceUrl);
  10591. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  10592. return parsedUrl;
  10593. }
  10594. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  10595. return url.parse(`file:///${sourceUrl}`);
  10596. }
  10597. if (!parsedUrl.host) {
  10598. parsedUrl.protocol = "file:";
  10599. }
  10600. return parsedUrl;
  10601. }
  10602. class PDFNodeStream {
  10603. constructor(source) {
  10604. this.source = source;
  10605. this.url = parseUrl(source.url);
  10606. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  10607. this.isFsUrl = this.url.protocol === "file:";
  10608. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  10609. this._fullRequestReader = null;
  10610. this._rangeRequestReaders = [];
  10611. }
  10612. get _progressiveDataLength() {
  10613. return this._fullRequestReader?._loaded ?? 0;
  10614. }
  10615. getFullReader() {
  10616. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  10617. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  10618. return this._fullRequestReader;
  10619. }
  10620. getRangeReader(start, end) {
  10621. if (end <= this._progressiveDataLength) {
  10622. return null;
  10623. }
  10624. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  10625. this._rangeRequestReaders.push(rangeReader);
  10626. return rangeReader;
  10627. }
  10628. cancelAllRequests(reason) {
  10629. this._fullRequestReader?.cancel(reason);
  10630. for (const reader of this._rangeRequestReaders.slice(0)) {
  10631. reader.cancel(reason);
  10632. }
  10633. }
  10634. }
  10635. exports.PDFNodeStream = PDFNodeStream;
  10636. class BaseFullReader {
  10637. constructor(stream) {
  10638. this._url = stream.url;
  10639. this._done = false;
  10640. this._storedError = null;
  10641. this.onProgress = null;
  10642. const source = stream.source;
  10643. this._contentLength = source.length;
  10644. this._loaded = 0;
  10645. this._filename = null;
  10646. this._disableRange = source.disableRange || false;
  10647. this._rangeChunkSize = source.rangeChunkSize;
  10648. if (!this._rangeChunkSize && !this._disableRange) {
  10649. this._disableRange = true;
  10650. }
  10651. this._isStreamingSupported = !source.disableStream;
  10652. this._isRangeSupported = !source.disableRange;
  10653. this._readableStream = null;
  10654. this._readCapability = new _util.PromiseCapability();
  10655. this._headersCapability = new _util.PromiseCapability();
  10656. }
  10657. get headersReady() {
  10658. return this._headersCapability.promise;
  10659. }
  10660. get filename() {
  10661. return this._filename;
  10662. }
  10663. get contentLength() {
  10664. return this._contentLength;
  10665. }
  10666. get isRangeSupported() {
  10667. return this._isRangeSupported;
  10668. }
  10669. get isStreamingSupported() {
  10670. return this._isStreamingSupported;
  10671. }
  10672. async read() {
  10673. await this._readCapability.promise;
  10674. if (this._done) {
  10675. return {
  10676. value: undefined,
  10677. done: true
  10678. };
  10679. }
  10680. if (this._storedError) {
  10681. throw this._storedError;
  10682. }
  10683. const chunk = this._readableStream.read();
  10684. if (chunk === null) {
  10685. this._readCapability = new _util.PromiseCapability();
  10686. return this.read();
  10687. }
  10688. this._loaded += chunk.length;
  10689. this.onProgress?.({
  10690. loaded: this._loaded,
  10691. total: this._contentLength
  10692. });
  10693. const buffer = new Uint8Array(chunk).buffer;
  10694. return {
  10695. value: buffer,
  10696. done: false
  10697. };
  10698. }
  10699. cancel(reason) {
  10700. if (!this._readableStream) {
  10701. this._error(reason);
  10702. return;
  10703. }
  10704. this._readableStream.destroy(reason);
  10705. }
  10706. _error(reason) {
  10707. this._storedError = reason;
  10708. this._readCapability.resolve();
  10709. }
  10710. _setReadableStream(readableStream) {
  10711. this._readableStream = readableStream;
  10712. readableStream.on("readable", () => {
  10713. this._readCapability.resolve();
  10714. });
  10715. readableStream.on("end", () => {
  10716. readableStream.destroy();
  10717. this._done = true;
  10718. this._readCapability.resolve();
  10719. });
  10720. readableStream.on("error", reason => {
  10721. this._error(reason);
  10722. });
  10723. if (!this._isStreamingSupported && this._isRangeSupported) {
  10724. this._error(new _util.AbortException("streaming is disabled"));
  10725. }
  10726. if (this._storedError) {
  10727. this._readableStream.destroy(this._storedError);
  10728. }
  10729. }
  10730. }
  10731. class BaseRangeReader {
  10732. constructor(stream) {
  10733. this._url = stream.url;
  10734. this._done = false;
  10735. this._storedError = null;
  10736. this.onProgress = null;
  10737. this._loaded = 0;
  10738. this._readableStream = null;
  10739. this._readCapability = new _util.PromiseCapability();
  10740. const source = stream.source;
  10741. this._isStreamingSupported = !source.disableStream;
  10742. }
  10743. get isStreamingSupported() {
  10744. return this._isStreamingSupported;
  10745. }
  10746. async read() {
  10747. await this._readCapability.promise;
  10748. if (this._done) {
  10749. return {
  10750. value: undefined,
  10751. done: true
  10752. };
  10753. }
  10754. if (this._storedError) {
  10755. throw this._storedError;
  10756. }
  10757. const chunk = this._readableStream.read();
  10758. if (chunk === null) {
  10759. this._readCapability = new _util.PromiseCapability();
  10760. return this.read();
  10761. }
  10762. this._loaded += chunk.length;
  10763. this.onProgress?.({
  10764. loaded: this._loaded
  10765. });
  10766. const buffer = new Uint8Array(chunk).buffer;
  10767. return {
  10768. value: buffer,
  10769. done: false
  10770. };
  10771. }
  10772. cancel(reason) {
  10773. if (!this._readableStream) {
  10774. this._error(reason);
  10775. return;
  10776. }
  10777. this._readableStream.destroy(reason);
  10778. }
  10779. _error(reason) {
  10780. this._storedError = reason;
  10781. this._readCapability.resolve();
  10782. }
  10783. _setReadableStream(readableStream) {
  10784. this._readableStream = readableStream;
  10785. readableStream.on("readable", () => {
  10786. this._readCapability.resolve();
  10787. });
  10788. readableStream.on("end", () => {
  10789. readableStream.destroy();
  10790. this._done = true;
  10791. this._readCapability.resolve();
  10792. });
  10793. readableStream.on("error", reason => {
  10794. this._error(reason);
  10795. });
  10796. if (this._storedError) {
  10797. this._readableStream.destroy(this._storedError);
  10798. }
  10799. }
  10800. }
  10801. function createRequestOptions(parsedUrl, headers) {
  10802. return {
  10803. protocol: parsedUrl.protocol,
  10804. auth: parsedUrl.auth,
  10805. host: parsedUrl.hostname,
  10806. port: parsedUrl.port,
  10807. path: parsedUrl.path,
  10808. method: "GET",
  10809. headers
  10810. };
  10811. }
  10812. class PDFNodeStreamFullReader extends BaseFullReader {
  10813. constructor(stream) {
  10814. super(stream);
  10815. const handleResponse = response => {
  10816. if (response.statusCode === 404) {
  10817. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10818. this._storedError = error;
  10819. this._headersCapability.reject(error);
  10820. return;
  10821. }
  10822. this._headersCapability.resolve();
  10823. this._setReadableStream(response);
  10824. const getResponseHeader = name => {
  10825. return this._readableStream.headers[name.toLowerCase()];
  10826. };
  10827. const {
  10828. allowRangeRequests,
  10829. suggestedLength
  10830. } = (0, _network_utils.validateRangeRequestCapabilities)({
  10831. getResponseHeader,
  10832. isHttp: stream.isHttp,
  10833. rangeChunkSize: this._rangeChunkSize,
  10834. disableRange: this._disableRange
  10835. });
  10836. this._isRangeSupported = allowRangeRequests;
  10837. this._contentLength = suggestedLength || this._contentLength;
  10838. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  10839. };
  10840. this._request = null;
  10841. if (this._url.protocol === "http:") {
  10842. const http = require("http");
  10843. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10844. } else {
  10845. const https = require("https");
  10846. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  10847. }
  10848. this._request.on("error", reason => {
  10849. this._storedError = reason;
  10850. this._headersCapability.reject(reason);
  10851. });
  10852. this._request.end();
  10853. }
  10854. }
  10855. class PDFNodeStreamRangeReader extends BaseRangeReader {
  10856. constructor(stream, start, end) {
  10857. super(stream);
  10858. this._httpHeaders = {};
  10859. for (const property in stream.httpHeaders) {
  10860. const value = stream.httpHeaders[property];
  10861. if (value === undefined) {
  10862. continue;
  10863. }
  10864. this._httpHeaders[property] = value;
  10865. }
  10866. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  10867. const handleResponse = response => {
  10868. if (response.statusCode === 404) {
  10869. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  10870. this._storedError = error;
  10871. return;
  10872. }
  10873. this._setReadableStream(response);
  10874. };
  10875. this._request = null;
  10876. if (this._url.protocol === "http:") {
  10877. const http = require("http");
  10878. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10879. } else {
  10880. const https = require("https");
  10881. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  10882. }
  10883. this._request.on("error", reason => {
  10884. this._storedError = reason;
  10885. });
  10886. this._request.end();
  10887. }
  10888. }
  10889. class PDFNodeStreamFsFullReader extends BaseFullReader {
  10890. constructor(stream) {
  10891. super(stream);
  10892. let path = decodeURIComponent(this._url.path);
  10893. if (fileUriRegex.test(this._url.href)) {
  10894. path = path.replace(/^\//, "");
  10895. }
  10896. const fs = require("fs");
  10897. fs.lstat(path, (error, stat) => {
  10898. if (error) {
  10899. if (error.code === "ENOENT") {
  10900. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  10901. }
  10902. this._storedError = error;
  10903. this._headersCapability.reject(error);
  10904. return;
  10905. }
  10906. this._contentLength = stat.size;
  10907. this._setReadableStream(fs.createReadStream(path));
  10908. this._headersCapability.resolve();
  10909. });
  10910. }
  10911. }
  10912. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  10913. constructor(stream, start, end) {
  10914. super(stream);
  10915. let path = decodeURIComponent(this._url.path);
  10916. if (fileUriRegex.test(this._url.href)) {
  10917. path = path.replace(/^\//, "");
  10918. }
  10919. const fs = require("fs");
  10920. this._setReadableStream(fs.createReadStream(path, {
  10921. start,
  10922. end: end - 1
  10923. }));
  10924. }
  10925. }
  10926. /***/ }),
  10927. /* 24 */
  10928. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10929. Object.defineProperty(exports, "__esModule", ({
  10930. value: true
  10931. }));
  10932. exports.SVGGraphics = void 0;
  10933. var _display_utils = __w_pdfjs_require__(6);
  10934. var _util = __w_pdfjs_require__(1);
  10935. ;
  10936. const SVG_DEFAULTS = {
  10937. fontStyle: "normal",
  10938. fontWeight: "normal",
  10939. fillColor: "#000000"
  10940. };
  10941. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  10942. const XLINK_NS = "http://www.w3.org/1999/xlink";
  10943. const LINE_CAP_STYLES = ["butt", "round", "square"];
  10944. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  10945. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  10946. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  10947. return URL.createObjectURL(new Blob([data], {
  10948. type: contentType
  10949. }));
  10950. }
  10951. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  10952. let buffer = `data:${contentType};base64,`;
  10953. for (let i = 0, ii = data.length; i < ii; i += 3) {
  10954. const b1 = data[i] & 0xff;
  10955. const b2 = data[i + 1] & 0xff;
  10956. const b3 = data[i + 2] & 0xff;
  10957. const d1 = b1 >> 2,
  10958. d2 = (b1 & 3) << 4 | b2 >> 4;
  10959. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  10960. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  10961. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  10962. }
  10963. return buffer;
  10964. };
  10965. const convertImgDataToPng = function () {
  10966. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  10967. const CHUNK_WRAPPER_SIZE = 12;
  10968. const crcTable = new Int32Array(256);
  10969. for (let i = 0; i < 256; i++) {
  10970. let c = i;
  10971. for (let h = 0; h < 8; h++) {
  10972. c = c & 1 ? 0xedb88320 ^ c >> 1 & 0x7fffffff : c >> 1 & 0x7fffffff;
  10973. }
  10974. crcTable[i] = c;
  10975. }
  10976. function crc32(data, start, end) {
  10977. let crc = -1;
  10978. for (let i = start; i < end; i++) {
  10979. const a = (crc ^ data[i]) & 0xff;
  10980. const b = crcTable[a];
  10981. crc = crc >>> 8 ^ b;
  10982. }
  10983. return crc ^ -1;
  10984. }
  10985. function writePngChunk(type, body, data, offset) {
  10986. let p = offset;
  10987. const len = body.length;
  10988. data[p] = len >> 24 & 0xff;
  10989. data[p + 1] = len >> 16 & 0xff;
  10990. data[p + 2] = len >> 8 & 0xff;
  10991. data[p + 3] = len & 0xff;
  10992. p += 4;
  10993. data[p] = type.charCodeAt(0) & 0xff;
  10994. data[p + 1] = type.charCodeAt(1) & 0xff;
  10995. data[p + 2] = type.charCodeAt(2) & 0xff;
  10996. data[p + 3] = type.charCodeAt(3) & 0xff;
  10997. p += 4;
  10998. data.set(body, p);
  10999. p += body.length;
  11000. const crc = crc32(data, offset + 4, p);
  11001. data[p] = crc >> 24 & 0xff;
  11002. data[p + 1] = crc >> 16 & 0xff;
  11003. data[p + 2] = crc >> 8 & 0xff;
  11004. data[p + 3] = crc & 0xff;
  11005. }
  11006. function adler32(data, start, end) {
  11007. let a = 1;
  11008. let b = 0;
  11009. for (let i = start; i < end; ++i) {
  11010. a = (a + (data[i] & 0xff)) % 65521;
  11011. b = (b + a) % 65521;
  11012. }
  11013. return b << 16 | a;
  11014. }
  11015. function deflateSync(literals) {
  11016. if (!_util.isNodeJS) {
  11017. return deflateSyncUncompressed(literals);
  11018. }
  11019. try {
  11020. const input = parseInt(process.versions.node) >= 8 ? literals : Buffer.from(literals);
  11021. const output = require("zlib").deflateSync(input, {
  11022. level: 9
  11023. });
  11024. return output instanceof Uint8Array ? output : new Uint8Array(output);
  11025. } catch (e) {
  11026. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  11027. }
  11028. return deflateSyncUncompressed(literals);
  11029. }
  11030. function deflateSyncUncompressed(literals) {
  11031. let len = literals.length;
  11032. const maxBlockLength = 0xffff;
  11033. const deflateBlocks = Math.ceil(len / maxBlockLength);
  11034. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  11035. let pi = 0;
  11036. idat[pi++] = 0x78;
  11037. idat[pi++] = 0x9c;
  11038. let pos = 0;
  11039. while (len > maxBlockLength) {
  11040. idat[pi++] = 0x00;
  11041. idat[pi++] = 0xff;
  11042. idat[pi++] = 0xff;
  11043. idat[pi++] = 0x00;
  11044. idat[pi++] = 0x00;
  11045. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  11046. pi += maxBlockLength;
  11047. pos += maxBlockLength;
  11048. len -= maxBlockLength;
  11049. }
  11050. idat[pi++] = 0x01;
  11051. idat[pi++] = len & 0xff;
  11052. idat[pi++] = len >> 8 & 0xff;
  11053. idat[pi++] = ~len & 0xffff & 0xff;
  11054. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  11055. idat.set(literals.subarray(pos), pi);
  11056. pi += literals.length - pos;
  11057. const adler = adler32(literals, 0, literals.length);
  11058. idat[pi++] = adler >> 24 & 0xff;
  11059. idat[pi++] = adler >> 16 & 0xff;
  11060. idat[pi++] = adler >> 8 & 0xff;
  11061. idat[pi++] = adler & 0xff;
  11062. return idat;
  11063. }
  11064. function encode(imgData, kind, forceDataSchema, isMask) {
  11065. const width = imgData.width;
  11066. const height = imgData.height;
  11067. let bitDepth, colorType, lineSize;
  11068. const bytes = imgData.data;
  11069. switch (kind) {
  11070. case _util.ImageKind.GRAYSCALE_1BPP:
  11071. colorType = 0;
  11072. bitDepth = 1;
  11073. lineSize = width + 7 >> 3;
  11074. break;
  11075. case _util.ImageKind.RGB_24BPP:
  11076. colorType = 2;
  11077. bitDepth = 8;
  11078. lineSize = width * 3;
  11079. break;
  11080. case _util.ImageKind.RGBA_32BPP:
  11081. colorType = 6;
  11082. bitDepth = 8;
  11083. lineSize = width * 4;
  11084. break;
  11085. default:
  11086. throw new Error("invalid format");
  11087. }
  11088. const literals = new Uint8Array((1 + lineSize) * height);
  11089. let offsetLiterals = 0,
  11090. offsetBytes = 0;
  11091. for (let y = 0; y < height; ++y) {
  11092. literals[offsetLiterals++] = 0;
  11093. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  11094. offsetBytes += lineSize;
  11095. offsetLiterals += lineSize;
  11096. }
  11097. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  11098. offsetLiterals = 0;
  11099. for (let y = 0; y < height; y++) {
  11100. offsetLiterals++;
  11101. for (let i = 0; i < lineSize; i++) {
  11102. literals[offsetLiterals++] ^= 0xff;
  11103. }
  11104. }
  11105. }
  11106. const ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
  11107. const idat = deflateSync(literals);
  11108. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  11109. const data = new Uint8Array(pngLength);
  11110. let offset = 0;
  11111. data.set(PNG_HEADER, offset);
  11112. offset += PNG_HEADER.length;
  11113. writePngChunk("IHDR", ihdr, data, offset);
  11114. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  11115. writePngChunk("IDATA", idat, data, offset);
  11116. offset += CHUNK_WRAPPER_SIZE + idat.length;
  11117. writePngChunk("IEND", new Uint8Array(0), data, offset);
  11118. return createObjectURL(data, "image/png", forceDataSchema);
  11119. }
  11120. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  11121. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  11122. return encode(imgData, kind, forceDataSchema, isMask);
  11123. };
  11124. }();
  11125. class SVGExtraState {
  11126. constructor() {
  11127. this.fontSizeScale = 1;
  11128. this.fontWeight = SVG_DEFAULTS.fontWeight;
  11129. this.fontSize = 0;
  11130. this.textMatrix = _util.IDENTITY_MATRIX;
  11131. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  11132. this.leading = 0;
  11133. this.textRenderingMode = _util.TextRenderingMode.FILL;
  11134. this.textMatrixScale = 1;
  11135. this.x = 0;
  11136. this.y = 0;
  11137. this.lineX = 0;
  11138. this.lineY = 0;
  11139. this.charSpacing = 0;
  11140. this.wordSpacing = 0;
  11141. this.textHScale = 1;
  11142. this.textRise = 0;
  11143. this.fillColor = SVG_DEFAULTS.fillColor;
  11144. this.strokeColor = "#000000";
  11145. this.fillAlpha = 1;
  11146. this.strokeAlpha = 1;
  11147. this.lineWidth = 1;
  11148. this.lineJoin = "";
  11149. this.lineCap = "";
  11150. this.miterLimit = 0;
  11151. this.dashArray = [];
  11152. this.dashPhase = 0;
  11153. this.dependencies = [];
  11154. this.activeClipUrl = null;
  11155. this.clipGroup = null;
  11156. this.maskId = "";
  11157. }
  11158. clone() {
  11159. return Object.create(this);
  11160. }
  11161. setCurrentPoint(x, y) {
  11162. this.x = x;
  11163. this.y = y;
  11164. }
  11165. }
  11166. function opListToTree(opList) {
  11167. let opTree = [];
  11168. const tmp = [];
  11169. for (const opListElement of opList) {
  11170. if (opListElement.fn === "save") {
  11171. opTree.push({
  11172. fnId: 92,
  11173. fn: "group",
  11174. items: []
  11175. });
  11176. tmp.push(opTree);
  11177. opTree = opTree.at(-1).items;
  11178. continue;
  11179. }
  11180. if (opListElement.fn === "restore") {
  11181. opTree = tmp.pop();
  11182. } else {
  11183. opTree.push(opListElement);
  11184. }
  11185. }
  11186. return opTree;
  11187. }
  11188. function pf(value) {
  11189. if (Number.isInteger(value)) {
  11190. return value.toString();
  11191. }
  11192. const s = value.toFixed(10);
  11193. let i = s.length - 1;
  11194. if (s[i] !== "0") {
  11195. return s;
  11196. }
  11197. do {
  11198. i--;
  11199. } while (s[i] === "0");
  11200. return s.substring(0, s[i] === "." ? i : i + 1);
  11201. }
  11202. function pm(m) {
  11203. if (m[4] === 0 && m[5] === 0) {
  11204. if (m[1] === 0 && m[2] === 0) {
  11205. if (m[0] === 1 && m[3] === 1) {
  11206. return "";
  11207. }
  11208. return `scale(${pf(m[0])} ${pf(m[3])})`;
  11209. }
  11210. if (m[0] === m[3] && m[1] === -m[2]) {
  11211. const a = Math.acos(m[0]) * 180 / Math.PI;
  11212. return `rotate(${pf(a)})`;
  11213. }
  11214. } else if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  11215. return `translate(${pf(m[4])} ${pf(m[5])})`;
  11216. }
  11217. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  11218. }
  11219. let clipCount = 0;
  11220. let maskCount = 0;
  11221. let shadingCount = 0;
  11222. class SVGGraphics {
  11223. constructor(commonObjs, objs, forceDataSchema = false) {
  11224. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  11225. this.svgFactory = new _display_utils.DOMSVGFactory();
  11226. this.current = new SVGExtraState();
  11227. this.transformMatrix = _util.IDENTITY_MATRIX;
  11228. this.transformStack = [];
  11229. this.extraStack = [];
  11230. this.commonObjs = commonObjs;
  11231. this.objs = objs;
  11232. this.pendingClip = null;
  11233. this.pendingEOFill = false;
  11234. this.embedFonts = false;
  11235. this.embeddedFonts = Object.create(null);
  11236. this.cssStyle = null;
  11237. this.forceDataSchema = !!forceDataSchema;
  11238. this._operatorIdMapping = [];
  11239. for (const op in _util.OPS) {
  11240. this._operatorIdMapping[_util.OPS[op]] = op;
  11241. }
  11242. }
  11243. getObject(data, fallback = null) {
  11244. if (typeof data === "string") {
  11245. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  11246. }
  11247. return fallback;
  11248. }
  11249. save() {
  11250. this.transformStack.push(this.transformMatrix);
  11251. const old = this.current;
  11252. this.extraStack.push(old);
  11253. this.current = old.clone();
  11254. }
  11255. restore() {
  11256. this.transformMatrix = this.transformStack.pop();
  11257. this.current = this.extraStack.pop();
  11258. this.pendingClip = null;
  11259. this.tgrp = null;
  11260. }
  11261. group(items) {
  11262. this.save();
  11263. this.executeOpTree(items);
  11264. this.restore();
  11265. }
  11266. loadDependencies(operatorList) {
  11267. const fnArray = operatorList.fnArray;
  11268. const argsArray = operatorList.argsArray;
  11269. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  11270. if (fnArray[i] !== _util.OPS.dependency) {
  11271. continue;
  11272. }
  11273. for (const obj of argsArray[i]) {
  11274. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  11275. const promise = new Promise(resolve => {
  11276. objsPool.get(obj, resolve);
  11277. });
  11278. this.current.dependencies.push(promise);
  11279. }
  11280. }
  11281. return Promise.all(this.current.dependencies);
  11282. }
  11283. transform(a, b, c, d, e, f) {
  11284. const transformMatrix = [a, b, c, d, e, f];
  11285. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  11286. this.tgrp = null;
  11287. }
  11288. getSVG(operatorList, viewport) {
  11289. this.viewport = viewport;
  11290. const svgElement = this._initialize(viewport);
  11291. return this.loadDependencies(operatorList).then(() => {
  11292. this.transformMatrix = _util.IDENTITY_MATRIX;
  11293. this.executeOpTree(this.convertOpList(operatorList));
  11294. return svgElement;
  11295. });
  11296. }
  11297. convertOpList(operatorList) {
  11298. const operatorIdMapping = this._operatorIdMapping;
  11299. const argsArray = operatorList.argsArray;
  11300. const fnArray = operatorList.fnArray;
  11301. const opList = [];
  11302. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  11303. const fnId = fnArray[i];
  11304. opList.push({
  11305. fnId,
  11306. fn: operatorIdMapping[fnId],
  11307. args: argsArray[i]
  11308. });
  11309. }
  11310. return opListToTree(opList);
  11311. }
  11312. executeOpTree(opTree) {
  11313. for (const opTreeElement of opTree) {
  11314. const fn = opTreeElement.fn;
  11315. const fnId = opTreeElement.fnId;
  11316. const args = opTreeElement.args;
  11317. switch (fnId | 0) {
  11318. case _util.OPS.beginText:
  11319. this.beginText();
  11320. break;
  11321. case _util.OPS.dependency:
  11322. break;
  11323. case _util.OPS.setLeading:
  11324. this.setLeading(args);
  11325. break;
  11326. case _util.OPS.setLeadingMoveText:
  11327. this.setLeadingMoveText(args[0], args[1]);
  11328. break;
  11329. case _util.OPS.setFont:
  11330. this.setFont(args);
  11331. break;
  11332. case _util.OPS.showText:
  11333. this.showText(args[0]);
  11334. break;
  11335. case _util.OPS.showSpacedText:
  11336. this.showText(args[0]);
  11337. break;
  11338. case _util.OPS.endText:
  11339. this.endText();
  11340. break;
  11341. case _util.OPS.moveText:
  11342. this.moveText(args[0], args[1]);
  11343. break;
  11344. case _util.OPS.setCharSpacing:
  11345. this.setCharSpacing(args[0]);
  11346. break;
  11347. case _util.OPS.setWordSpacing:
  11348. this.setWordSpacing(args[0]);
  11349. break;
  11350. case _util.OPS.setHScale:
  11351. this.setHScale(args[0]);
  11352. break;
  11353. case _util.OPS.setTextMatrix:
  11354. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  11355. break;
  11356. case _util.OPS.setTextRise:
  11357. this.setTextRise(args[0]);
  11358. break;
  11359. case _util.OPS.setTextRenderingMode:
  11360. this.setTextRenderingMode(args[0]);
  11361. break;
  11362. case _util.OPS.setLineWidth:
  11363. this.setLineWidth(args[0]);
  11364. break;
  11365. case _util.OPS.setLineJoin:
  11366. this.setLineJoin(args[0]);
  11367. break;
  11368. case _util.OPS.setLineCap:
  11369. this.setLineCap(args[0]);
  11370. break;
  11371. case _util.OPS.setMiterLimit:
  11372. this.setMiterLimit(args[0]);
  11373. break;
  11374. case _util.OPS.setFillRGBColor:
  11375. this.setFillRGBColor(args[0], args[1], args[2]);
  11376. break;
  11377. case _util.OPS.setStrokeRGBColor:
  11378. this.setStrokeRGBColor(args[0], args[1], args[2]);
  11379. break;
  11380. case _util.OPS.setStrokeColorN:
  11381. this.setStrokeColorN(args);
  11382. break;
  11383. case _util.OPS.setFillColorN:
  11384. this.setFillColorN(args);
  11385. break;
  11386. case _util.OPS.shadingFill:
  11387. this.shadingFill(args[0]);
  11388. break;
  11389. case _util.OPS.setDash:
  11390. this.setDash(args[0], args[1]);
  11391. break;
  11392. case _util.OPS.setRenderingIntent:
  11393. this.setRenderingIntent(args[0]);
  11394. break;
  11395. case _util.OPS.setFlatness:
  11396. this.setFlatness(args[0]);
  11397. break;
  11398. case _util.OPS.setGState:
  11399. this.setGState(args[0]);
  11400. break;
  11401. case _util.OPS.fill:
  11402. this.fill();
  11403. break;
  11404. case _util.OPS.eoFill:
  11405. this.eoFill();
  11406. break;
  11407. case _util.OPS.stroke:
  11408. this.stroke();
  11409. break;
  11410. case _util.OPS.fillStroke:
  11411. this.fillStroke();
  11412. break;
  11413. case _util.OPS.eoFillStroke:
  11414. this.eoFillStroke();
  11415. break;
  11416. case _util.OPS.clip:
  11417. this.clip("nonzero");
  11418. break;
  11419. case _util.OPS.eoClip:
  11420. this.clip("evenodd");
  11421. break;
  11422. case _util.OPS.paintSolidColorImageMask:
  11423. this.paintSolidColorImageMask();
  11424. break;
  11425. case _util.OPS.paintImageXObject:
  11426. this.paintImageXObject(args[0]);
  11427. break;
  11428. case _util.OPS.paintInlineImageXObject:
  11429. this.paintInlineImageXObject(args[0]);
  11430. break;
  11431. case _util.OPS.paintImageMaskXObject:
  11432. this.paintImageMaskXObject(args[0]);
  11433. break;
  11434. case _util.OPS.paintFormXObjectBegin:
  11435. this.paintFormXObjectBegin(args[0], args[1]);
  11436. break;
  11437. case _util.OPS.paintFormXObjectEnd:
  11438. this.paintFormXObjectEnd();
  11439. break;
  11440. case _util.OPS.closePath:
  11441. this.closePath();
  11442. break;
  11443. case _util.OPS.closeStroke:
  11444. this.closeStroke();
  11445. break;
  11446. case _util.OPS.closeFillStroke:
  11447. this.closeFillStroke();
  11448. break;
  11449. case _util.OPS.closeEOFillStroke:
  11450. this.closeEOFillStroke();
  11451. break;
  11452. case _util.OPS.nextLine:
  11453. this.nextLine();
  11454. break;
  11455. case _util.OPS.transform:
  11456. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  11457. break;
  11458. case _util.OPS.constructPath:
  11459. this.constructPath(args[0], args[1]);
  11460. break;
  11461. case _util.OPS.endPath:
  11462. this.endPath();
  11463. break;
  11464. case 92:
  11465. this.group(opTreeElement.items);
  11466. break;
  11467. default:
  11468. (0, _util.warn)(`Unimplemented operator ${fn}`);
  11469. break;
  11470. }
  11471. }
  11472. }
  11473. setWordSpacing(wordSpacing) {
  11474. this.current.wordSpacing = wordSpacing;
  11475. }
  11476. setCharSpacing(charSpacing) {
  11477. this.current.charSpacing = charSpacing;
  11478. }
  11479. nextLine() {
  11480. this.moveText(0, this.current.leading);
  11481. }
  11482. setTextMatrix(a, b, c, d, e, f) {
  11483. const current = this.current;
  11484. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  11485. current.textMatrixScale = Math.hypot(a, b);
  11486. current.x = current.lineX = 0;
  11487. current.y = current.lineY = 0;
  11488. current.xcoords = [];
  11489. current.ycoords = [];
  11490. current.tspan = this.svgFactory.createElement("svg:tspan");
  11491. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  11492. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  11493. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  11494. current.txtElement = this.svgFactory.createElement("svg:text");
  11495. current.txtElement.append(current.tspan);
  11496. }
  11497. beginText() {
  11498. const current = this.current;
  11499. current.x = current.lineX = 0;
  11500. current.y = current.lineY = 0;
  11501. current.textMatrix = _util.IDENTITY_MATRIX;
  11502. current.lineMatrix = _util.IDENTITY_MATRIX;
  11503. current.textMatrixScale = 1;
  11504. current.tspan = this.svgFactory.createElement("svg:tspan");
  11505. current.txtElement = this.svgFactory.createElement("svg:text");
  11506. current.txtgrp = this.svgFactory.createElement("svg:g");
  11507. current.xcoords = [];
  11508. current.ycoords = [];
  11509. }
  11510. moveText(x, y) {
  11511. const current = this.current;
  11512. current.x = current.lineX += x;
  11513. current.y = current.lineY += y;
  11514. current.xcoords = [];
  11515. current.ycoords = [];
  11516. current.tspan = this.svgFactory.createElement("svg:tspan");
  11517. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  11518. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  11519. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  11520. }
  11521. showText(glyphs) {
  11522. const current = this.current;
  11523. const font = current.font;
  11524. const fontSize = current.fontSize;
  11525. if (fontSize === 0) {
  11526. return;
  11527. }
  11528. const fontSizeScale = current.fontSizeScale;
  11529. const charSpacing = current.charSpacing;
  11530. const wordSpacing = current.wordSpacing;
  11531. const fontDirection = current.fontDirection;
  11532. const textHScale = current.textHScale * fontDirection;
  11533. const vertical = font.vertical;
  11534. const spacingDir = vertical ? 1 : -1;
  11535. const defaultVMetrics = font.defaultVMetrics;
  11536. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  11537. let x = 0;
  11538. for (const glyph of glyphs) {
  11539. if (glyph === null) {
  11540. x += fontDirection * wordSpacing;
  11541. continue;
  11542. } else if (typeof glyph === "number") {
  11543. x += spacingDir * glyph * fontSize / 1000;
  11544. continue;
  11545. }
  11546. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  11547. const character = glyph.fontChar;
  11548. let scaledX, scaledY;
  11549. let width = glyph.width;
  11550. if (vertical) {
  11551. let vx;
  11552. const vmetric = glyph.vmetric || defaultVMetrics;
  11553. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  11554. vx = -vx * widthAdvanceScale;
  11555. const vy = vmetric[2] * widthAdvanceScale;
  11556. width = vmetric ? -vmetric[0] : width;
  11557. scaledX = vx / fontSizeScale;
  11558. scaledY = (x + vy) / fontSizeScale;
  11559. } else {
  11560. scaledX = x / fontSizeScale;
  11561. scaledY = 0;
  11562. }
  11563. if (glyph.isInFont || font.missingFile) {
  11564. current.xcoords.push(current.x + scaledX);
  11565. if (vertical) {
  11566. current.ycoords.push(-current.y + scaledY);
  11567. }
  11568. current.tspan.textContent += character;
  11569. } else {}
  11570. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  11571. x += charWidth;
  11572. }
  11573. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  11574. if (vertical) {
  11575. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  11576. } else {
  11577. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  11578. }
  11579. if (vertical) {
  11580. current.y -= x;
  11581. } else {
  11582. current.x += x * textHScale;
  11583. }
  11584. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  11585. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  11586. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  11587. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  11588. }
  11589. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  11590. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  11591. }
  11592. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  11593. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  11594. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  11595. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  11596. }
  11597. if (current.fillAlpha < 1) {
  11598. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  11599. }
  11600. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  11601. current.tspan.setAttributeNS(null, "fill", "transparent");
  11602. } else {
  11603. current.tspan.setAttributeNS(null, "fill", "none");
  11604. }
  11605. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  11606. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  11607. this._setStrokeAttributes(current.tspan, lineWidthScale);
  11608. }
  11609. let textMatrix = current.textMatrix;
  11610. if (current.textRise !== 0) {
  11611. textMatrix = textMatrix.slice();
  11612. textMatrix[5] += current.textRise;
  11613. }
  11614. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  11615. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  11616. current.txtElement.append(current.tspan);
  11617. current.txtgrp.append(current.txtElement);
  11618. this._ensureTransformGroup().append(current.txtElement);
  11619. }
  11620. setLeadingMoveText(x, y) {
  11621. this.setLeading(-y);
  11622. this.moveText(x, y);
  11623. }
  11624. addFontStyle(fontObj) {
  11625. if (!fontObj.data) {
  11626. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  11627. }
  11628. if (!this.cssStyle) {
  11629. this.cssStyle = this.svgFactory.createElement("svg:style");
  11630. this.cssStyle.setAttributeNS(null, "type", "text/css");
  11631. this.defs.append(this.cssStyle);
  11632. }
  11633. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  11634. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  11635. }
  11636. setFont(details) {
  11637. const current = this.current;
  11638. const fontObj = this.commonObjs.get(details[0]);
  11639. let size = details[1];
  11640. current.font = fontObj;
  11641. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  11642. this.addFontStyle(fontObj);
  11643. this.embeddedFonts[fontObj.loadedName] = fontObj;
  11644. }
  11645. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  11646. let bold = "normal";
  11647. if (fontObj.black) {
  11648. bold = "900";
  11649. } else if (fontObj.bold) {
  11650. bold = "bold";
  11651. }
  11652. const italic = fontObj.italic ? "italic" : "normal";
  11653. if (size < 0) {
  11654. size = -size;
  11655. current.fontDirection = -1;
  11656. } else {
  11657. current.fontDirection = 1;
  11658. }
  11659. current.fontSize = size;
  11660. current.fontFamily = fontObj.loadedName;
  11661. current.fontWeight = bold;
  11662. current.fontStyle = italic;
  11663. current.tspan = this.svgFactory.createElement("svg:tspan");
  11664. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  11665. current.xcoords = [];
  11666. current.ycoords = [];
  11667. }
  11668. endText() {
  11669. const current = this.current;
  11670. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  11671. current.element = current.txtElement;
  11672. this.clip("nonzero");
  11673. this.endPath();
  11674. }
  11675. }
  11676. setLineWidth(width) {
  11677. if (width > 0) {
  11678. this.current.lineWidth = width;
  11679. }
  11680. }
  11681. setLineCap(style) {
  11682. this.current.lineCap = LINE_CAP_STYLES[style];
  11683. }
  11684. setLineJoin(style) {
  11685. this.current.lineJoin = LINE_JOIN_STYLES[style];
  11686. }
  11687. setMiterLimit(limit) {
  11688. this.current.miterLimit = limit;
  11689. }
  11690. setStrokeAlpha(strokeAlpha) {
  11691. this.current.strokeAlpha = strokeAlpha;
  11692. }
  11693. setStrokeRGBColor(r, g, b) {
  11694. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  11695. }
  11696. setFillAlpha(fillAlpha) {
  11697. this.current.fillAlpha = fillAlpha;
  11698. }
  11699. setFillRGBColor(r, g, b) {
  11700. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  11701. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  11702. this.current.xcoords = [];
  11703. this.current.ycoords = [];
  11704. }
  11705. setStrokeColorN(args) {
  11706. this.current.strokeColor = this._makeColorN_Pattern(args);
  11707. }
  11708. setFillColorN(args) {
  11709. this.current.fillColor = this._makeColorN_Pattern(args);
  11710. }
  11711. shadingFill(args) {
  11712. const {
  11713. width,
  11714. height
  11715. } = this.viewport;
  11716. const inv = _util.Util.inverseTransform(this.transformMatrix);
  11717. const [x0, y0, x1, y1] = _util.Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
  11718. const rect = this.svgFactory.createElement("svg:rect");
  11719. rect.setAttributeNS(null, "x", x0);
  11720. rect.setAttributeNS(null, "y", y0);
  11721. rect.setAttributeNS(null, "width", x1 - x0);
  11722. rect.setAttributeNS(null, "height", y1 - y0);
  11723. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  11724. if (this.current.fillAlpha < 1) {
  11725. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  11726. }
  11727. this._ensureTransformGroup().append(rect);
  11728. }
  11729. _makeColorN_Pattern(args) {
  11730. if (args[0] === "TilingPattern") {
  11731. return this._makeTilingPattern(args);
  11732. }
  11733. return this._makeShadingPattern(args);
  11734. }
  11735. _makeTilingPattern(args) {
  11736. const color = args[1];
  11737. const operatorList = args[2];
  11738. const matrix = args[3] || _util.IDENTITY_MATRIX;
  11739. const [x0, y0, x1, y1] = args[4];
  11740. const xstep = args[5];
  11741. const ystep = args[6];
  11742. const paintType = args[7];
  11743. const tilingId = `shading${shadingCount++}`;
  11744. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  11745. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  11746. const txstep = xstep * xscale;
  11747. const tystep = ystep * yscale;
  11748. const tiling = this.svgFactory.createElement("svg:pattern");
  11749. tiling.setAttributeNS(null, "id", tilingId);
  11750. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  11751. tiling.setAttributeNS(null, "width", txstep);
  11752. tiling.setAttributeNS(null, "height", tystep);
  11753. tiling.setAttributeNS(null, "x", `${tx0}`);
  11754. tiling.setAttributeNS(null, "y", `${ty0}`);
  11755. const svg = this.svg;
  11756. const transformMatrix = this.transformMatrix;
  11757. const fillColor = this.current.fillColor;
  11758. const strokeColor = this.current.strokeColor;
  11759. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  11760. this.svg = bbox;
  11761. this.transformMatrix = matrix;
  11762. if (paintType === 2) {
  11763. const cssColor = _util.Util.makeHexColor(...color);
  11764. this.current.fillColor = cssColor;
  11765. this.current.strokeColor = cssColor;
  11766. }
  11767. this.executeOpTree(this.convertOpList(operatorList));
  11768. this.svg = svg;
  11769. this.transformMatrix = transformMatrix;
  11770. this.current.fillColor = fillColor;
  11771. this.current.strokeColor = strokeColor;
  11772. tiling.append(bbox.childNodes[0]);
  11773. this.defs.append(tiling);
  11774. return `url(#${tilingId})`;
  11775. }
  11776. _makeShadingPattern(args) {
  11777. if (typeof args === "string") {
  11778. args = this.objs.get(args);
  11779. }
  11780. switch (args[0]) {
  11781. case "RadialAxial":
  11782. const shadingId = `shading${shadingCount++}`;
  11783. const colorStops = args[3];
  11784. let gradient;
  11785. switch (args[1]) {
  11786. case "axial":
  11787. const point0 = args[4];
  11788. const point1 = args[5];
  11789. gradient = this.svgFactory.createElement("svg:linearGradient");
  11790. gradient.setAttributeNS(null, "id", shadingId);
  11791. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  11792. gradient.setAttributeNS(null, "x1", point0[0]);
  11793. gradient.setAttributeNS(null, "y1", point0[1]);
  11794. gradient.setAttributeNS(null, "x2", point1[0]);
  11795. gradient.setAttributeNS(null, "y2", point1[1]);
  11796. break;
  11797. case "radial":
  11798. const focalPoint = args[4];
  11799. const circlePoint = args[5];
  11800. const focalRadius = args[6];
  11801. const circleRadius = args[7];
  11802. gradient = this.svgFactory.createElement("svg:radialGradient");
  11803. gradient.setAttributeNS(null, "id", shadingId);
  11804. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  11805. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  11806. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  11807. gradient.setAttributeNS(null, "r", circleRadius);
  11808. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  11809. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  11810. gradient.setAttributeNS(null, "fr", focalRadius);
  11811. break;
  11812. default:
  11813. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  11814. }
  11815. for (const colorStop of colorStops) {
  11816. const stop = this.svgFactory.createElement("svg:stop");
  11817. stop.setAttributeNS(null, "offset", colorStop[0]);
  11818. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  11819. gradient.append(stop);
  11820. }
  11821. this.defs.append(gradient);
  11822. return `url(#${shadingId})`;
  11823. case "Mesh":
  11824. (0, _util.warn)("Unimplemented pattern Mesh");
  11825. return null;
  11826. case "Dummy":
  11827. return "hotpink";
  11828. default:
  11829. throw new Error(`Unknown IR type: ${args[0]}`);
  11830. }
  11831. }
  11832. setDash(dashArray, dashPhase) {
  11833. this.current.dashArray = dashArray;
  11834. this.current.dashPhase = dashPhase;
  11835. }
  11836. constructPath(ops, args) {
  11837. const current = this.current;
  11838. let x = current.x,
  11839. y = current.y;
  11840. let d = [];
  11841. let j = 0;
  11842. for (const op of ops) {
  11843. switch (op | 0) {
  11844. case _util.OPS.rectangle:
  11845. x = args[j++];
  11846. y = args[j++];
  11847. const width = args[j++];
  11848. const height = args[j++];
  11849. const xw = x + width;
  11850. const yh = y + height;
  11851. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  11852. break;
  11853. case _util.OPS.moveTo:
  11854. x = args[j++];
  11855. y = args[j++];
  11856. d.push("M", pf(x), pf(y));
  11857. break;
  11858. case _util.OPS.lineTo:
  11859. x = args[j++];
  11860. y = args[j++];
  11861. d.push("L", pf(x), pf(y));
  11862. break;
  11863. case _util.OPS.curveTo:
  11864. x = args[j + 4];
  11865. y = args[j + 5];
  11866. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  11867. j += 6;
  11868. break;
  11869. case _util.OPS.curveTo2:
  11870. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  11871. x = args[j + 2];
  11872. y = args[j + 3];
  11873. j += 4;
  11874. break;
  11875. case _util.OPS.curveTo3:
  11876. x = args[j + 2];
  11877. y = args[j + 3];
  11878. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  11879. j += 4;
  11880. break;
  11881. case _util.OPS.closePath:
  11882. d.push("Z");
  11883. break;
  11884. }
  11885. }
  11886. d = d.join(" ");
  11887. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  11888. d = current.path.getAttributeNS(null, "d") + d;
  11889. } else {
  11890. current.path = this.svgFactory.createElement("svg:path");
  11891. this._ensureTransformGroup().append(current.path);
  11892. }
  11893. current.path.setAttributeNS(null, "d", d);
  11894. current.path.setAttributeNS(null, "fill", "none");
  11895. current.element = current.path;
  11896. current.setCurrentPoint(x, y);
  11897. }
  11898. endPath() {
  11899. const current = this.current;
  11900. current.path = null;
  11901. if (!this.pendingClip) {
  11902. return;
  11903. }
  11904. if (!current.element) {
  11905. this.pendingClip = null;
  11906. return;
  11907. }
  11908. const clipId = `clippath${clipCount++}`;
  11909. const clipPath = this.svgFactory.createElement("svg:clipPath");
  11910. clipPath.setAttributeNS(null, "id", clipId);
  11911. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  11912. const clipElement = current.element.cloneNode(true);
  11913. if (this.pendingClip === "evenodd") {
  11914. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  11915. } else {
  11916. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  11917. }
  11918. this.pendingClip = null;
  11919. clipPath.append(clipElement);
  11920. this.defs.append(clipPath);
  11921. if (current.activeClipUrl) {
  11922. current.clipGroup = null;
  11923. for (const prev of this.extraStack) {
  11924. prev.clipGroup = null;
  11925. }
  11926. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  11927. }
  11928. current.activeClipUrl = `url(#${clipId})`;
  11929. this.tgrp = null;
  11930. }
  11931. clip(type) {
  11932. this.pendingClip = type;
  11933. }
  11934. closePath() {
  11935. const current = this.current;
  11936. if (current.path) {
  11937. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  11938. current.path.setAttributeNS(null, "d", d);
  11939. }
  11940. }
  11941. setLeading(leading) {
  11942. this.current.leading = -leading;
  11943. }
  11944. setTextRise(textRise) {
  11945. this.current.textRise = textRise;
  11946. }
  11947. setTextRenderingMode(textRenderingMode) {
  11948. this.current.textRenderingMode = textRenderingMode;
  11949. }
  11950. setHScale(scale) {
  11951. this.current.textHScale = scale / 100;
  11952. }
  11953. setRenderingIntent(intent) {}
  11954. setFlatness(flatness) {}
  11955. setGState(states) {
  11956. for (const [key, value] of states) {
  11957. switch (key) {
  11958. case "LW":
  11959. this.setLineWidth(value);
  11960. break;
  11961. case "LC":
  11962. this.setLineCap(value);
  11963. break;
  11964. case "LJ":
  11965. this.setLineJoin(value);
  11966. break;
  11967. case "ML":
  11968. this.setMiterLimit(value);
  11969. break;
  11970. case "D":
  11971. this.setDash(value[0], value[1]);
  11972. break;
  11973. case "RI":
  11974. this.setRenderingIntent(value);
  11975. break;
  11976. case "FL":
  11977. this.setFlatness(value);
  11978. break;
  11979. case "Font":
  11980. this.setFont(value);
  11981. break;
  11982. case "CA":
  11983. this.setStrokeAlpha(value);
  11984. break;
  11985. case "ca":
  11986. this.setFillAlpha(value);
  11987. break;
  11988. default:
  11989. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  11990. break;
  11991. }
  11992. }
  11993. }
  11994. fill() {
  11995. const current = this.current;
  11996. if (current.element) {
  11997. current.element.setAttributeNS(null, "fill", current.fillColor);
  11998. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  11999. this.endPath();
  12000. }
  12001. }
  12002. stroke() {
  12003. const current = this.current;
  12004. if (current.element) {
  12005. this._setStrokeAttributes(current.element);
  12006. current.element.setAttributeNS(null, "fill", "none");
  12007. this.endPath();
  12008. }
  12009. }
  12010. _setStrokeAttributes(element, lineWidthScale = 1) {
  12011. const current = this.current;
  12012. let dashArray = current.dashArray;
  12013. if (lineWidthScale !== 1 && dashArray.length > 0) {
  12014. dashArray = dashArray.map(function (value) {
  12015. return lineWidthScale * value;
  12016. });
  12017. }
  12018. element.setAttributeNS(null, "stroke", current.strokeColor);
  12019. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  12020. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  12021. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  12022. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  12023. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  12024. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  12025. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  12026. }
  12027. eoFill() {
  12028. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  12029. this.fill();
  12030. }
  12031. fillStroke() {
  12032. this.stroke();
  12033. this.fill();
  12034. }
  12035. eoFillStroke() {
  12036. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  12037. this.fillStroke();
  12038. }
  12039. closeStroke() {
  12040. this.closePath();
  12041. this.stroke();
  12042. }
  12043. closeFillStroke() {
  12044. this.closePath();
  12045. this.fillStroke();
  12046. }
  12047. closeEOFillStroke() {
  12048. this.closePath();
  12049. this.eoFillStroke();
  12050. }
  12051. paintSolidColorImageMask() {
  12052. const rect = this.svgFactory.createElement("svg:rect");
  12053. rect.setAttributeNS(null, "x", "0");
  12054. rect.setAttributeNS(null, "y", "0");
  12055. rect.setAttributeNS(null, "width", "1px");
  12056. rect.setAttributeNS(null, "height", "1px");
  12057. rect.setAttributeNS(null, "fill", this.current.fillColor);
  12058. this._ensureTransformGroup().append(rect);
  12059. }
  12060. paintImageXObject(objId) {
  12061. const imgData = this.getObject(objId);
  12062. if (!imgData) {
  12063. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  12064. return;
  12065. }
  12066. this.paintInlineImageXObject(imgData);
  12067. }
  12068. paintInlineImageXObject(imgData, mask) {
  12069. const width = imgData.width;
  12070. const height = imgData.height;
  12071. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  12072. const cliprect = this.svgFactory.createElement("svg:rect");
  12073. cliprect.setAttributeNS(null, "x", "0");
  12074. cliprect.setAttributeNS(null, "y", "0");
  12075. cliprect.setAttributeNS(null, "width", pf(width));
  12076. cliprect.setAttributeNS(null, "height", pf(height));
  12077. this.current.element = cliprect;
  12078. this.clip("nonzero");
  12079. const imgEl = this.svgFactory.createElement("svg:image");
  12080. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  12081. imgEl.setAttributeNS(null, "x", "0");
  12082. imgEl.setAttributeNS(null, "y", pf(-height));
  12083. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  12084. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  12085. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  12086. if (mask) {
  12087. mask.append(imgEl);
  12088. } else {
  12089. this._ensureTransformGroup().append(imgEl);
  12090. }
  12091. }
  12092. paintImageMaskXObject(img) {
  12093. const imgData = this.getObject(img.data, img);
  12094. if (imgData.bitmap) {
  12095. (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
  12096. return;
  12097. }
  12098. const current = this.current;
  12099. const width = imgData.width;
  12100. const height = imgData.height;
  12101. const fillColor = current.fillColor;
  12102. current.maskId = `mask${maskCount++}`;
  12103. const mask = this.svgFactory.createElement("svg:mask");
  12104. mask.setAttributeNS(null, "id", current.maskId);
  12105. const rect = this.svgFactory.createElement("svg:rect");
  12106. rect.setAttributeNS(null, "x", "0");
  12107. rect.setAttributeNS(null, "y", "0");
  12108. rect.setAttributeNS(null, "width", pf(width));
  12109. rect.setAttributeNS(null, "height", pf(height));
  12110. rect.setAttributeNS(null, "fill", fillColor);
  12111. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  12112. this.defs.append(mask);
  12113. this._ensureTransformGroup().append(rect);
  12114. this.paintInlineImageXObject(imgData, mask);
  12115. }
  12116. paintFormXObjectBegin(matrix, bbox) {
  12117. if (Array.isArray(matrix) && matrix.length === 6) {
  12118. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  12119. }
  12120. if (bbox) {
  12121. const width = bbox[2] - bbox[0];
  12122. const height = bbox[3] - bbox[1];
  12123. const cliprect = this.svgFactory.createElement("svg:rect");
  12124. cliprect.setAttributeNS(null, "x", bbox[0]);
  12125. cliprect.setAttributeNS(null, "y", bbox[1]);
  12126. cliprect.setAttributeNS(null, "width", pf(width));
  12127. cliprect.setAttributeNS(null, "height", pf(height));
  12128. this.current.element = cliprect;
  12129. this.clip("nonzero");
  12130. this.endPath();
  12131. }
  12132. }
  12133. paintFormXObjectEnd() {}
  12134. _initialize(viewport) {
  12135. const svg = this.svgFactory.create(viewport.width, viewport.height);
  12136. const definitions = this.svgFactory.createElement("svg:defs");
  12137. svg.append(definitions);
  12138. this.defs = definitions;
  12139. const rootGroup = this.svgFactory.createElement("svg:g");
  12140. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  12141. svg.append(rootGroup);
  12142. this.svg = rootGroup;
  12143. return svg;
  12144. }
  12145. _ensureClipGroup() {
  12146. if (!this.current.clipGroup) {
  12147. const clipGroup = this.svgFactory.createElement("svg:g");
  12148. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  12149. this.svg.append(clipGroup);
  12150. this.current.clipGroup = clipGroup;
  12151. }
  12152. return this.current.clipGroup;
  12153. }
  12154. _ensureTransformGroup() {
  12155. if (!this.tgrp) {
  12156. this.tgrp = this.svgFactory.createElement("svg:g");
  12157. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  12158. if (this.current.activeClipUrl) {
  12159. this._ensureClipGroup().append(this.tgrp);
  12160. } else {
  12161. this.svg.append(this.tgrp);
  12162. }
  12163. }
  12164. return this.tgrp;
  12165. }
  12166. }
  12167. exports.SVGGraphics = SVGGraphics;
  12168. /***/ }),
  12169. /* 25 */
  12170. /***/ ((__unused_webpack_module, exports) => {
  12171. Object.defineProperty(exports, "__esModule", ({
  12172. value: true
  12173. }));
  12174. exports.XfaText = void 0;
  12175. class XfaText {
  12176. static textContent(xfa) {
  12177. const items = [];
  12178. const output = {
  12179. items,
  12180. styles: Object.create(null)
  12181. };
  12182. function walk(node) {
  12183. if (!node) {
  12184. return;
  12185. }
  12186. let str = null;
  12187. const name = node.name;
  12188. if (name === "#text") {
  12189. str = node.value;
  12190. } else if (!XfaText.shouldBuildText(name)) {
  12191. return;
  12192. } else if (node?.attributes?.textContent) {
  12193. str = node.attributes.textContent;
  12194. } else if (node.value) {
  12195. str = node.value;
  12196. }
  12197. if (str !== null) {
  12198. items.push({
  12199. str
  12200. });
  12201. }
  12202. if (!node.children) {
  12203. return;
  12204. }
  12205. for (const child of node.children) {
  12206. walk(child);
  12207. }
  12208. }
  12209. walk(xfa);
  12210. return output;
  12211. }
  12212. static shouldBuildText(name) {
  12213. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  12214. }
  12215. }
  12216. exports.XfaText = XfaText;
  12217. /***/ }),
  12218. /* 26 */
  12219. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12220. Object.defineProperty(exports, "__esModule", ({
  12221. value: true
  12222. }));
  12223. exports.TextLayerRenderTask = void 0;
  12224. exports.renderTextLayer = renderTextLayer;
  12225. exports.updateTextLayer = updateTextLayer;
  12226. var _util = __w_pdfjs_require__(1);
  12227. var _display_utils = __w_pdfjs_require__(6);
  12228. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  12229. const DEFAULT_FONT_SIZE = 30;
  12230. const DEFAULT_FONT_ASCENT = 0.8;
  12231. const ascentCache = new Map();
  12232. function getCtx(size, isOffscreenCanvasSupported) {
  12233. let ctx;
  12234. if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
  12235. ctx = new OffscreenCanvas(size, size).getContext("2d", {
  12236. alpha: false
  12237. });
  12238. } else {
  12239. const canvas = document.createElement("canvas");
  12240. canvas.width = canvas.height = size;
  12241. ctx = canvas.getContext("2d", {
  12242. alpha: false
  12243. });
  12244. }
  12245. return ctx;
  12246. }
  12247. function getAscent(fontFamily, isOffscreenCanvasSupported) {
  12248. const cachedAscent = ascentCache.get(fontFamily);
  12249. if (cachedAscent) {
  12250. return cachedAscent;
  12251. }
  12252. const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
  12253. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  12254. const metrics = ctx.measureText("");
  12255. let ascent = metrics.fontBoundingBoxAscent;
  12256. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  12257. if (ascent) {
  12258. const ratio = ascent / (ascent + descent);
  12259. ascentCache.set(fontFamily, ratio);
  12260. ctx.canvas.width = ctx.canvas.height = 0;
  12261. return ratio;
  12262. }
  12263. ctx.strokeStyle = "red";
  12264. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12265. ctx.strokeText("g", 0, 0);
  12266. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12267. descent = 0;
  12268. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  12269. if (pixels[i] > 0) {
  12270. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  12271. break;
  12272. }
  12273. }
  12274. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12275. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  12276. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12277. ascent = 0;
  12278. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  12279. if (pixels[i] > 0) {
  12280. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  12281. break;
  12282. }
  12283. }
  12284. ctx.canvas.width = ctx.canvas.height = 0;
  12285. if (ascent) {
  12286. const ratio = ascent / (ascent + descent);
  12287. ascentCache.set(fontFamily, ratio);
  12288. return ratio;
  12289. }
  12290. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  12291. return DEFAULT_FONT_ASCENT;
  12292. }
  12293. function appendText(task, geom, styles) {
  12294. const textDiv = document.createElement("span");
  12295. const textDivProperties = {
  12296. angle: 0,
  12297. canvasWidth: 0,
  12298. hasText: geom.str !== "",
  12299. hasEOL: geom.hasEOL,
  12300. fontSize: 0
  12301. };
  12302. task._textDivs.push(textDiv);
  12303. const tx = _util.Util.transform(task._transform, geom.transform);
  12304. let angle = Math.atan2(tx[1], tx[0]);
  12305. const style = styles[geom.fontName];
  12306. if (style.vertical) {
  12307. angle += Math.PI / 2;
  12308. }
  12309. const fontHeight = Math.hypot(tx[2], tx[3]);
  12310. const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
  12311. let left, top;
  12312. if (angle === 0) {
  12313. left = tx[4];
  12314. top = tx[5] - fontAscent;
  12315. } else {
  12316. left = tx[4] + fontAscent * Math.sin(angle);
  12317. top = tx[5] - fontAscent * Math.cos(angle);
  12318. }
  12319. const scaleFactorStr = "calc(var(--scale-factor)*";
  12320. const divStyle = textDiv.style;
  12321. if (task._container === task._rootContainer) {
  12322. divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
  12323. divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
  12324. } else {
  12325. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  12326. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  12327. }
  12328. divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
  12329. divStyle.fontFamily = style.fontFamily;
  12330. textDivProperties.fontSize = fontHeight;
  12331. textDiv.setAttribute("role", "presentation");
  12332. textDiv.textContent = geom.str;
  12333. textDiv.dir = geom.dir;
  12334. if (task._fontInspectorEnabled) {
  12335. textDiv.dataset.fontName = geom.fontName;
  12336. }
  12337. if (angle !== 0) {
  12338. textDivProperties.angle = angle * (180 / Math.PI);
  12339. }
  12340. let shouldScaleText = false;
  12341. if (geom.str.length > 1) {
  12342. shouldScaleText = true;
  12343. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  12344. const absScaleX = Math.abs(geom.transform[0]),
  12345. absScaleY = Math.abs(geom.transform[3]);
  12346. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  12347. shouldScaleText = true;
  12348. }
  12349. }
  12350. if (shouldScaleText) {
  12351. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  12352. }
  12353. task._textDivProperties.set(textDiv, textDivProperties);
  12354. if (task._isReadableStream) {
  12355. task._layoutText(textDiv);
  12356. }
  12357. }
  12358. function layout(params) {
  12359. const {
  12360. div,
  12361. scale,
  12362. properties,
  12363. ctx,
  12364. prevFontSize,
  12365. prevFontFamily
  12366. } = params;
  12367. const {
  12368. style
  12369. } = div;
  12370. let transform = "";
  12371. if (properties.canvasWidth !== 0 && properties.hasText) {
  12372. const {
  12373. fontFamily
  12374. } = style;
  12375. const {
  12376. canvasWidth,
  12377. fontSize
  12378. } = properties;
  12379. if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
  12380. ctx.font = `${fontSize * scale}px ${fontFamily}`;
  12381. params.prevFontSize = fontSize;
  12382. params.prevFontFamily = fontFamily;
  12383. }
  12384. const {
  12385. width
  12386. } = ctx.measureText(div.textContent);
  12387. if (width > 0) {
  12388. transform = `scaleX(${canvasWidth * scale / width})`;
  12389. }
  12390. }
  12391. if (properties.angle !== 0) {
  12392. transform = `rotate(${properties.angle}deg) ${transform}`;
  12393. }
  12394. if (transform.length > 0) {
  12395. style.transform = transform;
  12396. }
  12397. }
  12398. function render(task) {
  12399. if (task._canceled) {
  12400. return;
  12401. }
  12402. const textDivs = task._textDivs;
  12403. const capability = task._capability;
  12404. const textDivsLength = textDivs.length;
  12405. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  12406. capability.resolve();
  12407. return;
  12408. }
  12409. if (!task._isReadableStream) {
  12410. for (const textDiv of textDivs) {
  12411. task._layoutText(textDiv);
  12412. }
  12413. }
  12414. capability.resolve();
  12415. }
  12416. class TextLayerRenderTask {
  12417. constructor({
  12418. textContentSource,
  12419. container,
  12420. viewport,
  12421. textDivs,
  12422. textDivProperties,
  12423. textContentItemsStr,
  12424. isOffscreenCanvasSupported
  12425. }) {
  12426. this._textContentSource = textContentSource;
  12427. this._isReadableStream = textContentSource instanceof ReadableStream;
  12428. this._container = this._rootContainer = container;
  12429. this._textDivs = textDivs || [];
  12430. this._textContentItemsStr = textContentItemsStr || [];
  12431. this._isOffscreenCanvasSupported = isOffscreenCanvasSupported;
  12432. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  12433. this._reader = null;
  12434. this._textDivProperties = textDivProperties || new WeakMap();
  12435. this._canceled = false;
  12436. this._capability = new _util.PromiseCapability();
  12437. this._layoutTextParams = {
  12438. prevFontSize: null,
  12439. prevFontFamily: null,
  12440. div: null,
  12441. scale: viewport.scale * (globalThis.devicePixelRatio || 1),
  12442. properties: null,
  12443. ctx: getCtx(0, isOffscreenCanvasSupported)
  12444. };
  12445. const {
  12446. pageWidth,
  12447. pageHeight,
  12448. pageX,
  12449. pageY
  12450. } = viewport.rawDims;
  12451. this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  12452. this._pageWidth = pageWidth;
  12453. this._pageHeight = pageHeight;
  12454. (0, _display_utils.setLayerDimensions)(container, viewport);
  12455. this._capability.promise.finally(() => {
  12456. this._layoutTextParams = null;
  12457. }).catch(() => {});
  12458. }
  12459. get promise() {
  12460. return this._capability.promise;
  12461. }
  12462. cancel() {
  12463. this._canceled = true;
  12464. if (this._reader) {
  12465. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  12466. this._reader = null;
  12467. }
  12468. this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
  12469. }
  12470. _processItems(items, styleCache) {
  12471. for (const item of items) {
  12472. if (item.str === undefined) {
  12473. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  12474. const parent = this._container;
  12475. this._container = document.createElement("span");
  12476. this._container.classList.add("markedContent");
  12477. if (item.id !== null) {
  12478. this._container.setAttribute("id", `${item.id}`);
  12479. }
  12480. parent.append(this._container);
  12481. } else if (item.type === "endMarkedContent") {
  12482. this._container = this._container.parentNode;
  12483. }
  12484. continue;
  12485. }
  12486. this._textContentItemsStr.push(item.str);
  12487. appendText(this, item, styleCache);
  12488. }
  12489. }
  12490. _layoutText(textDiv) {
  12491. const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
  12492. this._layoutTextParams.div = textDiv;
  12493. layout(this._layoutTextParams);
  12494. if (textDivProperties.hasText) {
  12495. this._container.append(textDiv);
  12496. }
  12497. if (textDivProperties.hasEOL) {
  12498. const br = document.createElement("br");
  12499. br.setAttribute("role", "presentation");
  12500. this._container.append(br);
  12501. }
  12502. }
  12503. _render() {
  12504. const capability = new _util.PromiseCapability();
  12505. let styleCache = Object.create(null);
  12506. if (this._isReadableStream) {
  12507. const pump = () => {
  12508. this._reader.read().then(({
  12509. value,
  12510. done
  12511. }) => {
  12512. if (done) {
  12513. capability.resolve();
  12514. return;
  12515. }
  12516. Object.assign(styleCache, value.styles);
  12517. this._processItems(value.items, styleCache);
  12518. pump();
  12519. }, capability.reject);
  12520. };
  12521. this._reader = this._textContentSource.getReader();
  12522. pump();
  12523. } else if (this._textContentSource) {
  12524. const {
  12525. items,
  12526. styles
  12527. } = this._textContentSource;
  12528. this._processItems(items, styles);
  12529. capability.resolve();
  12530. } else {
  12531. throw new Error('No "textContentSource" parameter specified.');
  12532. }
  12533. capability.promise.then(() => {
  12534. styleCache = null;
  12535. render(this);
  12536. }, this._capability.reject);
  12537. }
  12538. }
  12539. exports.TextLayerRenderTask = TextLayerRenderTask;
  12540. function renderTextLayer(params) {
  12541. if (!params.textContentSource && (params.textContent || params.textContentStream)) {
  12542. (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
  12543. params.textContentSource = params.textContent || params.textContentStream;
  12544. }
  12545. const {
  12546. container,
  12547. viewport
  12548. } = params;
  12549. const style = getComputedStyle(container);
  12550. const visibility = style.getPropertyValue("visibility");
  12551. const scaleFactor = parseFloat(style.getPropertyValue("--scale-factor"));
  12552. if (visibility === "visible" && (!scaleFactor || Math.abs(scaleFactor - viewport.scale) > 1e-5)) {
  12553. console.error("The `--scale-factor` CSS-variable must be set, " + "to the same value as `viewport.scale`, " + "either on the `container`-element itself or higher up in the DOM.");
  12554. }
  12555. const task = new TextLayerRenderTask(params);
  12556. task._render();
  12557. return task;
  12558. }
  12559. function updateTextLayer({
  12560. container,
  12561. viewport,
  12562. textDivs,
  12563. textDivProperties,
  12564. isOffscreenCanvasSupported,
  12565. mustRotate = true,
  12566. mustRescale = true
  12567. }) {
  12568. if (mustRotate) {
  12569. (0, _display_utils.setLayerDimensions)(container, {
  12570. rotation: viewport.rotation
  12571. });
  12572. }
  12573. if (mustRescale) {
  12574. const ctx = getCtx(0, isOffscreenCanvasSupported);
  12575. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  12576. const params = {
  12577. prevFontSize: null,
  12578. prevFontFamily: null,
  12579. div: null,
  12580. scale,
  12581. properties: null,
  12582. ctx
  12583. };
  12584. for (const div of textDivs) {
  12585. params.properties = textDivProperties.get(div);
  12586. params.div = div;
  12587. layout(params);
  12588. }
  12589. }
  12590. }
  12591. /***/ }),
  12592. /* 27 */
  12593. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12594. Object.defineProperty(exports, "__esModule", ({
  12595. value: true
  12596. }));
  12597. exports.AnnotationEditorLayer = void 0;
  12598. var _util = __w_pdfjs_require__(1);
  12599. var _editor = __w_pdfjs_require__(4);
  12600. var _freetext = __w_pdfjs_require__(28);
  12601. var _ink = __w_pdfjs_require__(33);
  12602. var _display_utils = __w_pdfjs_require__(6);
  12603. var _stamp = __w_pdfjs_require__(34);
  12604. class AnnotationEditorLayer {
  12605. #accessibilityManager;
  12606. #allowClick = false;
  12607. #annotationLayer = null;
  12608. #boundPointerup = this.pointerup.bind(this);
  12609. #boundPointerdown = this.pointerdown.bind(this);
  12610. #editors = new Map();
  12611. #hadPointerDown = false;
  12612. #isCleaningUp = false;
  12613. #isDisabling = false;
  12614. #uiManager;
  12615. static _initialized = false;
  12616. constructor({
  12617. uiManager,
  12618. pageIndex,
  12619. div,
  12620. accessibilityManager,
  12621. annotationLayer,
  12622. viewport,
  12623. l10n
  12624. }) {
  12625. const editorTypes = [_freetext.FreeTextEditor, _ink.InkEditor, _stamp.StampEditor];
  12626. if (!AnnotationEditorLayer._initialized) {
  12627. AnnotationEditorLayer._initialized = true;
  12628. for (const editorType of editorTypes) {
  12629. editorType.initialize(l10n);
  12630. }
  12631. }
  12632. uiManager.registerEditorTypes(editorTypes);
  12633. this.#uiManager = uiManager;
  12634. this.pageIndex = pageIndex;
  12635. this.div = div;
  12636. this.#accessibilityManager = accessibilityManager;
  12637. this.#annotationLayer = annotationLayer;
  12638. this.viewport = viewport;
  12639. this.#uiManager.addLayer(this);
  12640. }
  12641. get isEmpty() {
  12642. return this.#editors.size === 0;
  12643. }
  12644. updateToolbar(mode) {
  12645. this.#uiManager.updateToolbar(mode);
  12646. }
  12647. updateMode(mode = this.#uiManager.getMode()) {
  12648. this.#cleanup();
  12649. if (mode === _util.AnnotationEditorType.INK) {
  12650. this.addInkEditorIfNeeded(false);
  12651. this.disableClick();
  12652. } else {
  12653. this.enableClick();
  12654. }
  12655. if (mode !== _util.AnnotationEditorType.NONE) {
  12656. this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
  12657. this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
  12658. this.div.classList.toggle("stampEditing", mode === _util.AnnotationEditorType.STAMP);
  12659. this.div.hidden = false;
  12660. }
  12661. }
  12662. addInkEditorIfNeeded(isCommitting) {
  12663. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  12664. return;
  12665. }
  12666. if (!isCommitting) {
  12667. for (const editor of this.#editors.values()) {
  12668. if (editor.isEmpty()) {
  12669. editor.setInBackground();
  12670. return;
  12671. }
  12672. }
  12673. }
  12674. const editor = this.#createAndAddNewEditor({
  12675. offsetX: 0,
  12676. offsetY: 0
  12677. }, false);
  12678. editor.setInBackground();
  12679. }
  12680. setEditingState(isEditing) {
  12681. this.#uiManager.setEditingState(isEditing);
  12682. }
  12683. addCommands(params) {
  12684. this.#uiManager.addCommands(params);
  12685. }
  12686. enable() {
  12687. this.div.style.pointerEvents = "auto";
  12688. const annotationElementIds = new Set();
  12689. for (const editor of this.#editors.values()) {
  12690. editor.enableEditing();
  12691. if (editor.annotationElementId) {
  12692. annotationElementIds.add(editor.annotationElementId);
  12693. }
  12694. }
  12695. if (!this.#annotationLayer) {
  12696. return;
  12697. }
  12698. const editables = this.#annotationLayer.getEditableAnnotations();
  12699. for (const editable of editables) {
  12700. editable.hide();
  12701. if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
  12702. continue;
  12703. }
  12704. if (annotationElementIds.has(editable.data.id)) {
  12705. continue;
  12706. }
  12707. const editor = this.deserialize(editable);
  12708. if (!editor) {
  12709. continue;
  12710. }
  12711. this.addOrRebuild(editor);
  12712. editor.enableEditing();
  12713. }
  12714. }
  12715. disable() {
  12716. this.#isDisabling = true;
  12717. this.div.style.pointerEvents = "none";
  12718. const hiddenAnnotationIds = new Set();
  12719. for (const editor of this.#editors.values()) {
  12720. editor.disableEditing();
  12721. if (!editor.annotationElementId || editor.serialize() !== null) {
  12722. hiddenAnnotationIds.add(editor.annotationElementId);
  12723. continue;
  12724. }
  12725. this.getEditableAnnotation(editor.annotationElementId)?.show();
  12726. editor.remove();
  12727. }
  12728. if (this.#annotationLayer) {
  12729. const editables = this.#annotationLayer.getEditableAnnotations();
  12730. for (const editable of editables) {
  12731. const {
  12732. id
  12733. } = editable.data;
  12734. if (hiddenAnnotationIds.has(id) || this.#uiManager.isDeletedAnnotationElement(id)) {
  12735. continue;
  12736. }
  12737. editable.show();
  12738. }
  12739. }
  12740. this.#cleanup();
  12741. if (this.isEmpty) {
  12742. this.div.hidden = true;
  12743. }
  12744. this.#isDisabling = false;
  12745. }
  12746. getEditableAnnotation(id) {
  12747. return this.#annotationLayer?.getEditableAnnotation(id) || null;
  12748. }
  12749. setActiveEditor(editor) {
  12750. const currentActive = this.#uiManager.getActive();
  12751. if (currentActive === editor) {
  12752. return;
  12753. }
  12754. this.#uiManager.setActiveEditor(editor);
  12755. }
  12756. enableClick() {
  12757. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  12758. this.div.addEventListener("pointerup", this.#boundPointerup);
  12759. }
  12760. disableClick() {
  12761. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  12762. this.div.removeEventListener("pointerup", this.#boundPointerup);
  12763. }
  12764. attach(editor) {
  12765. this.#editors.set(editor.id, editor);
  12766. const {
  12767. annotationElementId
  12768. } = editor;
  12769. if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
  12770. this.#uiManager.removeDeletedAnnotationElement(editor);
  12771. }
  12772. }
  12773. detach(editor) {
  12774. this.#editors.delete(editor.id);
  12775. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  12776. if (!this.#isDisabling && editor.annotationElementId) {
  12777. this.#uiManager.addDeletedAnnotationElement(editor);
  12778. }
  12779. }
  12780. remove(editor) {
  12781. this.detach(editor);
  12782. this.#uiManager.removeEditor(editor);
  12783. if (editor.div.contains(document.activeElement)) {
  12784. setTimeout(() => {
  12785. this.#uiManager.focusMainContainer();
  12786. }, 0);
  12787. }
  12788. editor.div.remove();
  12789. editor.isAttachedToDOM = false;
  12790. if (!this.#isCleaningUp) {
  12791. this.addInkEditorIfNeeded(false);
  12792. }
  12793. }
  12794. changeParent(editor) {
  12795. if (editor.parent === this) {
  12796. return;
  12797. }
  12798. if (editor.annotationElementId) {
  12799. this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
  12800. _editor.AnnotationEditor.deleteAnnotationElement(editor);
  12801. editor.annotationElementId = null;
  12802. }
  12803. this.attach(editor);
  12804. editor.parent?.detach(editor);
  12805. editor.setParent(this);
  12806. if (editor.div && editor.isAttachedToDOM) {
  12807. editor.div.remove();
  12808. this.div.append(editor.div);
  12809. }
  12810. }
  12811. add(editor) {
  12812. this.changeParent(editor);
  12813. this.#uiManager.addEditor(editor);
  12814. this.attach(editor);
  12815. if (!editor.isAttachedToDOM) {
  12816. const div = editor.render();
  12817. this.div.append(div);
  12818. editor.isAttachedToDOM = true;
  12819. }
  12820. this.moveEditorInDOM(editor);
  12821. editor.onceAdded();
  12822. this.#uiManager.addToAnnotationStorage(editor);
  12823. }
  12824. moveEditorInDOM(editor) {
  12825. if (!editor.isAttachedToDOM) {
  12826. return;
  12827. }
  12828. const {
  12829. activeElement
  12830. } = document;
  12831. if (editor.div.contains(activeElement)) {
  12832. editor._focusEventsAllowed = false;
  12833. setTimeout(() => {
  12834. editor.div.addEventListener("focusin", () => {
  12835. editor._focusEventsAllowed = true;
  12836. }, {
  12837. once: true
  12838. });
  12839. activeElement.focus();
  12840. }, 0);
  12841. }
  12842. this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  12843. }
  12844. addOrRebuild(editor) {
  12845. if (editor.needsToBeRebuilt()) {
  12846. editor.rebuild();
  12847. } else {
  12848. this.add(editor);
  12849. }
  12850. }
  12851. addUndoableEditor(editor) {
  12852. const cmd = () => editor._uiManager.rebuild(editor);
  12853. const undo = () => {
  12854. editor.remove();
  12855. };
  12856. this.addCommands({
  12857. cmd,
  12858. undo,
  12859. mustExec: false
  12860. });
  12861. }
  12862. getNextId() {
  12863. return this.#uiManager.getId();
  12864. }
  12865. #createNewEditor(params) {
  12866. switch (this.#uiManager.getMode()) {
  12867. case _util.AnnotationEditorType.FREETEXT:
  12868. return new _freetext.FreeTextEditor(params);
  12869. case _util.AnnotationEditorType.INK:
  12870. return new _ink.InkEditor(params);
  12871. case _util.AnnotationEditorType.STAMP:
  12872. return new _stamp.StampEditor(params);
  12873. }
  12874. return null;
  12875. }
  12876. pasteEditor(mode, params) {
  12877. this.#uiManager.updateToolbar(mode);
  12878. this.#uiManager.updateMode(mode);
  12879. const {
  12880. offsetX,
  12881. offsetY
  12882. } = this.#getCenterPoint();
  12883. const id = this.getNextId();
  12884. const editor = this.#createNewEditor({
  12885. parent: this,
  12886. id,
  12887. x: offsetX,
  12888. y: offsetY,
  12889. uiManager: this.#uiManager,
  12890. isCentered: true,
  12891. ...params
  12892. });
  12893. if (editor) {
  12894. this.add(editor);
  12895. }
  12896. }
  12897. deserialize(data) {
  12898. switch (data.annotationType ?? data.annotationEditorType) {
  12899. case _util.AnnotationEditorType.FREETEXT:
  12900. return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
  12901. case _util.AnnotationEditorType.INK:
  12902. return _ink.InkEditor.deserialize(data, this, this.#uiManager);
  12903. case _util.AnnotationEditorType.STAMP:
  12904. return _stamp.StampEditor.deserialize(data, this, this.#uiManager);
  12905. }
  12906. return null;
  12907. }
  12908. #createAndAddNewEditor(event, isCentered) {
  12909. const id = this.getNextId();
  12910. const editor = this.#createNewEditor({
  12911. parent: this,
  12912. id,
  12913. x: event.offsetX,
  12914. y: event.offsetY,
  12915. uiManager: this.#uiManager,
  12916. isCentered
  12917. });
  12918. if (editor) {
  12919. this.add(editor);
  12920. }
  12921. return editor;
  12922. }
  12923. #getCenterPoint() {
  12924. const {
  12925. x,
  12926. y,
  12927. width,
  12928. height
  12929. } = this.div.getBoundingClientRect();
  12930. const tlX = Math.max(0, x);
  12931. const tlY = Math.max(0, y);
  12932. const brX = Math.min(window.innerWidth, x + width);
  12933. const brY = Math.min(window.innerHeight, y + height);
  12934. const centerX = (tlX + brX) / 2 - x;
  12935. const centerY = (tlY + brY) / 2 - y;
  12936. const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
  12937. return {
  12938. offsetX,
  12939. offsetY
  12940. };
  12941. }
  12942. addNewEditor() {
  12943. this.#createAndAddNewEditor(this.#getCenterPoint(), true);
  12944. }
  12945. setSelected(editor) {
  12946. this.#uiManager.setSelected(editor);
  12947. }
  12948. toggleSelected(editor) {
  12949. this.#uiManager.toggleSelected(editor);
  12950. }
  12951. isSelected(editor) {
  12952. return this.#uiManager.isSelected(editor);
  12953. }
  12954. unselect(editor) {
  12955. this.#uiManager.unselect(editor);
  12956. }
  12957. pointerup(event) {
  12958. const {
  12959. isMac
  12960. } = _util.FeatureTest.platform;
  12961. if (event.button !== 0 || event.ctrlKey && isMac) {
  12962. return;
  12963. }
  12964. if (event.target !== this.div) {
  12965. return;
  12966. }
  12967. if (!this.#hadPointerDown) {
  12968. return;
  12969. }
  12970. this.#hadPointerDown = false;
  12971. if (!this.#allowClick) {
  12972. this.#allowClick = true;
  12973. return;
  12974. }
  12975. if (this.#uiManager.getMode() === _util.AnnotationEditorType.STAMP) {
  12976. this.#uiManager.unselectAll();
  12977. return;
  12978. }
  12979. this.#createAndAddNewEditor(event, false);
  12980. }
  12981. pointerdown(event) {
  12982. if (this.#hadPointerDown) {
  12983. this.#hadPointerDown = false;
  12984. return;
  12985. }
  12986. const {
  12987. isMac
  12988. } = _util.FeatureTest.platform;
  12989. if (event.button !== 0 || event.ctrlKey && isMac) {
  12990. return;
  12991. }
  12992. if (event.target !== this.div) {
  12993. return;
  12994. }
  12995. this.#hadPointerDown = true;
  12996. const editor = this.#uiManager.getActive();
  12997. this.#allowClick = !editor || editor.isEmpty();
  12998. }
  12999. findNewParent(editor, x, y) {
  13000. const layer = this.#uiManager.findParent(x, y);
  13001. if (layer === null || layer === this) {
  13002. return false;
  13003. }
  13004. layer.changeParent(editor);
  13005. return true;
  13006. }
  13007. destroy() {
  13008. if (this.#uiManager.getActive()?.parent === this) {
  13009. this.#uiManager.setActiveEditor(null);
  13010. }
  13011. for (const editor of this.#editors.values()) {
  13012. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  13013. editor.setParent(null);
  13014. editor.isAttachedToDOM = false;
  13015. editor.div.remove();
  13016. }
  13017. this.div = null;
  13018. this.#editors.clear();
  13019. this.#uiManager.removeLayer(this);
  13020. }
  13021. #cleanup() {
  13022. this.#isCleaningUp = true;
  13023. for (const editor of this.#editors.values()) {
  13024. if (editor.isEmpty()) {
  13025. editor.remove();
  13026. }
  13027. }
  13028. this.#isCleaningUp = false;
  13029. }
  13030. render({
  13031. viewport
  13032. }) {
  13033. this.viewport = viewport;
  13034. (0, _display_utils.setLayerDimensions)(this.div, viewport);
  13035. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  13036. this.add(editor);
  13037. }
  13038. this.updateMode();
  13039. }
  13040. update({
  13041. viewport
  13042. }) {
  13043. this.#uiManager.commitOrRemove();
  13044. this.viewport = viewport;
  13045. (0, _display_utils.setLayerDimensions)(this.div, {
  13046. rotation: viewport.rotation
  13047. });
  13048. this.updateMode();
  13049. }
  13050. get pageDimensions() {
  13051. const {
  13052. pageWidth,
  13053. pageHeight
  13054. } = this.viewport.rawDims;
  13055. return [pageWidth, pageHeight];
  13056. }
  13057. }
  13058. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  13059. /***/ }),
  13060. /* 28 */
  13061. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  13062. Object.defineProperty(exports, "__esModule", ({
  13063. value: true
  13064. }));
  13065. exports.FreeTextEditor = void 0;
  13066. var _util = __w_pdfjs_require__(1);
  13067. var _tools = __w_pdfjs_require__(5);
  13068. var _editor = __w_pdfjs_require__(4);
  13069. var _annotation_layer = __w_pdfjs_require__(29);
  13070. class FreeTextEditor extends _editor.AnnotationEditor {
  13071. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  13072. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  13073. #boundEditorDivInput = this.editorDivInput.bind(this);
  13074. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  13075. #color;
  13076. #content = "";
  13077. #editorDivId = `${this.id}-editor`;
  13078. #fontSize;
  13079. #initialData = null;
  13080. static _freeTextDefaultContent = "";
  13081. static _l10nPromise;
  13082. static _internalPadding = 0;
  13083. static _defaultColor = null;
  13084. static _defaultFontSize = 10;
  13085. static get _keyboardManager() {
  13086. const proto = FreeTextEditor.prototype;
  13087. const arrowChecker = self => self.isEmpty();
  13088. const small = _tools.AnnotationEditorUIManager.TRANSLATE_SMALL;
  13089. const big = _tools.AnnotationEditorUIManager.TRANSLATE_BIG;
  13090. return (0, _util.shadow)(this, "_keyboardManager", new _tools.KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
  13091. bubbles: true
  13092. }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
  13093. args: [-small, 0],
  13094. checker: arrowChecker
  13095. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
  13096. args: [-big, 0],
  13097. checker: arrowChecker
  13098. }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
  13099. args: [small, 0],
  13100. checker: arrowChecker
  13101. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
  13102. args: [big, 0],
  13103. checker: arrowChecker
  13104. }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
  13105. args: [0, -small],
  13106. checker: arrowChecker
  13107. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
  13108. args: [0, -big],
  13109. checker: arrowChecker
  13110. }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
  13111. args: [0, small],
  13112. checker: arrowChecker
  13113. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
  13114. args: [0, big],
  13115. checker: arrowChecker
  13116. }]]));
  13117. }
  13118. static _type = "freetext";
  13119. constructor(params) {
  13120. super({
  13121. ...params,
  13122. name: "freeTextEditor"
  13123. });
  13124. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  13125. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  13126. }
  13127. static initialize(l10n) {
  13128. this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
  13129. const style = getComputedStyle(document.documentElement);
  13130. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  13131. }
  13132. static updateDefaultParams(type, value) {
  13133. switch (type) {
  13134. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  13135. FreeTextEditor._defaultFontSize = value;
  13136. break;
  13137. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  13138. FreeTextEditor._defaultColor = value;
  13139. break;
  13140. }
  13141. }
  13142. updateParams(type, value) {
  13143. switch (type) {
  13144. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  13145. this.#updateFontSize(value);
  13146. break;
  13147. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  13148. this.#updateColor(value);
  13149. break;
  13150. }
  13151. }
  13152. static get defaultPropertiesToUpdate() {
  13153. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  13154. }
  13155. get propertiesToUpdate() {
  13156. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  13157. }
  13158. #updateFontSize(fontSize) {
  13159. const setFontsize = size => {
  13160. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  13161. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  13162. this.#fontSize = size;
  13163. this.#setEditorDimensions();
  13164. };
  13165. const savedFontsize = this.#fontSize;
  13166. this.addCommands({
  13167. cmd: () => {
  13168. setFontsize(fontSize);
  13169. },
  13170. undo: () => {
  13171. setFontsize(savedFontsize);
  13172. },
  13173. mustExec: true,
  13174. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  13175. overwriteIfSameType: true,
  13176. keepUndo: true
  13177. });
  13178. }
  13179. #updateColor(color) {
  13180. const savedColor = this.#color;
  13181. this.addCommands({
  13182. cmd: () => {
  13183. this.#color = this.editorDiv.style.color = color;
  13184. },
  13185. undo: () => {
  13186. this.#color = this.editorDiv.style.color = savedColor;
  13187. },
  13188. mustExec: true,
  13189. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  13190. overwriteIfSameType: true,
  13191. keepUndo: true
  13192. });
  13193. }
  13194. _translateEmpty(x, y) {
  13195. this._uiManager.translateSelectedEditors(x, y, true);
  13196. }
  13197. getInitialTranslation() {
  13198. const scale = this.parentScale;
  13199. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  13200. }
  13201. rebuild() {
  13202. if (!this.parent) {
  13203. return;
  13204. }
  13205. super.rebuild();
  13206. if (this.div === null) {
  13207. return;
  13208. }
  13209. if (!this.isAttachedToDOM) {
  13210. this.parent.add(this);
  13211. }
  13212. }
  13213. enableEditMode() {
  13214. if (this.isInEditMode()) {
  13215. return;
  13216. }
  13217. this.parent.setEditingState(false);
  13218. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  13219. super.enableEditMode();
  13220. this.overlayDiv.classList.remove("enabled");
  13221. this.editorDiv.contentEditable = true;
  13222. this._isDraggable = false;
  13223. this.div.removeAttribute("aria-activedescendant");
  13224. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  13225. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  13226. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  13227. this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  13228. }
  13229. disableEditMode() {
  13230. if (!this.isInEditMode()) {
  13231. return;
  13232. }
  13233. this.parent.setEditingState(true);
  13234. super.disableEditMode();
  13235. this.overlayDiv.classList.add("enabled");
  13236. this.editorDiv.contentEditable = false;
  13237. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  13238. this._isDraggable = true;
  13239. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  13240. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  13241. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  13242. this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
  13243. this.div.focus({
  13244. preventScroll: true
  13245. });
  13246. this.isEditing = false;
  13247. this.parent.div.classList.add("freeTextEditing");
  13248. }
  13249. focusin(event) {
  13250. if (!this._focusEventsAllowed) {
  13251. return;
  13252. }
  13253. super.focusin(event);
  13254. if (event.target !== this.editorDiv) {
  13255. this.editorDiv.focus();
  13256. }
  13257. }
  13258. onceAdded() {
  13259. if (this.width) {
  13260. this.#cheatInitialRect();
  13261. return;
  13262. }
  13263. this.enableEditMode();
  13264. this.editorDiv.focus();
  13265. if (this._initialOptions?.isCentered) {
  13266. this.center();
  13267. }
  13268. this._initialOptions = null;
  13269. }
  13270. isEmpty() {
  13271. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  13272. }
  13273. remove() {
  13274. this.isEditing = false;
  13275. if (this.parent) {
  13276. this.parent.setEditingState(true);
  13277. this.parent.div.classList.add("freeTextEditing");
  13278. }
  13279. super.remove();
  13280. }
  13281. #extractText() {
  13282. const divs = this.editorDiv.getElementsByTagName("div");
  13283. if (divs.length === 0) {
  13284. return this.editorDiv.innerText;
  13285. }
  13286. const buffer = [];
  13287. for (const div of divs) {
  13288. buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
  13289. }
  13290. return buffer.join("\n");
  13291. }
  13292. #setEditorDimensions() {
  13293. const [parentWidth, parentHeight] = this.parentDimensions;
  13294. let rect;
  13295. if (this.isAttachedToDOM) {
  13296. rect = this.div.getBoundingClientRect();
  13297. } else {
  13298. const {
  13299. currentLayer,
  13300. div
  13301. } = this;
  13302. const savedDisplay = div.style.display;
  13303. div.style.display = "hidden";
  13304. currentLayer.div.append(this.div);
  13305. rect = div.getBoundingClientRect();
  13306. div.remove();
  13307. div.style.display = savedDisplay;
  13308. }
  13309. if (this.rotation % 180 === this.parentRotation % 180) {
  13310. this.width = rect.width / parentWidth;
  13311. this.height = rect.height / parentHeight;
  13312. } else {
  13313. this.width = rect.height / parentWidth;
  13314. this.height = rect.width / parentHeight;
  13315. }
  13316. this.fixAndSetPosition();
  13317. }
  13318. commit() {
  13319. if (!this.isInEditMode()) {
  13320. return;
  13321. }
  13322. super.commit();
  13323. this.disableEditMode();
  13324. const savedText = this.#content;
  13325. const newText = this.#content = this.#extractText().trimEnd();
  13326. if (savedText === newText) {
  13327. return;
  13328. }
  13329. const setText = text => {
  13330. this.#content = text;
  13331. if (!text) {
  13332. this.remove();
  13333. return;
  13334. }
  13335. this.#setContent();
  13336. this._uiManager.rebuild(this);
  13337. this.#setEditorDimensions();
  13338. };
  13339. this.addCommands({
  13340. cmd: () => {
  13341. setText(newText);
  13342. },
  13343. undo: () => {
  13344. setText(savedText);
  13345. },
  13346. mustExec: false
  13347. });
  13348. this.#setEditorDimensions();
  13349. }
  13350. shouldGetKeyboardEvents() {
  13351. return this.isInEditMode();
  13352. }
  13353. enterInEditMode() {
  13354. this.enableEditMode();
  13355. this.editorDiv.focus();
  13356. }
  13357. dblclick(event) {
  13358. this.enterInEditMode();
  13359. }
  13360. keydown(event) {
  13361. if (event.target === this.div && event.key === "Enter") {
  13362. this.enterInEditMode();
  13363. event.preventDefault();
  13364. }
  13365. }
  13366. editorDivKeydown(event) {
  13367. FreeTextEditor._keyboardManager.exec(this, event);
  13368. }
  13369. editorDivFocus(event) {
  13370. this.isEditing = true;
  13371. }
  13372. editorDivBlur(event) {
  13373. this.isEditing = false;
  13374. }
  13375. editorDivInput(event) {
  13376. this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  13377. }
  13378. disableEditing() {
  13379. this.editorDiv.setAttribute("role", "comment");
  13380. this.editorDiv.removeAttribute("aria-multiline");
  13381. }
  13382. enableEditing() {
  13383. this.editorDiv.setAttribute("role", "textbox");
  13384. this.editorDiv.setAttribute("aria-multiline", true);
  13385. }
  13386. render() {
  13387. if (this.div) {
  13388. return this.div;
  13389. }
  13390. let baseX, baseY;
  13391. if (this.width) {
  13392. baseX = this.x;
  13393. baseY = this.y;
  13394. }
  13395. super.render();
  13396. this.editorDiv = document.createElement("div");
  13397. this.editorDiv.className = "internal";
  13398. this.editorDiv.setAttribute("id", this.#editorDivId);
  13399. this.enableEditing();
  13400. FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  13401. FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  13402. this.editorDiv.contentEditable = true;
  13403. const {
  13404. style
  13405. } = this.editorDiv;
  13406. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  13407. style.color = this.#color;
  13408. this.div.append(this.editorDiv);
  13409. this.overlayDiv = document.createElement("div");
  13410. this.overlayDiv.classList.add("overlay", "enabled");
  13411. this.div.append(this.overlayDiv);
  13412. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  13413. if (this.width) {
  13414. const [parentWidth, parentHeight] = this.parentDimensions;
  13415. if (this.annotationElementId) {
  13416. const {
  13417. position
  13418. } = this.#initialData;
  13419. let [tx, ty] = this.getInitialTranslation();
  13420. [tx, ty] = this.pageTranslationToScreen(tx, ty);
  13421. const [pageWidth, pageHeight] = this.pageDimensions;
  13422. const [pageX, pageY] = this.pageTranslation;
  13423. let posX, posY;
  13424. switch (this.rotation) {
  13425. case 0:
  13426. posX = baseX + (position[0] - pageX) / pageWidth;
  13427. posY = baseY + this.height - (position[1] - pageY) / pageHeight;
  13428. break;
  13429. case 90:
  13430. posX = baseX + (position[0] - pageX) / pageWidth;
  13431. posY = baseY - (position[1] - pageY) / pageHeight;
  13432. [tx, ty] = [ty, -tx];
  13433. break;
  13434. case 180:
  13435. posX = baseX - this.width + (position[0] - pageX) / pageWidth;
  13436. posY = baseY - (position[1] - pageY) / pageHeight;
  13437. [tx, ty] = [-tx, -ty];
  13438. break;
  13439. case 270:
  13440. posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
  13441. posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
  13442. [tx, ty] = [-ty, tx];
  13443. break;
  13444. }
  13445. this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
  13446. } else {
  13447. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  13448. }
  13449. this.#setContent();
  13450. this._isDraggable = true;
  13451. this.editorDiv.contentEditable = false;
  13452. } else {
  13453. this._isDraggable = false;
  13454. this.editorDiv.contentEditable = true;
  13455. }
  13456. return this.div;
  13457. }
  13458. #setContent() {
  13459. this.editorDiv.replaceChildren();
  13460. if (!this.#content) {
  13461. return;
  13462. }
  13463. for (const line of this.#content.split("\n")) {
  13464. const div = document.createElement("div");
  13465. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  13466. this.editorDiv.append(div);
  13467. }
  13468. }
  13469. get contentDiv() {
  13470. return this.editorDiv;
  13471. }
  13472. static deserialize(data, parent, uiManager) {
  13473. let initialData = null;
  13474. if (data instanceof _annotation_layer.FreeTextAnnotationElement) {
  13475. const {
  13476. data: {
  13477. defaultAppearanceData: {
  13478. fontSize,
  13479. fontColor
  13480. },
  13481. rect,
  13482. rotation,
  13483. id
  13484. },
  13485. textContent,
  13486. textPosition,
  13487. parent: {
  13488. page: {
  13489. pageNumber
  13490. }
  13491. }
  13492. } = data;
  13493. if (!textContent || textContent.length === 0) {
  13494. return null;
  13495. }
  13496. initialData = data = {
  13497. annotationType: _util.AnnotationEditorType.FREETEXT,
  13498. color: Array.from(fontColor),
  13499. fontSize,
  13500. value: textContent.join("\n"),
  13501. position: textPosition,
  13502. pageIndex: pageNumber - 1,
  13503. rect,
  13504. rotation,
  13505. id,
  13506. deleted: false
  13507. };
  13508. }
  13509. const editor = super.deserialize(data, parent, uiManager);
  13510. editor.#fontSize = data.fontSize;
  13511. editor.#color = _util.Util.makeHexColor(...data.color);
  13512. editor.#content = data.value;
  13513. editor.annotationElementId = data.id || null;
  13514. editor.#initialData = initialData;
  13515. return editor;
  13516. }
  13517. serialize(isForCopying = false) {
  13518. if (this.isEmpty()) {
  13519. return null;
  13520. }
  13521. if (this.deleted) {
  13522. return {
  13523. pageIndex: this.pageIndex,
  13524. id: this.annotationElementId,
  13525. deleted: true
  13526. };
  13527. }
  13528. const padding = FreeTextEditor._internalPadding * this.parentScale;
  13529. const rect = this.getRect(padding, padding);
  13530. const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  13531. const serialized = {
  13532. annotationType: _util.AnnotationEditorType.FREETEXT,
  13533. color,
  13534. fontSize: this.#fontSize,
  13535. value: this.#content,
  13536. pageIndex: this.pageIndex,
  13537. rect,
  13538. rotation: this.rotation
  13539. };
  13540. if (isForCopying) {
  13541. return serialized;
  13542. }
  13543. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  13544. return null;
  13545. }
  13546. serialized.id = this.annotationElementId;
  13547. return serialized;
  13548. }
  13549. #hasElementChanged(serialized) {
  13550. const {
  13551. value,
  13552. fontSize,
  13553. color,
  13554. rect,
  13555. pageIndex
  13556. } = this.#initialData;
  13557. return serialized.value !== value || serialized.fontSize !== fontSize || serialized.rect.some((x, i) => Math.abs(x - rect[i]) >= 1) || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
  13558. }
  13559. #cheatInitialRect(delayed = false) {
  13560. if (!this.annotationElementId) {
  13561. return;
  13562. }
  13563. this.#setEditorDimensions();
  13564. if (!delayed && (this.width === 0 || this.height === 0)) {
  13565. setTimeout(() => this.#cheatInitialRect(true), 0);
  13566. return;
  13567. }
  13568. const padding = FreeTextEditor._internalPadding * this.parentScale;
  13569. this.#initialData.rect = this.getRect(padding, padding);
  13570. }
  13571. }
  13572. exports.FreeTextEditor = FreeTextEditor;
  13573. /***/ }),
  13574. /* 29 */
  13575. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  13576. Object.defineProperty(exports, "__esModule", ({
  13577. value: true
  13578. }));
  13579. exports.StampAnnotationElement = exports.InkAnnotationElement = exports.FreeTextAnnotationElement = exports.AnnotationLayer = void 0;
  13580. var _util = __w_pdfjs_require__(1);
  13581. var _display_utils = __w_pdfjs_require__(6);
  13582. var _annotation_storage = __w_pdfjs_require__(3);
  13583. var _scripting_utils = __w_pdfjs_require__(30);
  13584. var _displayL10n_utils = __w_pdfjs_require__(31);
  13585. var _xfa_layer = __w_pdfjs_require__(32);
  13586. const DEFAULT_TAB_INDEX = 1000;
  13587. const DEFAULT_FONT_SIZE = 9;
  13588. const GetElementsByNameSet = new WeakSet();
  13589. function getRectDims(rect) {
  13590. return {
  13591. width: rect[2] - rect[0],
  13592. height: rect[3] - rect[1]
  13593. };
  13594. }
  13595. class AnnotationElementFactory {
  13596. static create(parameters) {
  13597. const subtype = parameters.data.annotationType;
  13598. switch (subtype) {
  13599. case _util.AnnotationType.LINK:
  13600. return new LinkAnnotationElement(parameters);
  13601. case _util.AnnotationType.TEXT:
  13602. return new TextAnnotationElement(parameters);
  13603. case _util.AnnotationType.WIDGET:
  13604. const fieldType = parameters.data.fieldType;
  13605. switch (fieldType) {
  13606. case "Tx":
  13607. return new TextWidgetAnnotationElement(parameters);
  13608. case "Btn":
  13609. if (parameters.data.radioButton) {
  13610. return new RadioButtonWidgetAnnotationElement(parameters);
  13611. } else if (parameters.data.checkBox) {
  13612. return new CheckboxWidgetAnnotationElement(parameters);
  13613. }
  13614. return new PushButtonWidgetAnnotationElement(parameters);
  13615. case "Ch":
  13616. return new ChoiceWidgetAnnotationElement(parameters);
  13617. case "Sig":
  13618. return new SignatureWidgetAnnotationElement(parameters);
  13619. }
  13620. return new WidgetAnnotationElement(parameters);
  13621. case _util.AnnotationType.POPUP:
  13622. return new PopupAnnotationElement(parameters);
  13623. case _util.AnnotationType.FREETEXT:
  13624. return new FreeTextAnnotationElement(parameters);
  13625. case _util.AnnotationType.LINE:
  13626. return new LineAnnotationElement(parameters);
  13627. case _util.AnnotationType.SQUARE:
  13628. return new SquareAnnotationElement(parameters);
  13629. case _util.AnnotationType.CIRCLE:
  13630. return new CircleAnnotationElement(parameters);
  13631. case _util.AnnotationType.POLYLINE:
  13632. return new PolylineAnnotationElement(parameters);
  13633. case _util.AnnotationType.CARET:
  13634. return new CaretAnnotationElement(parameters);
  13635. case _util.AnnotationType.INK:
  13636. return new InkAnnotationElement(parameters);
  13637. case _util.AnnotationType.POLYGON:
  13638. return new PolygonAnnotationElement(parameters);
  13639. case _util.AnnotationType.HIGHLIGHT:
  13640. return new HighlightAnnotationElement(parameters);
  13641. case _util.AnnotationType.UNDERLINE:
  13642. return new UnderlineAnnotationElement(parameters);
  13643. case _util.AnnotationType.SQUIGGLY:
  13644. return new SquigglyAnnotationElement(parameters);
  13645. case _util.AnnotationType.STRIKEOUT:
  13646. return new StrikeOutAnnotationElement(parameters);
  13647. case _util.AnnotationType.STAMP:
  13648. return new StampAnnotationElement(parameters);
  13649. case _util.AnnotationType.FILEATTACHMENT:
  13650. return new FileAttachmentAnnotationElement(parameters);
  13651. default:
  13652. return new AnnotationElement(parameters);
  13653. }
  13654. }
  13655. }
  13656. class AnnotationElement {
  13657. #hasBorder = false;
  13658. constructor(parameters, {
  13659. isRenderable = false,
  13660. ignoreBorder = false,
  13661. createQuadrilaterals = false
  13662. } = {}) {
  13663. this.isRenderable = isRenderable;
  13664. this.data = parameters.data;
  13665. this.layer = parameters.layer;
  13666. this.linkService = parameters.linkService;
  13667. this.downloadManager = parameters.downloadManager;
  13668. this.imageResourcesPath = parameters.imageResourcesPath;
  13669. this.renderForms = parameters.renderForms;
  13670. this.svgFactory = parameters.svgFactory;
  13671. this.annotationStorage = parameters.annotationStorage;
  13672. this.enableScripting = parameters.enableScripting;
  13673. this.hasJSActions = parameters.hasJSActions;
  13674. this._fieldObjects = parameters.fieldObjects;
  13675. this.parent = parameters.parent;
  13676. if (isRenderable) {
  13677. this.container = this._createContainer(ignoreBorder);
  13678. }
  13679. if (createQuadrilaterals) {
  13680. this._createQuadrilaterals();
  13681. }
  13682. }
  13683. _createContainer(ignoreBorder) {
  13684. const {
  13685. data,
  13686. parent: {
  13687. page,
  13688. viewport
  13689. }
  13690. } = this;
  13691. const container = document.createElement("section");
  13692. container.setAttribute("data-annotation-id", data.id);
  13693. container.style.zIndex = this.parent.zIndex++;
  13694. if (this.data.popupRef) {
  13695. container.setAttribute("aria-haspopup", "dialog");
  13696. }
  13697. if (data.noRotate) {
  13698. container.classList.add("norotate");
  13699. }
  13700. const {
  13701. pageWidth,
  13702. pageHeight,
  13703. pageX,
  13704. pageY
  13705. } = viewport.rawDims;
  13706. if (!data.rect || this instanceof PopupAnnotationElement) {
  13707. const {
  13708. rotation
  13709. } = data;
  13710. if (!data.hasOwnCanvas && rotation !== 0) {
  13711. this.setRotation(rotation, container);
  13712. }
  13713. return container;
  13714. }
  13715. const {
  13716. width,
  13717. height
  13718. } = getRectDims(data.rect);
  13719. const rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
  13720. if (!ignoreBorder && data.borderStyle.width > 0) {
  13721. container.style.borderWidth = `${data.borderStyle.width}px`;
  13722. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  13723. const verticalRadius = data.borderStyle.verticalCornerRadius;
  13724. if (horizontalRadius > 0 || verticalRadius > 0) {
  13725. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  13726. container.style.borderRadius = radius;
  13727. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  13728. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  13729. container.style.borderRadius = radius;
  13730. }
  13731. switch (data.borderStyle.style) {
  13732. case _util.AnnotationBorderStyleType.SOLID:
  13733. container.style.borderStyle = "solid";
  13734. break;
  13735. case _util.AnnotationBorderStyleType.DASHED:
  13736. container.style.borderStyle = "dashed";
  13737. break;
  13738. case _util.AnnotationBorderStyleType.BEVELED:
  13739. (0, _util.warn)("Unimplemented border style: beveled");
  13740. break;
  13741. case _util.AnnotationBorderStyleType.INSET:
  13742. (0, _util.warn)("Unimplemented border style: inset");
  13743. break;
  13744. case _util.AnnotationBorderStyleType.UNDERLINE:
  13745. container.style.borderBottomStyle = "solid";
  13746. break;
  13747. default:
  13748. break;
  13749. }
  13750. const borderColor = data.borderColor || null;
  13751. if (borderColor) {
  13752. this.#hasBorder = true;
  13753. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  13754. } else {
  13755. container.style.borderWidth = 0;
  13756. }
  13757. }
  13758. container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  13759. container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  13760. const {
  13761. rotation
  13762. } = data;
  13763. if (data.hasOwnCanvas || rotation === 0) {
  13764. container.style.width = `${100 * width / pageWidth}%`;
  13765. container.style.height = `${100 * height / pageHeight}%`;
  13766. } else {
  13767. this.setRotation(rotation, container);
  13768. }
  13769. return container;
  13770. }
  13771. setRotation(angle, container = this.container) {
  13772. if (!this.data.rect) {
  13773. return;
  13774. }
  13775. const {
  13776. pageWidth,
  13777. pageHeight
  13778. } = this.parent.viewport.rawDims;
  13779. const {
  13780. width,
  13781. height
  13782. } = getRectDims(this.data.rect);
  13783. let elementWidth, elementHeight;
  13784. if (angle % 180 === 0) {
  13785. elementWidth = 100 * width / pageWidth;
  13786. elementHeight = 100 * height / pageHeight;
  13787. } else {
  13788. elementWidth = 100 * height / pageWidth;
  13789. elementHeight = 100 * width / pageHeight;
  13790. }
  13791. container.style.width = `${elementWidth}%`;
  13792. container.style.height = `${elementHeight}%`;
  13793. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  13794. }
  13795. get _commonActions() {
  13796. const setColor = (jsName, styleName, event) => {
  13797. const color = event.detail[jsName];
  13798. const colorType = color[0];
  13799. const colorArray = color.slice(1);
  13800. event.target.style[styleName] = _scripting_utils.ColorConverters[`${colorType}_HTML`](colorArray);
  13801. this.annotationStorage.setValue(this.data.id, {
  13802. [styleName]: _scripting_utils.ColorConverters[`${colorType}_rgb`](colorArray)
  13803. });
  13804. };
  13805. return (0, _util.shadow)(this, "_commonActions", {
  13806. display: event => {
  13807. const {
  13808. display
  13809. } = event.detail;
  13810. const hidden = display % 2 === 1;
  13811. this.container.style.visibility = hidden ? "hidden" : "visible";
  13812. this.annotationStorage.setValue(this.data.id, {
  13813. noView: hidden,
  13814. noPrint: display === 1 || display === 2
  13815. });
  13816. },
  13817. print: event => {
  13818. this.annotationStorage.setValue(this.data.id, {
  13819. noPrint: !event.detail.print
  13820. });
  13821. },
  13822. hidden: event => {
  13823. const {
  13824. hidden
  13825. } = event.detail;
  13826. this.container.style.visibility = hidden ? "hidden" : "visible";
  13827. this.annotationStorage.setValue(this.data.id, {
  13828. noPrint: hidden,
  13829. noView: hidden
  13830. });
  13831. },
  13832. focus: event => {
  13833. setTimeout(() => event.target.focus({
  13834. preventScroll: false
  13835. }), 0);
  13836. },
  13837. userName: event => {
  13838. event.target.title = event.detail.userName;
  13839. },
  13840. readonly: event => {
  13841. event.target.disabled = event.detail.readonly;
  13842. },
  13843. required: event => {
  13844. this._setRequired(event.target, event.detail.required);
  13845. },
  13846. bgColor: event => {
  13847. setColor("bgColor", "backgroundColor", event);
  13848. },
  13849. fillColor: event => {
  13850. setColor("fillColor", "backgroundColor", event);
  13851. },
  13852. fgColor: event => {
  13853. setColor("fgColor", "color", event);
  13854. },
  13855. textColor: event => {
  13856. setColor("textColor", "color", event);
  13857. },
  13858. borderColor: event => {
  13859. setColor("borderColor", "borderColor", event);
  13860. },
  13861. strokeColor: event => {
  13862. setColor("strokeColor", "borderColor", event);
  13863. },
  13864. rotation: event => {
  13865. const angle = event.detail.rotation;
  13866. this.setRotation(angle);
  13867. this.annotationStorage.setValue(this.data.id, {
  13868. rotation: angle
  13869. });
  13870. }
  13871. });
  13872. }
  13873. _dispatchEventFromSandbox(actions, jsEvent) {
  13874. const commonActions = this._commonActions;
  13875. for (const name of Object.keys(jsEvent.detail)) {
  13876. const action = actions[name] || commonActions[name];
  13877. action?.(jsEvent);
  13878. }
  13879. }
  13880. _setDefaultPropertiesFromJS(element) {
  13881. if (!this.enableScripting) {
  13882. return;
  13883. }
  13884. const storedData = this.annotationStorage.getRawValue(this.data.id);
  13885. if (!storedData) {
  13886. return;
  13887. }
  13888. const commonActions = this._commonActions;
  13889. for (const [actionName, detail] of Object.entries(storedData)) {
  13890. const action = commonActions[actionName];
  13891. if (action) {
  13892. const eventProxy = {
  13893. detail: {
  13894. [actionName]: detail
  13895. },
  13896. target: element
  13897. };
  13898. action(eventProxy);
  13899. delete storedData[actionName];
  13900. }
  13901. }
  13902. }
  13903. _createQuadrilaterals() {
  13904. if (!this.container) {
  13905. return;
  13906. }
  13907. const {
  13908. quadPoints
  13909. } = this.data;
  13910. if (!quadPoints) {
  13911. return;
  13912. }
  13913. const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect;
  13914. if (quadPoints.length === 1) {
  13915. const [, {
  13916. x: trX,
  13917. y: trY
  13918. }, {
  13919. x: blX,
  13920. y: blY
  13921. }] = quadPoints[0];
  13922. if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
  13923. return;
  13924. }
  13925. }
  13926. const {
  13927. style
  13928. } = this.container;
  13929. let svgBuffer;
  13930. if (this.#hasBorder) {
  13931. const {
  13932. borderColor,
  13933. borderWidth
  13934. } = style;
  13935. style.borderWidth = 0;
  13936. svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];
  13937. this.container.classList.add("hasBorder");
  13938. }
  13939. const width = rectTrX - rectBlX;
  13940. const height = rectTrY - rectBlY;
  13941. const {
  13942. svgFactory
  13943. } = this;
  13944. const svg = svgFactory.createElement("svg");
  13945. svg.classList.add("quadrilateralsContainer");
  13946. svg.setAttribute("width", 0);
  13947. svg.setAttribute("height", 0);
  13948. const defs = svgFactory.createElement("defs");
  13949. svg.append(defs);
  13950. const clipPath = svgFactory.createElement("clipPath");
  13951. const id = `clippath_${this.data.id}`;
  13952. clipPath.setAttribute("id", id);
  13953. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  13954. defs.append(clipPath);
  13955. for (const [, {
  13956. x: trX,
  13957. y: trY
  13958. }, {
  13959. x: blX,
  13960. y: blY
  13961. }] of quadPoints) {
  13962. const rect = svgFactory.createElement("rect");
  13963. const x = (blX - rectBlX) / width;
  13964. const y = (rectTrY - trY) / height;
  13965. const rectWidth = (trX - blX) / width;
  13966. const rectHeight = (trY - blY) / height;
  13967. rect.setAttribute("x", x);
  13968. rect.setAttribute("y", y);
  13969. rect.setAttribute("width", rectWidth);
  13970. rect.setAttribute("height", rectHeight);
  13971. clipPath.append(rect);
  13972. svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
  13973. }
  13974. if (this.#hasBorder) {
  13975. svgBuffer.push(`</g></svg>')`);
  13976. style.backgroundImage = svgBuffer.join("");
  13977. }
  13978. this.container.append(svg);
  13979. this.container.style.clipPath = `url(#${id})`;
  13980. }
  13981. _createPopup() {
  13982. const {
  13983. container,
  13984. data
  13985. } = this;
  13986. container.setAttribute("aria-haspopup", "dialog");
  13987. const popup = new PopupAnnotationElement({
  13988. data: {
  13989. color: data.color,
  13990. titleObj: data.titleObj,
  13991. modificationDate: data.modificationDate,
  13992. contentsObj: data.contentsObj,
  13993. richText: data.richText,
  13994. parentRect: data.rect,
  13995. borderStyle: 0,
  13996. id: `popup_${data.id}`,
  13997. rotation: data.rotation
  13998. },
  13999. parent: this.parent,
  14000. elements: [this]
  14001. });
  14002. this.parent.div.append(popup.render());
  14003. }
  14004. render() {
  14005. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  14006. }
  14007. _getElementsByName(name, skipId = null) {
  14008. const fields = [];
  14009. if (this._fieldObjects) {
  14010. const fieldObj = this._fieldObjects[name];
  14011. if (fieldObj) {
  14012. for (const {
  14013. page,
  14014. id,
  14015. exportValues
  14016. } of fieldObj) {
  14017. if (page === -1) {
  14018. continue;
  14019. }
  14020. if (id === skipId) {
  14021. continue;
  14022. }
  14023. const exportValue = typeof exportValues === "string" ? exportValues : null;
  14024. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  14025. if (domElement && !GetElementsByNameSet.has(domElement)) {
  14026. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  14027. continue;
  14028. }
  14029. fields.push({
  14030. id,
  14031. exportValue,
  14032. domElement
  14033. });
  14034. }
  14035. }
  14036. return fields;
  14037. }
  14038. for (const domElement of document.getElementsByName(name)) {
  14039. const {
  14040. exportValue
  14041. } = domElement;
  14042. const id = domElement.getAttribute("data-element-id");
  14043. if (id === skipId) {
  14044. continue;
  14045. }
  14046. if (!GetElementsByNameSet.has(domElement)) {
  14047. continue;
  14048. }
  14049. fields.push({
  14050. id,
  14051. exportValue,
  14052. domElement
  14053. });
  14054. }
  14055. return fields;
  14056. }
  14057. show() {
  14058. if (this.container) {
  14059. this.container.hidden = false;
  14060. }
  14061. this.popup?.maybeShow();
  14062. }
  14063. hide() {
  14064. if (this.container) {
  14065. this.container.hidden = true;
  14066. }
  14067. this.popup?.forceHide();
  14068. }
  14069. getElementsToTriggerPopup() {
  14070. return this.container;
  14071. }
  14072. addHighlightArea() {
  14073. const triggers = this.getElementsToTriggerPopup();
  14074. if (Array.isArray(triggers)) {
  14075. for (const element of triggers) {
  14076. element.classList.add("highlightArea");
  14077. }
  14078. } else {
  14079. triggers.classList.add("highlightArea");
  14080. }
  14081. }
  14082. _editOnDoubleClick() {
  14083. const {
  14084. annotationEditorType: mode,
  14085. data: {
  14086. id: editId
  14087. }
  14088. } = this;
  14089. this.container.addEventListener("dblclick", () => {
  14090. this.linkService.eventBus?.dispatch("switchannotationeditormode", {
  14091. source: this,
  14092. mode,
  14093. editId
  14094. });
  14095. });
  14096. }
  14097. }
  14098. class LinkAnnotationElement extends AnnotationElement {
  14099. constructor(parameters, options = null) {
  14100. super(parameters, {
  14101. isRenderable: true,
  14102. ignoreBorder: !!options?.ignoreBorder,
  14103. createQuadrilaterals: true
  14104. });
  14105. this.isTooltipOnly = parameters.data.isTooltipOnly;
  14106. }
  14107. render() {
  14108. const {
  14109. data,
  14110. linkService
  14111. } = this;
  14112. const link = document.createElement("a");
  14113. link.setAttribute("data-element-id", data.id);
  14114. let isBound = false;
  14115. if (data.url) {
  14116. linkService.addLinkAttributes(link, data.url, data.newWindow);
  14117. isBound = true;
  14118. } else if (data.action) {
  14119. this._bindNamedAction(link, data.action);
  14120. isBound = true;
  14121. } else if (data.attachment) {
  14122. this._bindAttachment(link, data.attachment);
  14123. isBound = true;
  14124. } else if (data.setOCGState) {
  14125. this.#bindSetOCGState(link, data.setOCGState);
  14126. isBound = true;
  14127. } else if (data.dest) {
  14128. this._bindLink(link, data.dest);
  14129. isBound = true;
  14130. } else {
  14131. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  14132. this._bindJSAction(link, data);
  14133. isBound = true;
  14134. }
  14135. if (data.resetForm) {
  14136. this._bindResetFormAction(link, data.resetForm);
  14137. isBound = true;
  14138. } else if (this.isTooltipOnly && !isBound) {
  14139. this._bindLink(link, "");
  14140. isBound = true;
  14141. }
  14142. }
  14143. this.container.classList.add("linkAnnotation");
  14144. if (isBound) {
  14145. this.container.append(link);
  14146. }
  14147. return this.container;
  14148. }
  14149. #setInternalLink() {
  14150. this.container.setAttribute("data-internal-link", "");
  14151. }
  14152. _bindLink(link, destination) {
  14153. link.href = this.linkService.getDestinationHash(destination);
  14154. link.onclick = () => {
  14155. if (destination) {
  14156. this.linkService.goToDestination(destination);
  14157. }
  14158. return false;
  14159. };
  14160. if (destination || destination === "") {
  14161. this.#setInternalLink();
  14162. }
  14163. }
  14164. _bindNamedAction(link, action) {
  14165. link.href = this.linkService.getAnchorUrl("");
  14166. link.onclick = () => {
  14167. this.linkService.executeNamedAction(action);
  14168. return false;
  14169. };
  14170. this.#setInternalLink();
  14171. }
  14172. _bindAttachment(link, attachment) {
  14173. link.href = this.linkService.getAnchorUrl("");
  14174. link.onclick = () => {
  14175. this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
  14176. return false;
  14177. };
  14178. this.#setInternalLink();
  14179. }
  14180. #bindSetOCGState(link, action) {
  14181. link.href = this.linkService.getAnchorUrl("");
  14182. link.onclick = () => {
  14183. this.linkService.executeSetOCGState(action);
  14184. return false;
  14185. };
  14186. this.#setInternalLink();
  14187. }
  14188. _bindJSAction(link, data) {
  14189. link.href = this.linkService.getAnchorUrl("");
  14190. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  14191. for (const name of Object.keys(data.actions)) {
  14192. const jsName = map.get(name);
  14193. if (!jsName) {
  14194. continue;
  14195. }
  14196. link[jsName] = () => {
  14197. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14198. source: this,
  14199. detail: {
  14200. id: data.id,
  14201. name
  14202. }
  14203. });
  14204. return false;
  14205. };
  14206. }
  14207. if (!link.onclick) {
  14208. link.onclick = () => false;
  14209. }
  14210. this.#setInternalLink();
  14211. }
  14212. _bindResetFormAction(link, resetForm) {
  14213. const otherClickAction = link.onclick;
  14214. if (!otherClickAction) {
  14215. link.href = this.linkService.getAnchorUrl("");
  14216. }
  14217. this.#setInternalLink();
  14218. if (!this._fieldObjects) {
  14219. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  14220. if (!otherClickAction) {
  14221. link.onclick = () => false;
  14222. }
  14223. return;
  14224. }
  14225. link.onclick = () => {
  14226. otherClickAction?.();
  14227. const {
  14228. fields: resetFormFields,
  14229. refs: resetFormRefs,
  14230. include
  14231. } = resetForm;
  14232. const allFields = [];
  14233. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  14234. const fieldIds = new Set(resetFormRefs);
  14235. for (const fieldName of resetFormFields) {
  14236. const fields = this._fieldObjects[fieldName] || [];
  14237. for (const {
  14238. id
  14239. } of fields) {
  14240. fieldIds.add(id);
  14241. }
  14242. }
  14243. for (const fields of Object.values(this._fieldObjects)) {
  14244. for (const field of fields) {
  14245. if (fieldIds.has(field.id) === include) {
  14246. allFields.push(field);
  14247. }
  14248. }
  14249. }
  14250. } else {
  14251. for (const fields of Object.values(this._fieldObjects)) {
  14252. allFields.push(...fields);
  14253. }
  14254. }
  14255. const storage = this.annotationStorage;
  14256. const allIds = [];
  14257. for (const field of allFields) {
  14258. const {
  14259. id
  14260. } = field;
  14261. allIds.push(id);
  14262. switch (field.type) {
  14263. case "text":
  14264. {
  14265. const value = field.defaultValue || "";
  14266. storage.setValue(id, {
  14267. value
  14268. });
  14269. break;
  14270. }
  14271. case "checkbox":
  14272. case "radiobutton":
  14273. {
  14274. const value = field.defaultValue === field.exportValues;
  14275. storage.setValue(id, {
  14276. value
  14277. });
  14278. break;
  14279. }
  14280. case "combobox":
  14281. case "listbox":
  14282. {
  14283. const value = field.defaultValue || "";
  14284. storage.setValue(id, {
  14285. value
  14286. });
  14287. break;
  14288. }
  14289. default:
  14290. continue;
  14291. }
  14292. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  14293. if (!domElement) {
  14294. continue;
  14295. } else if (!GetElementsByNameSet.has(domElement)) {
  14296. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  14297. continue;
  14298. }
  14299. domElement.dispatchEvent(new Event("resetform"));
  14300. }
  14301. if (this.enableScripting) {
  14302. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14303. source: this,
  14304. detail: {
  14305. id: "app",
  14306. ids: allIds,
  14307. name: "ResetForm"
  14308. }
  14309. });
  14310. }
  14311. return false;
  14312. };
  14313. }
  14314. }
  14315. class TextAnnotationElement extends AnnotationElement {
  14316. constructor(parameters) {
  14317. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  14318. super(parameters, {
  14319. isRenderable
  14320. });
  14321. }
  14322. render() {
  14323. this.container.classList.add("textAnnotation");
  14324. const image = document.createElement("img");
  14325. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  14326. image.alt = "[{{type}} Annotation]";
  14327. image.dataset.l10nId = "text_annotation_type";
  14328. image.dataset.l10nArgs = JSON.stringify({
  14329. type: this.data.name
  14330. });
  14331. if (!this.data.popupRef) {
  14332. this._createPopup();
  14333. }
  14334. this.container.append(image);
  14335. return this.container;
  14336. }
  14337. }
  14338. class WidgetAnnotationElement extends AnnotationElement {
  14339. render() {
  14340. if (this.data.alternativeText) {
  14341. this.container.title = this.data.alternativeText;
  14342. }
  14343. return this.container;
  14344. }
  14345. showElementAndHideCanvas(element) {
  14346. if (this.data.hasOwnCanvas) {
  14347. if (element.previousSibling?.nodeName === "CANVAS") {
  14348. element.previousSibling.hidden = true;
  14349. }
  14350. element.hidden = false;
  14351. }
  14352. }
  14353. _getKeyModifier(event) {
  14354. const {
  14355. isWin,
  14356. isMac
  14357. } = _util.FeatureTest.platform;
  14358. return isWin && event.ctrlKey || isMac && event.metaKey;
  14359. }
  14360. _setEventListener(element, baseName, eventName, valueGetter) {
  14361. if (baseName.includes("mouse")) {
  14362. element.addEventListener(baseName, event => {
  14363. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14364. source: this,
  14365. detail: {
  14366. id: this.data.id,
  14367. name: eventName,
  14368. value: valueGetter(event),
  14369. shift: event.shiftKey,
  14370. modifier: this._getKeyModifier(event)
  14371. }
  14372. });
  14373. });
  14374. } else {
  14375. element.addEventListener(baseName, event => {
  14376. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14377. source: this,
  14378. detail: {
  14379. id: this.data.id,
  14380. name: eventName,
  14381. value: valueGetter(event)
  14382. }
  14383. });
  14384. });
  14385. }
  14386. }
  14387. _setEventListeners(element, names, getter) {
  14388. for (const [baseName, eventName] of names) {
  14389. if (eventName === "Action" || this.data.actions?.[eventName]) {
  14390. this._setEventListener(element, baseName, eventName, getter);
  14391. }
  14392. }
  14393. }
  14394. _setBackgroundColor(element) {
  14395. const color = this.data.backgroundColor || null;
  14396. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  14397. }
  14398. _setTextStyle(element) {
  14399. const TEXT_ALIGNMENT = ["left", "center", "right"];
  14400. const {
  14401. fontColor
  14402. } = this.data.defaultAppearanceData;
  14403. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  14404. const style = element.style;
  14405. let computedFontSize;
  14406. const BORDER_SIZE = 2;
  14407. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  14408. if (this.data.multiLine) {
  14409. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14410. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  14411. const lineHeight = height / numberOfLines;
  14412. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
  14413. } else {
  14414. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  14415. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
  14416. }
  14417. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  14418. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  14419. if (this.data.textAlignment !== null) {
  14420. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  14421. }
  14422. }
  14423. _setRequired(element, isRequired) {
  14424. if (isRequired) {
  14425. element.setAttribute("required", true);
  14426. } else {
  14427. element.removeAttribute("required");
  14428. }
  14429. element.setAttribute("aria-required", isRequired);
  14430. }
  14431. }
  14432. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  14433. constructor(parameters) {
  14434. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  14435. super(parameters, {
  14436. isRenderable
  14437. });
  14438. }
  14439. setPropertyOnSiblings(base, key, value, keyInStorage) {
  14440. const storage = this.annotationStorage;
  14441. for (const element of this._getElementsByName(base.name, base.id)) {
  14442. if (element.domElement) {
  14443. element.domElement[key] = value;
  14444. }
  14445. storage.setValue(element.id, {
  14446. [keyInStorage]: value
  14447. });
  14448. }
  14449. }
  14450. render() {
  14451. const storage = this.annotationStorage;
  14452. const id = this.data.id;
  14453. this.container.classList.add("textWidgetAnnotation");
  14454. let element = null;
  14455. if (this.renderForms) {
  14456. const storedData = storage.getValue(id, {
  14457. value: this.data.fieldValue
  14458. });
  14459. let textContent = storedData.value || "";
  14460. const maxLen = storage.getValue(id, {
  14461. charLimit: this.data.maxLen
  14462. }).charLimit;
  14463. if (maxLen && textContent.length > maxLen) {
  14464. textContent = textContent.slice(0, maxLen);
  14465. }
  14466. let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
  14467. if (fieldFormattedValues && this.data.comb) {
  14468. fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
  14469. }
  14470. const elementData = {
  14471. userValue: textContent,
  14472. formattedValue: fieldFormattedValues,
  14473. lastCommittedValue: null,
  14474. commitKey: 1
  14475. };
  14476. if (this.data.multiLine) {
  14477. element = document.createElement("textarea");
  14478. element.textContent = fieldFormattedValues ?? textContent;
  14479. if (this.data.doNotScroll) {
  14480. element.style.overflowY = "hidden";
  14481. }
  14482. } else {
  14483. element = document.createElement("input");
  14484. element.type = "text";
  14485. element.setAttribute("value", fieldFormattedValues ?? textContent);
  14486. if (this.data.doNotScroll) {
  14487. element.style.overflowX = "hidden";
  14488. }
  14489. }
  14490. if (this.data.hasOwnCanvas) {
  14491. element.hidden = true;
  14492. }
  14493. GetElementsByNameSet.add(element);
  14494. element.setAttribute("data-element-id", id);
  14495. element.disabled = this.data.readOnly;
  14496. element.name = this.data.fieldName;
  14497. element.tabIndex = DEFAULT_TAB_INDEX;
  14498. this._setRequired(element, this.data.required);
  14499. if (maxLen) {
  14500. element.maxLength = maxLen;
  14501. }
  14502. element.addEventListener("input", event => {
  14503. storage.setValue(id, {
  14504. value: event.target.value
  14505. });
  14506. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  14507. elementData.formattedValue = null;
  14508. });
  14509. element.addEventListener("resetform", event => {
  14510. const defaultValue = this.data.defaultFieldValue ?? "";
  14511. element.value = elementData.userValue = defaultValue;
  14512. elementData.formattedValue = null;
  14513. });
  14514. let blurListener = event => {
  14515. const {
  14516. formattedValue
  14517. } = elementData;
  14518. if (formattedValue !== null && formattedValue !== undefined) {
  14519. event.target.value = formattedValue;
  14520. }
  14521. event.target.scrollLeft = 0;
  14522. };
  14523. if (this.enableScripting && this.hasJSActions) {
  14524. element.addEventListener("focus", event => {
  14525. const {
  14526. target
  14527. } = event;
  14528. if (elementData.userValue) {
  14529. target.value = elementData.userValue;
  14530. }
  14531. elementData.lastCommittedValue = target.value;
  14532. elementData.commitKey = 1;
  14533. });
  14534. element.addEventListener("updatefromsandbox", jsEvent => {
  14535. this.showElementAndHideCanvas(jsEvent.target);
  14536. const actions = {
  14537. value(event) {
  14538. elementData.userValue = event.detail.value ?? "";
  14539. storage.setValue(id, {
  14540. value: elementData.userValue.toString()
  14541. });
  14542. event.target.value = elementData.userValue;
  14543. },
  14544. formattedValue(event) {
  14545. const {
  14546. formattedValue
  14547. } = event.detail;
  14548. elementData.formattedValue = formattedValue;
  14549. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  14550. event.target.value = formattedValue;
  14551. }
  14552. storage.setValue(id, {
  14553. formattedValue
  14554. });
  14555. },
  14556. selRange(event) {
  14557. event.target.setSelectionRange(...event.detail.selRange);
  14558. },
  14559. charLimit: event => {
  14560. const {
  14561. charLimit
  14562. } = event.detail;
  14563. const {
  14564. target
  14565. } = event;
  14566. if (charLimit === 0) {
  14567. target.removeAttribute("maxLength");
  14568. return;
  14569. }
  14570. target.setAttribute("maxLength", charLimit);
  14571. let value = elementData.userValue;
  14572. if (!value || value.length <= charLimit) {
  14573. return;
  14574. }
  14575. value = value.slice(0, charLimit);
  14576. target.value = elementData.userValue = value;
  14577. storage.setValue(id, {
  14578. value
  14579. });
  14580. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14581. source: this,
  14582. detail: {
  14583. id,
  14584. name: "Keystroke",
  14585. value,
  14586. willCommit: true,
  14587. commitKey: 1,
  14588. selStart: target.selectionStart,
  14589. selEnd: target.selectionEnd
  14590. }
  14591. });
  14592. }
  14593. };
  14594. this._dispatchEventFromSandbox(actions, jsEvent);
  14595. });
  14596. element.addEventListener("keydown", event => {
  14597. elementData.commitKey = 1;
  14598. let commitKey = -1;
  14599. if (event.key === "Escape") {
  14600. commitKey = 0;
  14601. } else if (event.key === "Enter" && !this.data.multiLine) {
  14602. commitKey = 2;
  14603. } else if (event.key === "Tab") {
  14604. elementData.commitKey = 3;
  14605. }
  14606. if (commitKey === -1) {
  14607. return;
  14608. }
  14609. const {
  14610. value
  14611. } = event.target;
  14612. if (elementData.lastCommittedValue === value) {
  14613. return;
  14614. }
  14615. elementData.lastCommittedValue = value;
  14616. elementData.userValue = value;
  14617. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14618. source: this,
  14619. detail: {
  14620. id,
  14621. name: "Keystroke",
  14622. value,
  14623. willCommit: true,
  14624. commitKey,
  14625. selStart: event.target.selectionStart,
  14626. selEnd: event.target.selectionEnd
  14627. }
  14628. });
  14629. });
  14630. const _blurListener = blurListener;
  14631. blurListener = null;
  14632. element.addEventListener("blur", event => {
  14633. if (!event.relatedTarget) {
  14634. return;
  14635. }
  14636. const {
  14637. value
  14638. } = event.target;
  14639. elementData.userValue = value;
  14640. if (elementData.lastCommittedValue !== value) {
  14641. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14642. source: this,
  14643. detail: {
  14644. id,
  14645. name: "Keystroke",
  14646. value,
  14647. willCommit: true,
  14648. commitKey: elementData.commitKey,
  14649. selStart: event.target.selectionStart,
  14650. selEnd: event.target.selectionEnd
  14651. }
  14652. });
  14653. }
  14654. _blurListener(event);
  14655. });
  14656. if (this.data.actions?.Keystroke) {
  14657. element.addEventListener("beforeinput", event => {
  14658. elementData.lastCommittedValue = null;
  14659. const {
  14660. data,
  14661. target
  14662. } = event;
  14663. const {
  14664. value,
  14665. selectionStart,
  14666. selectionEnd
  14667. } = target;
  14668. let selStart = selectionStart,
  14669. selEnd = selectionEnd;
  14670. switch (event.inputType) {
  14671. case "deleteWordBackward":
  14672. {
  14673. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  14674. if (match) {
  14675. selStart -= match[0].length;
  14676. }
  14677. break;
  14678. }
  14679. case "deleteWordForward":
  14680. {
  14681. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  14682. if (match) {
  14683. selEnd += match[0].length;
  14684. }
  14685. break;
  14686. }
  14687. case "deleteContentBackward":
  14688. if (selectionStart === selectionEnd) {
  14689. selStart -= 1;
  14690. }
  14691. break;
  14692. case "deleteContentForward":
  14693. if (selectionStart === selectionEnd) {
  14694. selEnd += 1;
  14695. }
  14696. break;
  14697. }
  14698. event.preventDefault();
  14699. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  14700. source: this,
  14701. detail: {
  14702. id,
  14703. name: "Keystroke",
  14704. value,
  14705. change: data || "",
  14706. willCommit: false,
  14707. selStart,
  14708. selEnd
  14709. }
  14710. });
  14711. });
  14712. }
  14713. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  14714. }
  14715. if (blurListener) {
  14716. element.addEventListener("blur", blurListener);
  14717. }
  14718. if (this.data.comb) {
  14719. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  14720. const combWidth = fieldWidth / maxLen;
  14721. element.classList.add("comb");
  14722. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  14723. }
  14724. } else {
  14725. element = document.createElement("div");
  14726. element.textContent = this.data.fieldValue;
  14727. element.style.verticalAlign = "middle";
  14728. element.style.display = "table-cell";
  14729. }
  14730. this._setTextStyle(element);
  14731. this._setBackgroundColor(element);
  14732. this._setDefaultPropertiesFromJS(element);
  14733. this.container.append(element);
  14734. return this.container;
  14735. }
  14736. }
  14737. class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
  14738. constructor(parameters) {
  14739. super(parameters, {
  14740. isRenderable: !!parameters.data.hasOwnCanvas
  14741. });
  14742. }
  14743. }
  14744. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  14745. constructor(parameters) {
  14746. super(parameters, {
  14747. isRenderable: parameters.renderForms
  14748. });
  14749. }
  14750. render() {
  14751. const storage = this.annotationStorage;
  14752. const data = this.data;
  14753. const id = data.id;
  14754. let value = storage.getValue(id, {
  14755. value: data.exportValue === data.fieldValue
  14756. }).value;
  14757. if (typeof value === "string") {
  14758. value = value !== "Off";
  14759. storage.setValue(id, {
  14760. value
  14761. });
  14762. }
  14763. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  14764. const element = document.createElement("input");
  14765. GetElementsByNameSet.add(element);
  14766. element.setAttribute("data-element-id", id);
  14767. element.disabled = data.readOnly;
  14768. this._setRequired(element, this.data.required);
  14769. element.type = "checkbox";
  14770. element.name = data.fieldName;
  14771. if (value) {
  14772. element.setAttribute("checked", true);
  14773. }
  14774. element.setAttribute("exportValue", data.exportValue);
  14775. element.tabIndex = DEFAULT_TAB_INDEX;
  14776. element.addEventListener("change", event => {
  14777. const {
  14778. name,
  14779. checked
  14780. } = event.target;
  14781. for (const checkbox of this._getElementsByName(name, id)) {
  14782. const curChecked = checked && checkbox.exportValue === data.exportValue;
  14783. if (checkbox.domElement) {
  14784. checkbox.domElement.checked = curChecked;
  14785. }
  14786. storage.setValue(checkbox.id, {
  14787. value: curChecked
  14788. });
  14789. }
  14790. storage.setValue(id, {
  14791. value: checked
  14792. });
  14793. });
  14794. element.addEventListener("resetform", event => {
  14795. const defaultValue = data.defaultFieldValue || "Off";
  14796. event.target.checked = defaultValue === data.exportValue;
  14797. });
  14798. if (this.enableScripting && this.hasJSActions) {
  14799. element.addEventListener("updatefromsandbox", jsEvent => {
  14800. const actions = {
  14801. value(event) {
  14802. event.target.checked = event.detail.value !== "Off";
  14803. storage.setValue(id, {
  14804. value: event.target.checked
  14805. });
  14806. }
  14807. };
  14808. this._dispatchEventFromSandbox(actions, jsEvent);
  14809. });
  14810. this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  14811. }
  14812. this._setBackgroundColor(element);
  14813. this._setDefaultPropertiesFromJS(element);
  14814. this.container.append(element);
  14815. return this.container;
  14816. }
  14817. }
  14818. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  14819. constructor(parameters) {
  14820. super(parameters, {
  14821. isRenderable: parameters.renderForms
  14822. });
  14823. }
  14824. render() {
  14825. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  14826. const storage = this.annotationStorage;
  14827. const data = this.data;
  14828. const id = data.id;
  14829. let value = storage.getValue(id, {
  14830. value: data.fieldValue === data.buttonValue
  14831. }).value;
  14832. if (typeof value === "string") {
  14833. value = value !== data.buttonValue;
  14834. storage.setValue(id, {
  14835. value
  14836. });
  14837. }
  14838. const element = document.createElement("input");
  14839. GetElementsByNameSet.add(element);
  14840. element.setAttribute("data-element-id", id);
  14841. element.disabled = data.readOnly;
  14842. this._setRequired(element, this.data.required);
  14843. element.type = "radio";
  14844. element.name = data.fieldName;
  14845. if (value) {
  14846. element.setAttribute("checked", true);
  14847. }
  14848. element.tabIndex = DEFAULT_TAB_INDEX;
  14849. element.addEventListener("change", event => {
  14850. const {
  14851. name,
  14852. checked
  14853. } = event.target;
  14854. for (const radio of this._getElementsByName(name, id)) {
  14855. storage.setValue(radio.id, {
  14856. value: false
  14857. });
  14858. }
  14859. storage.setValue(id, {
  14860. value: checked
  14861. });
  14862. });
  14863. element.addEventListener("resetform", event => {
  14864. const defaultValue = data.defaultFieldValue;
  14865. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  14866. });
  14867. if (this.enableScripting && this.hasJSActions) {
  14868. const pdfButtonValue = data.buttonValue;
  14869. element.addEventListener("updatefromsandbox", jsEvent => {
  14870. const actions = {
  14871. value: event => {
  14872. const checked = pdfButtonValue === event.detail.value;
  14873. for (const radio of this._getElementsByName(event.target.name)) {
  14874. const curChecked = checked && radio.id === id;
  14875. if (radio.domElement) {
  14876. radio.domElement.checked = curChecked;
  14877. }
  14878. storage.setValue(radio.id, {
  14879. value: curChecked
  14880. });
  14881. }
  14882. }
  14883. };
  14884. this._dispatchEventFromSandbox(actions, jsEvent);
  14885. });
  14886. this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  14887. }
  14888. this._setBackgroundColor(element);
  14889. this._setDefaultPropertiesFromJS(element);
  14890. this.container.append(element);
  14891. return this.container;
  14892. }
  14893. }
  14894. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  14895. constructor(parameters) {
  14896. super(parameters, {
  14897. ignoreBorder: parameters.data.hasAppearance
  14898. });
  14899. }
  14900. render() {
  14901. const container = super.render();
  14902. container.classList.add("buttonWidgetAnnotation", "pushButton");
  14903. if (this.data.alternativeText) {
  14904. container.title = this.data.alternativeText;
  14905. }
  14906. const linkElement = container.lastChild;
  14907. if (this.enableScripting && this.hasJSActions && linkElement) {
  14908. this._setDefaultPropertiesFromJS(linkElement);
  14909. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  14910. this._dispatchEventFromSandbox({}, jsEvent);
  14911. });
  14912. }
  14913. return container;
  14914. }
  14915. }
  14916. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  14917. constructor(parameters) {
  14918. super(parameters, {
  14919. isRenderable: parameters.renderForms
  14920. });
  14921. }
  14922. render() {
  14923. this.container.classList.add("choiceWidgetAnnotation");
  14924. const storage = this.annotationStorage;
  14925. const id = this.data.id;
  14926. const storedData = storage.getValue(id, {
  14927. value: this.data.fieldValue
  14928. });
  14929. const selectElement = document.createElement("select");
  14930. GetElementsByNameSet.add(selectElement);
  14931. selectElement.setAttribute("data-element-id", id);
  14932. selectElement.disabled = this.data.readOnly;
  14933. this._setRequired(selectElement, this.data.required);
  14934. selectElement.name = this.data.fieldName;
  14935. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  14936. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  14937. if (!this.data.combo) {
  14938. selectElement.size = this.data.options.length;
  14939. if (this.data.multiSelect) {
  14940. selectElement.multiple = true;
  14941. }
  14942. }
  14943. selectElement.addEventListener("resetform", event => {
  14944. const defaultValue = this.data.defaultFieldValue;
  14945. for (const option of selectElement.options) {
  14946. option.selected = option.value === defaultValue;
  14947. }
  14948. });
  14949. for (const option of this.data.options) {
  14950. const optionElement = document.createElement("option");
  14951. optionElement.textContent = option.displayValue;
  14952. optionElement.value = option.exportValue;
  14953. if (storedData.value.includes(option.exportValue)) {
  14954. optionElement.setAttribute("selected", true);
  14955. addAnEmptyEntry = false;
  14956. }
  14957. selectElement.append(optionElement);
  14958. }
  14959. let removeEmptyEntry = null;
  14960. if (addAnEmptyEntry) {
  14961. const noneOptionElement = document.createElement("option");
  14962. noneOptionElement.value = " ";
  14963. noneOptionElement.setAttribute("hidden", true);
  14964. noneOptionElement.setAttribute("selected", true);
  14965. selectElement.prepend(noneOptionElement);
  14966. removeEmptyEntry = () => {
  14967. noneOptionElement.remove();
  14968. selectElement.removeEventListener("input", removeEmptyEntry);
  14969. removeEmptyEntry = null;
  14970. };
  14971. selectElement.addEventListener("input", removeEmptyEntry);
  14972. }
  14973. const getValue = isExport => {
  14974. const name = isExport ? "value" : "textContent";
  14975. const {
  14976. options,
  14977. multiple
  14978. } = selectElement;
  14979. if (!multiple) {
  14980. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  14981. }
  14982. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  14983. };
  14984. let selectedValues = getValue(false);
  14985. const getItems = event => {
  14986. const options = event.target.options;
  14987. return Array.prototype.map.call(options, option => {
  14988. return {
  14989. displayValue: option.textContent,
  14990. exportValue: option.value
  14991. };
  14992. });
  14993. };
  14994. if (this.enableScripting && this.hasJSActions) {
  14995. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  14996. const actions = {
  14997. value(event) {
  14998. removeEmptyEntry?.();
  14999. const value = event.detail.value;
  15000. const values = new Set(Array.isArray(value) ? value : [value]);
  15001. for (const option of selectElement.options) {
  15002. option.selected = values.has(option.value);
  15003. }
  15004. storage.setValue(id, {
  15005. value: getValue(true)
  15006. });
  15007. selectedValues = getValue(false);
  15008. },
  15009. multipleSelection(event) {
  15010. selectElement.multiple = true;
  15011. },
  15012. remove(event) {
  15013. const options = selectElement.options;
  15014. const index = event.detail.remove;
  15015. options[index].selected = false;
  15016. selectElement.remove(index);
  15017. if (options.length > 0) {
  15018. const i = Array.prototype.findIndex.call(options, option => option.selected);
  15019. if (i === -1) {
  15020. options[0].selected = true;
  15021. }
  15022. }
  15023. storage.setValue(id, {
  15024. value: getValue(true),
  15025. items: getItems(event)
  15026. });
  15027. selectedValues = getValue(false);
  15028. },
  15029. clear(event) {
  15030. while (selectElement.length !== 0) {
  15031. selectElement.remove(0);
  15032. }
  15033. storage.setValue(id, {
  15034. value: null,
  15035. items: []
  15036. });
  15037. selectedValues = getValue(false);
  15038. },
  15039. insert(event) {
  15040. const {
  15041. index,
  15042. displayValue,
  15043. exportValue
  15044. } = event.detail.insert;
  15045. const selectChild = selectElement.children[index];
  15046. const optionElement = document.createElement("option");
  15047. optionElement.textContent = displayValue;
  15048. optionElement.value = exportValue;
  15049. if (selectChild) {
  15050. selectChild.before(optionElement);
  15051. } else {
  15052. selectElement.append(optionElement);
  15053. }
  15054. storage.setValue(id, {
  15055. value: getValue(true),
  15056. items: getItems(event)
  15057. });
  15058. selectedValues = getValue(false);
  15059. },
  15060. items(event) {
  15061. const {
  15062. items
  15063. } = event.detail;
  15064. while (selectElement.length !== 0) {
  15065. selectElement.remove(0);
  15066. }
  15067. for (const item of items) {
  15068. const {
  15069. displayValue,
  15070. exportValue
  15071. } = item;
  15072. const optionElement = document.createElement("option");
  15073. optionElement.textContent = displayValue;
  15074. optionElement.value = exportValue;
  15075. selectElement.append(optionElement);
  15076. }
  15077. if (selectElement.options.length > 0) {
  15078. selectElement.options[0].selected = true;
  15079. }
  15080. storage.setValue(id, {
  15081. value: getValue(true),
  15082. items: getItems(event)
  15083. });
  15084. selectedValues = getValue(false);
  15085. },
  15086. indices(event) {
  15087. const indices = new Set(event.detail.indices);
  15088. for (const option of event.target.options) {
  15089. option.selected = indices.has(option.index);
  15090. }
  15091. storage.setValue(id, {
  15092. value: getValue(true)
  15093. });
  15094. selectedValues = getValue(false);
  15095. },
  15096. editable(event) {
  15097. event.target.disabled = !event.detail.editable;
  15098. }
  15099. };
  15100. this._dispatchEventFromSandbox(actions, jsEvent);
  15101. });
  15102. selectElement.addEventListener("input", event => {
  15103. const exportValue = getValue(true);
  15104. storage.setValue(id, {
  15105. value: exportValue
  15106. });
  15107. event.preventDefault();
  15108. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  15109. source: this,
  15110. detail: {
  15111. id,
  15112. name: "Keystroke",
  15113. value: selectedValues,
  15114. changeEx: exportValue,
  15115. willCommit: false,
  15116. commitKey: 1,
  15117. keyDown: false
  15118. }
  15119. });
  15120. });
  15121. this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
  15122. } else {
  15123. selectElement.addEventListener("input", function (event) {
  15124. storage.setValue(id, {
  15125. value: getValue(true)
  15126. });
  15127. });
  15128. }
  15129. if (this.data.combo) {
  15130. this._setTextStyle(selectElement);
  15131. } else {}
  15132. this._setBackgroundColor(selectElement);
  15133. this._setDefaultPropertiesFromJS(selectElement);
  15134. this.container.append(selectElement);
  15135. return this.container;
  15136. }
  15137. }
  15138. class PopupAnnotationElement extends AnnotationElement {
  15139. constructor(parameters) {
  15140. const {
  15141. data,
  15142. elements
  15143. } = parameters;
  15144. const isRenderable = !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  15145. super(parameters, {
  15146. isRenderable
  15147. });
  15148. this.elements = elements;
  15149. }
  15150. render() {
  15151. this.container.classList.add("popupAnnotation");
  15152. const popup = new PopupElement({
  15153. container: this.container,
  15154. color: this.data.color,
  15155. titleObj: this.data.titleObj,
  15156. modificationDate: this.data.modificationDate,
  15157. contentsObj: this.data.contentsObj,
  15158. richText: this.data.richText,
  15159. rect: this.data.rect,
  15160. parentRect: this.data.parentRect || null,
  15161. parent: this.parent,
  15162. elements: this.elements,
  15163. open: this.data.open
  15164. });
  15165. const elementIds = [];
  15166. for (const element of this.elements) {
  15167. element.popup = popup;
  15168. elementIds.push(element.data.id);
  15169. element.addHighlightArea();
  15170. }
  15171. this.container.setAttribute("aria-controls", elementIds.join(","));
  15172. return this.container;
  15173. }
  15174. }
  15175. class PopupElement {
  15176. #dateTimePromise = null;
  15177. #boundHide = this.#hide.bind(this);
  15178. #boundShow = this.#show.bind(this);
  15179. #boundToggle = this.#toggle.bind(this);
  15180. #color = null;
  15181. #container = null;
  15182. #contentsObj = null;
  15183. #elements = null;
  15184. #parent = null;
  15185. #parentRect = null;
  15186. #pinned = false;
  15187. #popup = null;
  15188. #rect = null;
  15189. #richText = null;
  15190. #titleObj = null;
  15191. #wasVisible = false;
  15192. constructor({
  15193. container,
  15194. color,
  15195. elements,
  15196. titleObj,
  15197. modificationDate,
  15198. contentsObj,
  15199. richText,
  15200. parent,
  15201. rect,
  15202. parentRect,
  15203. open
  15204. }) {
  15205. this.#container = container;
  15206. this.#titleObj = titleObj;
  15207. this.#contentsObj = contentsObj;
  15208. this.#richText = richText;
  15209. this.#parent = parent;
  15210. this.#color = color;
  15211. this.#rect = rect;
  15212. this.#parentRect = parentRect;
  15213. this.#elements = elements;
  15214. const dateObject = _display_utils.PDFDateString.toDateObject(modificationDate);
  15215. if (dateObject) {
  15216. this.#dateTimePromise = parent.l10n.get("annotation_date_string", {
  15217. date: dateObject.toLocaleDateString(),
  15218. time: dateObject.toLocaleTimeString()
  15219. });
  15220. }
  15221. this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
  15222. for (const element of this.trigger) {
  15223. element.addEventListener("click", this.#boundToggle);
  15224. element.addEventListener("mouseenter", this.#boundShow);
  15225. element.addEventListener("mouseleave", this.#boundHide);
  15226. }
  15227. this.#container.hidden = true;
  15228. if (open) {
  15229. this.#toggle();
  15230. }
  15231. }
  15232. render() {
  15233. if (this.#popup) {
  15234. return;
  15235. }
  15236. const {
  15237. page: {
  15238. view
  15239. },
  15240. viewport: {
  15241. rawDims: {
  15242. pageWidth,
  15243. pageHeight,
  15244. pageX,
  15245. pageY
  15246. }
  15247. }
  15248. } = this.#parent;
  15249. const popup = this.#popup = document.createElement("div");
  15250. popup.className = "popup";
  15251. if (this.#color) {
  15252. const baseColor = popup.style.outlineColor = _util.Util.makeHexColor(...this.#color);
  15253. if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
  15254. popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
  15255. } else {
  15256. const BACKGROUND_ENLIGHT = 0.7;
  15257. popup.style.backgroundColor = _util.Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
  15258. }
  15259. }
  15260. const header = document.createElement("span");
  15261. header.className = "header";
  15262. const title = document.createElement("h1");
  15263. header.append(title);
  15264. ({
  15265. dir: title.dir,
  15266. str: title.textContent
  15267. } = this.#titleObj);
  15268. popup.append(header);
  15269. if (this.#dateTimePromise) {
  15270. const modificationDate = document.createElement("span");
  15271. modificationDate.classList.add("popupDate");
  15272. this.#dateTimePromise.then(localized => {
  15273. modificationDate.textContent = localized;
  15274. });
  15275. header.append(modificationDate);
  15276. }
  15277. const contentsObj = this.#contentsObj;
  15278. const richText = this.#richText;
  15279. if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
  15280. _xfa_layer.XfaLayer.render({
  15281. xfaHtml: richText.html,
  15282. intent: "richText",
  15283. div: popup
  15284. });
  15285. popup.lastChild.classList.add("richText", "popupContent");
  15286. } else {
  15287. const contents = this._formatContents(contentsObj);
  15288. popup.append(contents);
  15289. }
  15290. let useParentRect = !!this.#parentRect;
  15291. let rect = useParentRect ? this.#parentRect : this.#rect;
  15292. for (const element of this.#elements) {
  15293. if (!rect || _util.Util.intersect(element.data.rect, rect) !== null) {
  15294. rect = element.data.rect;
  15295. useParentRect = true;
  15296. break;
  15297. }
  15298. }
  15299. const normalizedRect = _util.Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
  15300. const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
  15301. const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
  15302. const popupLeft = normalizedRect[0] + parentWidth;
  15303. const popupTop = normalizedRect[1];
  15304. const {
  15305. style
  15306. } = this.#container;
  15307. style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
  15308. style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
  15309. this.#container.append(popup);
  15310. }
  15311. _formatContents({
  15312. str,
  15313. dir
  15314. }) {
  15315. const p = document.createElement("p");
  15316. p.classList.add("popupContent");
  15317. p.dir = dir;
  15318. const lines = str.split(/(?:\r\n?|\n)/);
  15319. for (let i = 0, ii = lines.length; i < ii; ++i) {
  15320. const line = lines[i];
  15321. p.append(document.createTextNode(line));
  15322. if (i < ii - 1) {
  15323. p.append(document.createElement("br"));
  15324. }
  15325. }
  15326. return p;
  15327. }
  15328. #toggle() {
  15329. this.#pinned = !this.#pinned;
  15330. if (this.#pinned) {
  15331. this.#show();
  15332. this.#container.addEventListener("click", this.#boundToggle);
  15333. } else {
  15334. this.#hide();
  15335. this.#container.removeEventListener("click", this.#boundToggle);
  15336. }
  15337. }
  15338. #show() {
  15339. if (!this.#popup) {
  15340. this.render();
  15341. }
  15342. if (!this.isVisible) {
  15343. this.#container.hidden = false;
  15344. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
  15345. } else if (this.#pinned) {
  15346. this.#container.classList.add("focused");
  15347. }
  15348. }
  15349. #hide() {
  15350. this.#container.classList.remove("focused");
  15351. if (this.#pinned || !this.isVisible) {
  15352. return;
  15353. }
  15354. this.#container.hidden = true;
  15355. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
  15356. }
  15357. forceHide() {
  15358. this.#wasVisible = this.isVisible;
  15359. if (!this.#wasVisible) {
  15360. return;
  15361. }
  15362. this.#container.hidden = true;
  15363. }
  15364. maybeShow() {
  15365. if (!this.#wasVisible) {
  15366. return;
  15367. }
  15368. this.#wasVisible = false;
  15369. this.#container.hidden = false;
  15370. }
  15371. get isVisible() {
  15372. return this.#container.hidden === false;
  15373. }
  15374. }
  15375. class FreeTextAnnotationElement extends AnnotationElement {
  15376. constructor(parameters) {
  15377. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15378. super(parameters, {
  15379. isRenderable,
  15380. ignoreBorder: true
  15381. });
  15382. this.textContent = parameters.data.textContent;
  15383. this.textPosition = parameters.data.textPosition;
  15384. this.annotationEditorType = _util.AnnotationEditorType.FREETEXT;
  15385. }
  15386. render() {
  15387. this.container.classList.add("freeTextAnnotation");
  15388. if (this.textContent) {
  15389. const content = document.createElement("div");
  15390. content.classList.add("annotationTextContent");
  15391. content.setAttribute("role", "comment");
  15392. for (const line of this.textContent) {
  15393. const lineSpan = document.createElement("span");
  15394. lineSpan.textContent = line;
  15395. content.append(lineSpan);
  15396. }
  15397. this.container.append(content);
  15398. }
  15399. if (!this.data.popupRef) {
  15400. this._createPopup();
  15401. }
  15402. this._editOnDoubleClick();
  15403. return this.container;
  15404. }
  15405. }
  15406. exports.FreeTextAnnotationElement = FreeTextAnnotationElement;
  15407. class LineAnnotationElement extends AnnotationElement {
  15408. #line = null;
  15409. constructor(parameters) {
  15410. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15411. super(parameters, {
  15412. isRenderable,
  15413. ignoreBorder: true
  15414. });
  15415. }
  15416. render() {
  15417. this.container.classList.add("lineAnnotation");
  15418. const data = this.data;
  15419. const {
  15420. width,
  15421. height
  15422. } = getRectDims(data.rect);
  15423. const svg = this.svgFactory.create(width, height, true);
  15424. const line = this.#line = this.svgFactory.createElement("svg:line");
  15425. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  15426. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  15427. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  15428. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  15429. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  15430. line.setAttribute("stroke", "transparent");
  15431. line.setAttribute("fill", "transparent");
  15432. svg.append(line);
  15433. this.container.append(svg);
  15434. if (!data.popupRef) {
  15435. this._createPopup();
  15436. }
  15437. return this.container;
  15438. }
  15439. getElementsToTriggerPopup() {
  15440. return this.#line;
  15441. }
  15442. addHighlightArea() {
  15443. this.container.classList.add("highlightArea");
  15444. }
  15445. }
  15446. class SquareAnnotationElement extends AnnotationElement {
  15447. #square = null;
  15448. constructor(parameters) {
  15449. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15450. super(parameters, {
  15451. isRenderable,
  15452. ignoreBorder: true
  15453. });
  15454. }
  15455. render() {
  15456. this.container.classList.add("squareAnnotation");
  15457. const data = this.data;
  15458. const {
  15459. width,
  15460. height
  15461. } = getRectDims(data.rect);
  15462. const svg = this.svgFactory.create(width, height, true);
  15463. const borderWidth = data.borderStyle.width;
  15464. const square = this.#square = this.svgFactory.createElement("svg:rect");
  15465. square.setAttribute("x", borderWidth / 2);
  15466. square.setAttribute("y", borderWidth / 2);
  15467. square.setAttribute("width", width - borderWidth);
  15468. square.setAttribute("height", height - borderWidth);
  15469. square.setAttribute("stroke-width", borderWidth || 1);
  15470. square.setAttribute("stroke", "transparent");
  15471. square.setAttribute("fill", "transparent");
  15472. svg.append(square);
  15473. this.container.append(svg);
  15474. if (!data.popupRef) {
  15475. this._createPopup();
  15476. }
  15477. return this.container;
  15478. }
  15479. getElementsToTriggerPopup() {
  15480. return this.#square;
  15481. }
  15482. addHighlightArea() {
  15483. this.container.classList.add("highlightArea");
  15484. }
  15485. }
  15486. class CircleAnnotationElement extends AnnotationElement {
  15487. #circle = null;
  15488. constructor(parameters) {
  15489. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15490. super(parameters, {
  15491. isRenderable,
  15492. ignoreBorder: true
  15493. });
  15494. }
  15495. render() {
  15496. this.container.classList.add("circleAnnotation");
  15497. const data = this.data;
  15498. const {
  15499. width,
  15500. height
  15501. } = getRectDims(data.rect);
  15502. const svg = this.svgFactory.create(width, height, true);
  15503. const borderWidth = data.borderStyle.width;
  15504. const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
  15505. circle.setAttribute("cx", width / 2);
  15506. circle.setAttribute("cy", height / 2);
  15507. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  15508. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  15509. circle.setAttribute("stroke-width", borderWidth || 1);
  15510. circle.setAttribute("stroke", "transparent");
  15511. circle.setAttribute("fill", "transparent");
  15512. svg.append(circle);
  15513. this.container.append(svg);
  15514. if (!data.popupRef) {
  15515. this._createPopup();
  15516. }
  15517. return this.container;
  15518. }
  15519. getElementsToTriggerPopup() {
  15520. return this.#circle;
  15521. }
  15522. addHighlightArea() {
  15523. this.container.classList.add("highlightArea");
  15524. }
  15525. }
  15526. class PolylineAnnotationElement extends AnnotationElement {
  15527. #polyline = null;
  15528. constructor(parameters) {
  15529. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15530. super(parameters, {
  15531. isRenderable,
  15532. ignoreBorder: true
  15533. });
  15534. this.containerClassName = "polylineAnnotation";
  15535. this.svgElementName = "svg:polyline";
  15536. }
  15537. render() {
  15538. this.container.classList.add(this.containerClassName);
  15539. const data = this.data;
  15540. const {
  15541. width,
  15542. height
  15543. } = getRectDims(data.rect);
  15544. const svg = this.svgFactory.create(width, height, true);
  15545. let points = [];
  15546. for (const coordinate of data.vertices) {
  15547. const x = coordinate.x - data.rect[0];
  15548. const y = data.rect[3] - coordinate.y;
  15549. points.push(x + "," + y);
  15550. }
  15551. points = points.join(" ");
  15552. const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
  15553. polyline.setAttribute("points", points);
  15554. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  15555. polyline.setAttribute("stroke", "transparent");
  15556. polyline.setAttribute("fill", "transparent");
  15557. svg.append(polyline);
  15558. this.container.append(svg);
  15559. if (!data.popupRef) {
  15560. this._createPopup(polyline, data);
  15561. }
  15562. return this.container;
  15563. }
  15564. getElementsToTriggerPopup() {
  15565. return this.#polyline;
  15566. }
  15567. addHighlightArea() {
  15568. this.container.classList.add("highlightArea");
  15569. }
  15570. }
  15571. class PolygonAnnotationElement extends PolylineAnnotationElement {
  15572. constructor(parameters) {
  15573. super(parameters);
  15574. this.containerClassName = "polygonAnnotation";
  15575. this.svgElementName = "svg:polygon";
  15576. }
  15577. }
  15578. class CaretAnnotationElement extends AnnotationElement {
  15579. constructor(parameters) {
  15580. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15581. super(parameters, {
  15582. isRenderable,
  15583. ignoreBorder: true
  15584. });
  15585. }
  15586. render() {
  15587. this.container.classList.add("caretAnnotation");
  15588. if (!this.data.popupRef) {
  15589. this._createPopup();
  15590. }
  15591. return this.container;
  15592. }
  15593. }
  15594. class InkAnnotationElement extends AnnotationElement {
  15595. #polylines = [];
  15596. constructor(parameters) {
  15597. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15598. super(parameters, {
  15599. isRenderable,
  15600. ignoreBorder: true
  15601. });
  15602. this.containerClassName = "inkAnnotation";
  15603. this.svgElementName = "svg:polyline";
  15604. this.annotationEditorType = _util.AnnotationEditorType.INK;
  15605. }
  15606. render() {
  15607. this.container.classList.add(this.containerClassName);
  15608. const data = this.data;
  15609. const {
  15610. width,
  15611. height
  15612. } = getRectDims(data.rect);
  15613. const svg = this.svgFactory.create(width, height, true);
  15614. for (const inkList of data.inkLists) {
  15615. let points = [];
  15616. for (const coordinate of inkList) {
  15617. const x = coordinate.x - data.rect[0];
  15618. const y = data.rect[3] - coordinate.y;
  15619. points.push(`${x},${y}`);
  15620. }
  15621. points = points.join(" ");
  15622. const polyline = this.svgFactory.createElement(this.svgElementName);
  15623. this.#polylines.push(polyline);
  15624. polyline.setAttribute("points", points);
  15625. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  15626. polyline.setAttribute("stroke", "transparent");
  15627. polyline.setAttribute("fill", "transparent");
  15628. if (!data.popupRef) {
  15629. this._createPopup(polyline, data);
  15630. }
  15631. svg.append(polyline);
  15632. }
  15633. this.container.append(svg);
  15634. return this.container;
  15635. }
  15636. getElementsToTriggerPopup() {
  15637. return this.#polylines;
  15638. }
  15639. addHighlightArea() {
  15640. this.container.classList.add("highlightArea");
  15641. }
  15642. }
  15643. exports.InkAnnotationElement = InkAnnotationElement;
  15644. class HighlightAnnotationElement extends AnnotationElement {
  15645. constructor(parameters) {
  15646. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15647. super(parameters, {
  15648. isRenderable,
  15649. ignoreBorder: true,
  15650. createQuadrilaterals: true
  15651. });
  15652. }
  15653. render() {
  15654. if (!this.data.popupRef) {
  15655. this._createPopup();
  15656. }
  15657. this.container.classList.add("highlightAnnotation");
  15658. return this.container;
  15659. }
  15660. }
  15661. class UnderlineAnnotationElement extends AnnotationElement {
  15662. constructor(parameters) {
  15663. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15664. super(parameters, {
  15665. isRenderable,
  15666. ignoreBorder: true,
  15667. createQuadrilaterals: true
  15668. });
  15669. }
  15670. render() {
  15671. if (!this.data.popupRef) {
  15672. this._createPopup();
  15673. }
  15674. this.container.classList.add("underlineAnnotation");
  15675. return this.container;
  15676. }
  15677. }
  15678. class SquigglyAnnotationElement extends AnnotationElement {
  15679. constructor(parameters) {
  15680. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15681. super(parameters, {
  15682. isRenderable,
  15683. ignoreBorder: true,
  15684. createQuadrilaterals: true
  15685. });
  15686. }
  15687. render() {
  15688. if (!this.data.popupRef) {
  15689. this._createPopup();
  15690. }
  15691. this.container.classList.add("squigglyAnnotation");
  15692. return this.container;
  15693. }
  15694. }
  15695. class StrikeOutAnnotationElement extends AnnotationElement {
  15696. constructor(parameters) {
  15697. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15698. super(parameters, {
  15699. isRenderable,
  15700. ignoreBorder: true,
  15701. createQuadrilaterals: true
  15702. });
  15703. }
  15704. render() {
  15705. if (!this.data.popupRef) {
  15706. this._createPopup();
  15707. }
  15708. this.container.classList.add("strikeoutAnnotation");
  15709. return this.container;
  15710. }
  15711. }
  15712. class StampAnnotationElement extends AnnotationElement {
  15713. constructor(parameters) {
  15714. const isRenderable = !!(parameters.data.popupRef || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  15715. super(parameters, {
  15716. isRenderable,
  15717. ignoreBorder: true
  15718. });
  15719. }
  15720. render() {
  15721. this.container.classList.add("stampAnnotation");
  15722. if (!this.data.popupRef) {
  15723. this._createPopup();
  15724. }
  15725. return this.container;
  15726. }
  15727. }
  15728. exports.StampAnnotationElement = StampAnnotationElement;
  15729. class FileAttachmentAnnotationElement extends AnnotationElement {
  15730. #trigger = null;
  15731. constructor(parameters) {
  15732. super(parameters, {
  15733. isRenderable: true
  15734. });
  15735. const {
  15736. filename,
  15737. content
  15738. } = this.data.file;
  15739. this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
  15740. this.content = content;
  15741. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  15742. source: this,
  15743. filename,
  15744. content
  15745. });
  15746. }
  15747. render() {
  15748. this.container.classList.add("fileAttachmentAnnotation");
  15749. const {
  15750. data
  15751. } = this;
  15752. let trigger;
  15753. if (data.hasAppearance || data.fillAlpha === 0) {
  15754. trigger = document.createElement("div");
  15755. } else {
  15756. trigger = document.createElement("img");
  15757. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
  15758. if (data.fillAlpha && data.fillAlpha < 1) {
  15759. trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
  15760. }
  15761. }
  15762. trigger.classList.add("popupTriggerArea");
  15763. trigger.addEventListener("dblclick", this._download.bind(this));
  15764. this.#trigger = trigger;
  15765. if (!data.popupRef && (data.titleObj?.str || data.contentsObj?.str || data.richText)) {
  15766. this._createPopup();
  15767. }
  15768. this.container.append(trigger);
  15769. return this.container;
  15770. }
  15771. getElementsToTriggerPopup() {
  15772. return this.#trigger;
  15773. }
  15774. addHighlightArea() {
  15775. this.container.classList.add("highlightArea");
  15776. }
  15777. _download() {
  15778. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  15779. }
  15780. }
  15781. class AnnotationLayer {
  15782. #accessibilityManager = null;
  15783. #annotationCanvasMap = null;
  15784. #editableAnnotations = new Map();
  15785. constructor({
  15786. div,
  15787. accessibilityManager,
  15788. annotationCanvasMap,
  15789. l10n,
  15790. page,
  15791. viewport
  15792. }) {
  15793. this.div = div;
  15794. this.#accessibilityManager = accessibilityManager;
  15795. this.#annotationCanvasMap = annotationCanvasMap;
  15796. this.l10n = l10n;
  15797. this.page = page;
  15798. this.viewport = viewport;
  15799. this.zIndex = 0;
  15800. this.l10n ||= _displayL10n_utils.NullL10n;
  15801. }
  15802. #appendElement(element, id) {
  15803. const contentElement = element.firstChild || element;
  15804. contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
  15805. this.div.append(element);
  15806. this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
  15807. }
  15808. async render(params) {
  15809. const {
  15810. annotations
  15811. } = params;
  15812. const layer = this.div;
  15813. (0, _display_utils.setLayerDimensions)(layer, this.viewport);
  15814. const popupToElements = new Map();
  15815. const elementParams = {
  15816. data: null,
  15817. layer,
  15818. linkService: params.linkService,
  15819. downloadManager: params.downloadManager,
  15820. imageResourcesPath: params.imageResourcesPath || "",
  15821. renderForms: params.renderForms !== false,
  15822. svgFactory: new _display_utils.DOMSVGFactory(),
  15823. annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
  15824. enableScripting: params.enableScripting === true,
  15825. hasJSActions: params.hasJSActions,
  15826. fieldObjects: params.fieldObjects,
  15827. parent: this,
  15828. elements: null
  15829. };
  15830. for (const data of annotations) {
  15831. if (data.noHTML) {
  15832. continue;
  15833. }
  15834. const isPopupAnnotation = data.annotationType === _util.AnnotationType.POPUP;
  15835. if (!isPopupAnnotation) {
  15836. const {
  15837. width,
  15838. height
  15839. } = getRectDims(data.rect);
  15840. if (width <= 0 || height <= 0) {
  15841. continue;
  15842. }
  15843. } else {
  15844. const elements = popupToElements.get(data.id);
  15845. if (!elements) {
  15846. continue;
  15847. }
  15848. elementParams.elements = elements;
  15849. }
  15850. elementParams.data = data;
  15851. const element = AnnotationElementFactory.create(elementParams);
  15852. if (!element.isRenderable) {
  15853. continue;
  15854. }
  15855. if (!isPopupAnnotation && data.popupRef) {
  15856. const elements = popupToElements.get(data.popupRef);
  15857. if (!elements) {
  15858. popupToElements.set(data.popupRef, [element]);
  15859. } else {
  15860. elements.push(element);
  15861. }
  15862. }
  15863. if (element.annotationEditorType > 0) {
  15864. this.#editableAnnotations.set(element.data.id, element);
  15865. }
  15866. const rendered = element.render();
  15867. if (data.hidden) {
  15868. rendered.style.visibility = "hidden";
  15869. }
  15870. this.#appendElement(rendered, data.id);
  15871. }
  15872. this.#setAnnotationCanvasMap();
  15873. await this.l10n.translate(layer);
  15874. }
  15875. update({
  15876. viewport
  15877. }) {
  15878. const layer = this.div;
  15879. this.viewport = viewport;
  15880. (0, _display_utils.setLayerDimensions)(layer, {
  15881. rotation: viewport.rotation
  15882. });
  15883. this.#setAnnotationCanvasMap();
  15884. layer.hidden = false;
  15885. }
  15886. #setAnnotationCanvasMap() {
  15887. if (!this.#annotationCanvasMap) {
  15888. return;
  15889. }
  15890. const layer = this.div;
  15891. for (const [id, canvas] of this.#annotationCanvasMap) {
  15892. const element = layer.querySelector(`[data-annotation-id="${id}"]`);
  15893. if (!element) {
  15894. continue;
  15895. }
  15896. const {
  15897. firstChild
  15898. } = element;
  15899. if (!firstChild) {
  15900. element.append(canvas);
  15901. } else if (firstChild.nodeName === "CANVAS") {
  15902. firstChild.replaceWith(canvas);
  15903. } else {
  15904. firstChild.before(canvas);
  15905. }
  15906. }
  15907. this.#annotationCanvasMap.clear();
  15908. }
  15909. getEditableAnnotations() {
  15910. return Array.from(this.#editableAnnotations.values());
  15911. }
  15912. getEditableAnnotation(id) {
  15913. return this.#editableAnnotations.get(id);
  15914. }
  15915. }
  15916. exports.AnnotationLayer = AnnotationLayer;
  15917. /***/ }),
  15918. /* 30 */
  15919. /***/ ((__unused_webpack_module, exports) => {
  15920. Object.defineProperty(exports, "__esModule", ({
  15921. value: true
  15922. }));
  15923. exports.ColorConverters = void 0;
  15924. function makeColorComp(n) {
  15925. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  15926. }
  15927. function scaleAndClamp(x) {
  15928. return Math.max(0, Math.min(255, 255 * x));
  15929. }
  15930. class ColorConverters {
  15931. static CMYK_G([c, y, m, k]) {
  15932. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  15933. }
  15934. static G_CMYK([g]) {
  15935. return ["CMYK", 0, 0, 0, 1 - g];
  15936. }
  15937. static G_RGB([g]) {
  15938. return ["RGB", g, g, g];
  15939. }
  15940. static G_rgb([g]) {
  15941. g = scaleAndClamp(g);
  15942. return [g, g, g];
  15943. }
  15944. static G_HTML([g]) {
  15945. const G = makeColorComp(g);
  15946. return `#${G}${G}${G}`;
  15947. }
  15948. static RGB_G([r, g, b]) {
  15949. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  15950. }
  15951. static RGB_rgb(color) {
  15952. return color.map(scaleAndClamp);
  15953. }
  15954. static RGB_HTML(color) {
  15955. return `#${color.map(makeColorComp).join("")}`;
  15956. }
  15957. static T_HTML() {
  15958. return "#00000000";
  15959. }
  15960. static T_rgb() {
  15961. return [null];
  15962. }
  15963. static CMYK_RGB([c, y, m, k]) {
  15964. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  15965. }
  15966. static CMYK_rgb([c, y, m, k]) {
  15967. return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
  15968. }
  15969. static CMYK_HTML(components) {
  15970. const rgb = this.CMYK_RGB(components).slice(1);
  15971. return this.RGB_HTML(rgb);
  15972. }
  15973. static RGB_CMYK([r, g, b]) {
  15974. const c = 1 - r;
  15975. const m = 1 - g;
  15976. const y = 1 - b;
  15977. const k = Math.min(c, m, y);
  15978. return ["CMYK", c, m, y, k];
  15979. }
  15980. }
  15981. exports.ColorConverters = ColorConverters;
  15982. /***/ }),
  15983. /* 31 */
  15984. /***/ ((__unused_webpack_module, exports) => {
  15985. Object.defineProperty(exports, "__esModule", ({
  15986. value: true
  15987. }));
  15988. exports.NullL10n = void 0;
  15989. exports.getL10nFallback = getL10nFallback;
  15990. const DEFAULT_L10N_STRINGS = {
  15991. of_pages: "of {{pagesCount}}",
  15992. page_of_pages: "({{pageNumber}} of {{pagesCount}})",
  15993. document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)",
  15994. document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)",
  15995. document_properties_date_string: "{{date}}, {{time}}",
  15996. document_properties_page_size_unit_inches: "in",
  15997. document_properties_page_size_unit_millimeters: "mm",
  15998. document_properties_page_size_orientation_portrait: "portrait",
  15999. document_properties_page_size_orientation_landscape: "landscape",
  16000. document_properties_page_size_name_a3: "A3",
  16001. document_properties_page_size_name_a4: "A4",
  16002. document_properties_page_size_name_letter: "Letter",
  16003. document_properties_page_size_name_legal: "Legal",
  16004. document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})",
  16005. document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})",
  16006. document_properties_linearized_yes: "Yes",
  16007. document_properties_linearized_no: "No",
  16008. additional_layers: "Additional Layers",
  16009. page_landmark: "Page {{page}}",
  16010. thumb_page_title: "Page {{page}}",
  16011. thumb_page_canvas: "Thumbnail of Page {{page}}",
  16012. find_reached_top: "Reached top of document, continued from bottom",
  16013. find_reached_bottom: "Reached end of document, continued from top",
  16014. "find_match_count[one]": "{{current}} of {{total}} match",
  16015. "find_match_count[other]": "{{current}} of {{total}} matches",
  16016. "find_match_count_limit[one]": "More than {{limit}} match",
  16017. "find_match_count_limit[other]": "More than {{limit}} matches",
  16018. find_not_found: "Phrase not found",
  16019. page_scale_width: "Page Width",
  16020. page_scale_fit: "Page Fit",
  16021. page_scale_auto: "Automatic Zoom",
  16022. page_scale_actual: "Actual Size",
  16023. page_scale_percent: "{{scale}}%",
  16024. loading_error: "An error occurred while loading the PDF.",
  16025. invalid_file_error: "Invalid or corrupted PDF file.",
  16026. missing_file_error: "Missing PDF file.",
  16027. unexpected_response_error: "Unexpected server response.",
  16028. rendering_error: "An error occurred while rendering the page.",
  16029. annotation_date_string: "{{date}}, {{time}}",
  16030. printing_not_supported: "Warning: Printing is not fully supported by this browser.",
  16031. printing_not_ready: "Warning: The PDF is not fully loaded for printing.",
  16032. web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts.",
  16033. free_text2_default_content: "Start typing…",
  16034. editor_free_text2_aria_label: "Text Editor",
  16035. editor_ink2_aria_label: "Draw Editor",
  16036. editor_ink_canvas_aria_label: "User-created image"
  16037. };
  16038. {
  16039. DEFAULT_L10N_STRINGS.print_progress_percent = "{{progress}}%";
  16040. }
  16041. function getL10nFallback(key, args) {
  16042. switch (key) {
  16043. case "find_match_count":
  16044. key = `find_match_count[${args.total === 1 ? "one" : "other"}]`;
  16045. break;
  16046. case "find_match_count_limit":
  16047. key = `find_match_count_limit[${args.limit === 1 ? "one" : "other"}]`;
  16048. break;
  16049. }
  16050. return DEFAULT_L10N_STRINGS[key] || "";
  16051. }
  16052. function formatL10nValue(text, args) {
  16053. if (!args) {
  16054. return text;
  16055. }
  16056. return text.replaceAll(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => {
  16057. return name in args ? args[name] : "{{" + name + "}}";
  16058. });
  16059. }
  16060. const NullL10n = {
  16061. async getLanguage() {
  16062. return "en-us";
  16063. },
  16064. async getDirection() {
  16065. return "ltr";
  16066. },
  16067. async get(key, args = null, fallback = getL10nFallback(key, args)) {
  16068. return formatL10nValue(fallback, args);
  16069. },
  16070. async translate(element) {}
  16071. };
  16072. exports.NullL10n = NullL10n;
  16073. /***/ }),
  16074. /* 32 */
  16075. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  16076. Object.defineProperty(exports, "__esModule", ({
  16077. value: true
  16078. }));
  16079. exports.XfaLayer = void 0;
  16080. var _xfa_text = __w_pdfjs_require__(25);
  16081. class XfaLayer {
  16082. static setupStorage(html, id, element, storage, intent) {
  16083. const storedData = storage.getValue(id, {
  16084. value: null
  16085. });
  16086. switch (element.name) {
  16087. case "textarea":
  16088. if (storedData.value !== null) {
  16089. html.textContent = storedData.value;
  16090. }
  16091. if (intent === "print") {
  16092. break;
  16093. }
  16094. html.addEventListener("input", event => {
  16095. storage.setValue(id, {
  16096. value: event.target.value
  16097. });
  16098. });
  16099. break;
  16100. case "input":
  16101. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  16102. if (storedData.value === element.attributes.xfaOn) {
  16103. html.setAttribute("checked", true);
  16104. } else if (storedData.value === element.attributes.xfaOff) {
  16105. html.removeAttribute("checked");
  16106. }
  16107. if (intent === "print") {
  16108. break;
  16109. }
  16110. html.addEventListener("change", event => {
  16111. storage.setValue(id, {
  16112. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  16113. });
  16114. });
  16115. } else {
  16116. if (storedData.value !== null) {
  16117. html.setAttribute("value", storedData.value);
  16118. }
  16119. if (intent === "print") {
  16120. break;
  16121. }
  16122. html.addEventListener("input", event => {
  16123. storage.setValue(id, {
  16124. value: event.target.value
  16125. });
  16126. });
  16127. }
  16128. break;
  16129. case "select":
  16130. if (storedData.value !== null) {
  16131. html.setAttribute("value", storedData.value);
  16132. for (const option of element.children) {
  16133. if (option.attributes.value === storedData.value) {
  16134. option.attributes.selected = true;
  16135. } else if (option.attributes.hasOwnProperty("selected")) {
  16136. delete option.attributes.selected;
  16137. }
  16138. }
  16139. }
  16140. html.addEventListener("input", event => {
  16141. const options = event.target.options;
  16142. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  16143. storage.setValue(id, {
  16144. value
  16145. });
  16146. });
  16147. break;
  16148. }
  16149. }
  16150. static setAttributes({
  16151. html,
  16152. element,
  16153. storage = null,
  16154. intent,
  16155. linkService
  16156. }) {
  16157. const {
  16158. attributes
  16159. } = element;
  16160. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  16161. if (attributes.type === "radio") {
  16162. attributes.name = `${attributes.name}-${intent}`;
  16163. }
  16164. for (const [key, value] of Object.entries(attributes)) {
  16165. if (value === null || value === undefined) {
  16166. continue;
  16167. }
  16168. switch (key) {
  16169. case "class":
  16170. if (value.length) {
  16171. html.setAttribute(key, value.join(" "));
  16172. }
  16173. break;
  16174. case "dataId":
  16175. break;
  16176. case "id":
  16177. html.setAttribute("data-element-id", value);
  16178. break;
  16179. case "style":
  16180. Object.assign(html.style, value);
  16181. break;
  16182. case "textContent":
  16183. html.textContent = value;
  16184. break;
  16185. default:
  16186. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  16187. html.setAttribute(key, value);
  16188. }
  16189. }
  16190. }
  16191. if (isHTMLAnchorElement) {
  16192. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  16193. }
  16194. if (storage && attributes.dataId) {
  16195. this.setupStorage(html, attributes.dataId, element, storage);
  16196. }
  16197. }
  16198. static render(parameters) {
  16199. const storage = parameters.annotationStorage;
  16200. const linkService = parameters.linkService;
  16201. const root = parameters.xfaHtml;
  16202. const intent = parameters.intent || "display";
  16203. const rootHtml = document.createElement(root.name);
  16204. if (root.attributes) {
  16205. this.setAttributes({
  16206. html: rootHtml,
  16207. element: root,
  16208. intent,
  16209. linkService
  16210. });
  16211. }
  16212. const stack = [[root, -1, rootHtml]];
  16213. const rootDiv = parameters.div;
  16214. rootDiv.append(rootHtml);
  16215. if (parameters.viewport) {
  16216. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  16217. rootDiv.style.transform = transform;
  16218. }
  16219. if (intent !== "richText") {
  16220. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  16221. }
  16222. const textDivs = [];
  16223. while (stack.length > 0) {
  16224. const [parent, i, html] = stack.at(-1);
  16225. if (i + 1 === parent.children.length) {
  16226. stack.pop();
  16227. continue;
  16228. }
  16229. const child = parent.children[++stack.at(-1)[1]];
  16230. if (child === null) {
  16231. continue;
  16232. }
  16233. const {
  16234. name
  16235. } = child;
  16236. if (name === "#text") {
  16237. const node = document.createTextNode(child.value);
  16238. textDivs.push(node);
  16239. html.append(node);
  16240. continue;
  16241. }
  16242. const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
  16243. html.append(childHtml);
  16244. if (child.attributes) {
  16245. this.setAttributes({
  16246. html: childHtml,
  16247. element: child,
  16248. storage,
  16249. intent,
  16250. linkService
  16251. });
  16252. }
  16253. if (child.children && child.children.length > 0) {
  16254. stack.push([child, -1, childHtml]);
  16255. } else if (child.value) {
  16256. const node = document.createTextNode(child.value);
  16257. if (_xfa_text.XfaText.shouldBuildText(name)) {
  16258. textDivs.push(node);
  16259. }
  16260. childHtml.append(node);
  16261. }
  16262. }
  16263. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  16264. el.setAttribute("readOnly", true);
  16265. }
  16266. return {
  16267. textDivs
  16268. };
  16269. }
  16270. static update(parameters) {
  16271. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  16272. parameters.div.style.transform = transform;
  16273. parameters.div.hidden = false;
  16274. }
  16275. }
  16276. exports.XfaLayer = XfaLayer;
  16277. /***/ }),
  16278. /* 33 */
  16279. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  16280. Object.defineProperty(exports, "__esModule", ({
  16281. value: true
  16282. }));
  16283. exports.InkEditor = void 0;
  16284. var _util = __w_pdfjs_require__(1);
  16285. var _editor = __w_pdfjs_require__(4);
  16286. var _annotation_layer = __w_pdfjs_require__(29);
  16287. var _tools = __w_pdfjs_require__(5);
  16288. class InkEditor extends _editor.AnnotationEditor {
  16289. #baseHeight = 0;
  16290. #baseWidth = 0;
  16291. #boundCanvasContextMenu = this.canvasContextMenu.bind(this);
  16292. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  16293. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  16294. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  16295. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  16296. #currentPath2D = new Path2D();
  16297. #disableEditing = false;
  16298. #hasSomethingToDraw = false;
  16299. #isCanvasInitialized = false;
  16300. #observer = null;
  16301. #realWidth = 0;
  16302. #realHeight = 0;
  16303. #requestFrameCallback = null;
  16304. static _defaultColor = null;
  16305. static _defaultOpacity = 1;
  16306. static _defaultThickness = 1;
  16307. static _l10nPromise;
  16308. static _type = "ink";
  16309. constructor(params) {
  16310. super({
  16311. ...params,
  16312. name: "inkEditor"
  16313. });
  16314. this.color = params.color || null;
  16315. this.thickness = params.thickness || null;
  16316. this.opacity = params.opacity || null;
  16317. this.paths = [];
  16318. this.bezierPath2D = [];
  16319. this.allRawPaths = [];
  16320. this.currentPath = [];
  16321. this.scaleFactor = 1;
  16322. this.translationX = this.translationY = 0;
  16323. this.x = 0;
  16324. this.y = 0;
  16325. this._willKeepAspectRatio = true;
  16326. }
  16327. static initialize(l10n) {
  16328. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  16329. }
  16330. static updateDefaultParams(type, value) {
  16331. switch (type) {
  16332. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  16333. InkEditor._defaultThickness = value;
  16334. break;
  16335. case _util.AnnotationEditorParamsType.INK_COLOR:
  16336. InkEditor._defaultColor = value;
  16337. break;
  16338. case _util.AnnotationEditorParamsType.INK_OPACITY:
  16339. InkEditor._defaultOpacity = value / 100;
  16340. break;
  16341. }
  16342. }
  16343. updateParams(type, value) {
  16344. switch (type) {
  16345. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  16346. this.#updateThickness(value);
  16347. break;
  16348. case _util.AnnotationEditorParamsType.INK_COLOR:
  16349. this.#updateColor(value);
  16350. break;
  16351. case _util.AnnotationEditorParamsType.INK_OPACITY:
  16352. this.#updateOpacity(value);
  16353. break;
  16354. }
  16355. }
  16356. static get defaultPropertiesToUpdate() {
  16357. return [[_util.AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
  16358. }
  16359. get propertiesToUpdate() {
  16360. return [[_util.AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
  16361. }
  16362. #updateThickness(thickness) {
  16363. const savedThickness = this.thickness;
  16364. this.addCommands({
  16365. cmd: () => {
  16366. this.thickness = thickness;
  16367. this.#fitToContent();
  16368. },
  16369. undo: () => {
  16370. this.thickness = savedThickness;
  16371. this.#fitToContent();
  16372. },
  16373. mustExec: true,
  16374. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  16375. overwriteIfSameType: true,
  16376. keepUndo: true
  16377. });
  16378. }
  16379. #updateColor(color) {
  16380. const savedColor = this.color;
  16381. this.addCommands({
  16382. cmd: () => {
  16383. this.color = color;
  16384. this.#redraw();
  16385. },
  16386. undo: () => {
  16387. this.color = savedColor;
  16388. this.#redraw();
  16389. },
  16390. mustExec: true,
  16391. type: _util.AnnotationEditorParamsType.INK_COLOR,
  16392. overwriteIfSameType: true,
  16393. keepUndo: true
  16394. });
  16395. }
  16396. #updateOpacity(opacity) {
  16397. opacity /= 100;
  16398. const savedOpacity = this.opacity;
  16399. this.addCommands({
  16400. cmd: () => {
  16401. this.opacity = opacity;
  16402. this.#redraw();
  16403. },
  16404. undo: () => {
  16405. this.opacity = savedOpacity;
  16406. this.#redraw();
  16407. },
  16408. mustExec: true,
  16409. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  16410. overwriteIfSameType: true,
  16411. keepUndo: true
  16412. });
  16413. }
  16414. rebuild() {
  16415. if (!this.parent) {
  16416. return;
  16417. }
  16418. super.rebuild();
  16419. if (this.div === null) {
  16420. return;
  16421. }
  16422. if (!this.canvas) {
  16423. this.#createCanvas();
  16424. this.#createObserver();
  16425. }
  16426. if (!this.isAttachedToDOM) {
  16427. this.parent.add(this);
  16428. this.#setCanvasDims();
  16429. }
  16430. this.#fitToContent();
  16431. }
  16432. remove() {
  16433. if (this.canvas === null) {
  16434. return;
  16435. }
  16436. if (!this.isEmpty()) {
  16437. this.commit();
  16438. }
  16439. this.canvas.width = this.canvas.height = 0;
  16440. this.canvas.remove();
  16441. this.canvas = null;
  16442. this.#observer.disconnect();
  16443. this.#observer = null;
  16444. super.remove();
  16445. }
  16446. setParent(parent) {
  16447. if (!this.parent && parent) {
  16448. this._uiManager.removeShouldRescale(this);
  16449. } else if (this.parent && parent === null) {
  16450. this._uiManager.addShouldRescale(this);
  16451. }
  16452. super.setParent(parent);
  16453. }
  16454. onScaleChanging() {
  16455. const [parentWidth, parentHeight] = this.parentDimensions;
  16456. const width = this.width * parentWidth;
  16457. const height = this.height * parentHeight;
  16458. this.setDimensions(width, height);
  16459. }
  16460. enableEditMode() {
  16461. if (this.#disableEditing || this.canvas === null) {
  16462. return;
  16463. }
  16464. super.enableEditMode();
  16465. this._isDraggable = false;
  16466. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  16467. }
  16468. disableEditMode() {
  16469. if (!this.isInEditMode() || this.canvas === null) {
  16470. return;
  16471. }
  16472. super.disableEditMode();
  16473. this._isDraggable = !this.isEmpty();
  16474. this.div.classList.remove("editing");
  16475. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  16476. }
  16477. onceAdded() {
  16478. this._isDraggable = !this.isEmpty();
  16479. }
  16480. isEmpty() {
  16481. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  16482. }
  16483. #getInitialBBox() {
  16484. const {
  16485. parentRotation,
  16486. parentDimensions: [width, height]
  16487. } = this;
  16488. switch (parentRotation) {
  16489. case 90:
  16490. return [0, height, height, width];
  16491. case 180:
  16492. return [width, height, width, height];
  16493. case 270:
  16494. return [width, 0, height, width];
  16495. default:
  16496. return [0, 0, width, height];
  16497. }
  16498. }
  16499. #setStroke() {
  16500. const {
  16501. ctx,
  16502. color,
  16503. opacity,
  16504. thickness,
  16505. parentScale,
  16506. scaleFactor
  16507. } = this;
  16508. ctx.lineWidth = thickness * parentScale / scaleFactor;
  16509. ctx.lineCap = "round";
  16510. ctx.lineJoin = "round";
  16511. ctx.miterLimit = 10;
  16512. ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
  16513. }
  16514. #startDrawing(x, y) {
  16515. this.canvas.addEventListener("contextmenu", this.#boundCanvasContextMenu);
  16516. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  16517. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  16518. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  16519. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  16520. this.isEditing = true;
  16521. if (!this.#isCanvasInitialized) {
  16522. this.#isCanvasInitialized = true;
  16523. this.#setCanvasDims();
  16524. this.thickness ||= InkEditor._defaultThickness;
  16525. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  16526. this.opacity ??= InkEditor._defaultOpacity;
  16527. }
  16528. this.currentPath.push([x, y]);
  16529. this.#hasSomethingToDraw = false;
  16530. this.#setStroke();
  16531. this.#requestFrameCallback = () => {
  16532. this.#drawPoints();
  16533. if (this.#requestFrameCallback) {
  16534. window.requestAnimationFrame(this.#requestFrameCallback);
  16535. }
  16536. };
  16537. window.requestAnimationFrame(this.#requestFrameCallback);
  16538. }
  16539. #draw(x, y) {
  16540. const [lastX, lastY] = this.currentPath.at(-1);
  16541. if (this.currentPath.length > 1 && x === lastX && y === lastY) {
  16542. return;
  16543. }
  16544. const currentPath = this.currentPath;
  16545. let path2D = this.#currentPath2D;
  16546. currentPath.push([x, y]);
  16547. this.#hasSomethingToDraw = true;
  16548. if (currentPath.length <= 2) {
  16549. path2D.moveTo(...currentPath[0]);
  16550. path2D.lineTo(x, y);
  16551. return;
  16552. }
  16553. if (currentPath.length === 3) {
  16554. this.#currentPath2D = path2D = new Path2D();
  16555. path2D.moveTo(...currentPath[0]);
  16556. }
  16557. this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y);
  16558. }
  16559. #endPath() {
  16560. if (this.currentPath.length === 0) {
  16561. return;
  16562. }
  16563. const lastPoint = this.currentPath.at(-1);
  16564. this.#currentPath2D.lineTo(...lastPoint);
  16565. }
  16566. #stopDrawing(x, y) {
  16567. this.#requestFrameCallback = null;
  16568. x = Math.min(Math.max(x, 0), this.canvas.width);
  16569. y = Math.min(Math.max(y, 0), this.canvas.height);
  16570. this.#draw(x, y);
  16571. this.#endPath();
  16572. let bezier;
  16573. if (this.currentPath.length !== 1) {
  16574. bezier = this.#generateBezierPoints();
  16575. } else {
  16576. const xy = [x, y];
  16577. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  16578. }
  16579. const path2D = this.#currentPath2D;
  16580. const currentPath = this.currentPath;
  16581. this.currentPath = [];
  16582. this.#currentPath2D = new Path2D();
  16583. const cmd = () => {
  16584. this.allRawPaths.push(currentPath);
  16585. this.paths.push(bezier);
  16586. this.bezierPath2D.push(path2D);
  16587. this.rebuild();
  16588. };
  16589. const undo = () => {
  16590. this.allRawPaths.pop();
  16591. this.paths.pop();
  16592. this.bezierPath2D.pop();
  16593. if (this.paths.length === 0) {
  16594. this.remove();
  16595. } else {
  16596. if (!this.canvas) {
  16597. this.#createCanvas();
  16598. this.#createObserver();
  16599. }
  16600. this.#fitToContent();
  16601. }
  16602. };
  16603. this.addCommands({
  16604. cmd,
  16605. undo,
  16606. mustExec: true
  16607. });
  16608. }
  16609. #drawPoints() {
  16610. if (!this.#hasSomethingToDraw) {
  16611. return;
  16612. }
  16613. this.#hasSomethingToDraw = false;
  16614. const thickness = Math.ceil(this.thickness * this.parentScale);
  16615. const lastPoints = this.currentPath.slice(-3);
  16616. const x = lastPoints.map(xy => xy[0]);
  16617. const y = lastPoints.map(xy => xy[1]);
  16618. const xMin = Math.min(...x) - thickness;
  16619. const xMax = Math.max(...x) + thickness;
  16620. const yMin = Math.min(...y) - thickness;
  16621. const yMax = Math.max(...y) + thickness;
  16622. const {
  16623. ctx
  16624. } = this;
  16625. ctx.save();
  16626. ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  16627. for (const path of this.bezierPath2D) {
  16628. ctx.stroke(path);
  16629. }
  16630. ctx.stroke(this.#currentPath2D);
  16631. ctx.restore();
  16632. }
  16633. #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) {
  16634. const prevX = (x0 + x1) / 2;
  16635. const prevY = (y0 + y1) / 2;
  16636. const x3 = (x1 + x2) / 2;
  16637. const y3 = (y1 + y2) / 2;
  16638. path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3);
  16639. }
  16640. #generateBezierPoints() {
  16641. const path = this.currentPath;
  16642. if (path.length <= 2) {
  16643. return [[path[0], path[0], path.at(-1), path.at(-1)]];
  16644. }
  16645. const bezierPoints = [];
  16646. let i;
  16647. let [x0, y0] = path[0];
  16648. for (i = 1; i < path.length - 2; i++) {
  16649. const [x1, y1] = path[i];
  16650. const [x2, y2] = path[i + 1];
  16651. const x3 = (x1 + x2) / 2;
  16652. const y3 = (y1 + y2) / 2;
  16653. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  16654. const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3];
  16655. bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]);
  16656. [x0, y0] = [x3, y3];
  16657. }
  16658. const [x1, y1] = path[i];
  16659. const [x2, y2] = path[i + 1];
  16660. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  16661. const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3];
  16662. bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]);
  16663. return bezierPoints;
  16664. }
  16665. #redraw() {
  16666. if (this.isEmpty()) {
  16667. this.#updateTransform();
  16668. return;
  16669. }
  16670. this.#setStroke();
  16671. const {
  16672. canvas,
  16673. ctx
  16674. } = this;
  16675. ctx.setTransform(1, 0, 0, 1, 0, 0);
  16676. ctx.clearRect(0, 0, canvas.width, canvas.height);
  16677. this.#updateTransform();
  16678. for (const path of this.bezierPath2D) {
  16679. ctx.stroke(path);
  16680. }
  16681. }
  16682. commit() {
  16683. if (this.#disableEditing) {
  16684. return;
  16685. }
  16686. super.commit();
  16687. this.isEditing = false;
  16688. this.disableEditMode();
  16689. this.setInForeground();
  16690. this.#disableEditing = true;
  16691. this.div.classList.add("disabled");
  16692. this.#fitToContent(true);
  16693. this.makeResizable();
  16694. this.parent.addInkEditorIfNeeded(true);
  16695. this.moveInDOM();
  16696. this.div.focus({
  16697. preventScroll: true
  16698. });
  16699. }
  16700. focusin(event) {
  16701. if (!this._focusEventsAllowed) {
  16702. return;
  16703. }
  16704. super.focusin(event);
  16705. this.enableEditMode();
  16706. }
  16707. canvasPointerdown(event) {
  16708. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  16709. return;
  16710. }
  16711. this.setInForeground();
  16712. event.preventDefault();
  16713. if (event.type !== "mouse") {
  16714. this.div.focus();
  16715. }
  16716. this.#startDrawing(event.offsetX, event.offsetY);
  16717. }
  16718. canvasContextMenu(event) {
  16719. event.preventDefault();
  16720. }
  16721. canvasPointermove(event) {
  16722. event.preventDefault();
  16723. this.#draw(event.offsetX, event.offsetY);
  16724. }
  16725. canvasPointerup(event) {
  16726. event.preventDefault();
  16727. this.#endDrawing(event);
  16728. }
  16729. canvasPointerleave(event) {
  16730. this.#endDrawing(event);
  16731. }
  16732. #endDrawing(event) {
  16733. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  16734. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  16735. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  16736. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  16737. setTimeout(() => {
  16738. this.canvas.removeEventListener("contextmenu", this.#boundCanvasContextMenu);
  16739. }, 10);
  16740. this.#stopDrawing(event.offsetX, event.offsetY);
  16741. this.addToAnnotationStorage();
  16742. this.setInBackground();
  16743. }
  16744. #createCanvas() {
  16745. this.canvas = document.createElement("canvas");
  16746. this.canvas.width = this.canvas.height = 0;
  16747. this.canvas.className = "inkEditorCanvas";
  16748. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  16749. this.div.append(this.canvas);
  16750. this.ctx = this.canvas.getContext("2d");
  16751. }
  16752. #createObserver() {
  16753. this.#observer = new ResizeObserver(entries => {
  16754. const rect = entries[0].contentRect;
  16755. if (rect.width && rect.height) {
  16756. this.setDimensions(rect.width, rect.height);
  16757. }
  16758. });
  16759. this.#observer.observe(this.div);
  16760. }
  16761. get isResizable() {
  16762. return !this.isEmpty() && this.#disableEditing;
  16763. }
  16764. render() {
  16765. if (this.div) {
  16766. return this.div;
  16767. }
  16768. let baseX, baseY;
  16769. if (this.width) {
  16770. baseX = this.x;
  16771. baseY = this.y;
  16772. }
  16773. super.render();
  16774. InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  16775. const [x, y, w, h] = this.#getInitialBBox();
  16776. this.setAt(x, y, 0, 0);
  16777. this.setDims(w, h);
  16778. this.#createCanvas();
  16779. if (this.width) {
  16780. const [parentWidth, parentHeight] = this.parentDimensions;
  16781. this.setAspectRatio(this.width * parentWidth, this.height * parentHeight);
  16782. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  16783. this.#isCanvasInitialized = true;
  16784. this.#setCanvasDims();
  16785. this.setDims(this.width * parentWidth, this.height * parentHeight);
  16786. this.#redraw();
  16787. this.div.classList.add("disabled");
  16788. } else {
  16789. this.div.classList.add("editing");
  16790. this.enableEditMode();
  16791. }
  16792. this.#createObserver();
  16793. return this.div;
  16794. }
  16795. #setCanvasDims() {
  16796. if (!this.#isCanvasInitialized) {
  16797. return;
  16798. }
  16799. const [parentWidth, parentHeight] = this.parentDimensions;
  16800. this.canvas.width = Math.ceil(this.width * parentWidth);
  16801. this.canvas.height = Math.ceil(this.height * parentHeight);
  16802. this.#updateTransform();
  16803. }
  16804. setDimensions(width, height) {
  16805. const roundedWidth = Math.round(width);
  16806. const roundedHeight = Math.round(height);
  16807. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  16808. return;
  16809. }
  16810. this.#realWidth = roundedWidth;
  16811. this.#realHeight = roundedHeight;
  16812. this.canvas.style.visibility = "hidden";
  16813. const [parentWidth, parentHeight] = this.parentDimensions;
  16814. this.width = width / parentWidth;
  16815. this.height = height / parentHeight;
  16816. this.fixAndSetPosition();
  16817. if (this.#disableEditing) {
  16818. this.#setScaleFactor(width, height);
  16819. }
  16820. this.#setCanvasDims();
  16821. this.#redraw();
  16822. this.canvas.style.visibility = "visible";
  16823. this.fixDims();
  16824. }
  16825. #setScaleFactor(width, height) {
  16826. const padding = this.#getPadding();
  16827. const scaleFactorW = (width - padding) / this.#baseWidth;
  16828. const scaleFactorH = (height - padding) / this.#baseHeight;
  16829. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  16830. }
  16831. #updateTransform() {
  16832. const padding = this.#getPadding() / 2;
  16833. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  16834. }
  16835. static #buildPath2D(bezier) {
  16836. const path2D = new Path2D();
  16837. for (let i = 0, ii = bezier.length; i < ii; i++) {
  16838. const [first, control1, control2, second] = bezier[i];
  16839. if (i === 0) {
  16840. path2D.moveTo(...first);
  16841. }
  16842. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  16843. }
  16844. return path2D;
  16845. }
  16846. static #toPDFCoordinates(points, rect, rotation) {
  16847. const [blX, blY, trX, trY] = rect;
  16848. switch (rotation) {
  16849. case 0:
  16850. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16851. points[i] += blX;
  16852. points[i + 1] = trY - points[i + 1];
  16853. }
  16854. break;
  16855. case 90:
  16856. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16857. const x = points[i];
  16858. points[i] = points[i + 1] + blX;
  16859. points[i + 1] = x + blY;
  16860. }
  16861. break;
  16862. case 180:
  16863. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16864. points[i] = trX - points[i];
  16865. points[i + 1] += blY;
  16866. }
  16867. break;
  16868. case 270:
  16869. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16870. const x = points[i];
  16871. points[i] = trX - points[i + 1];
  16872. points[i + 1] = trY - x;
  16873. }
  16874. break;
  16875. default:
  16876. throw new Error("Invalid rotation");
  16877. }
  16878. return points;
  16879. }
  16880. static #fromPDFCoordinates(points, rect, rotation) {
  16881. const [blX, blY, trX, trY] = rect;
  16882. switch (rotation) {
  16883. case 0:
  16884. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16885. points[i] -= blX;
  16886. points[i + 1] = trY - points[i + 1];
  16887. }
  16888. break;
  16889. case 90:
  16890. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16891. const x = points[i];
  16892. points[i] = points[i + 1] - blY;
  16893. points[i + 1] = x - blX;
  16894. }
  16895. break;
  16896. case 180:
  16897. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16898. points[i] = trX - points[i];
  16899. points[i + 1] -= blY;
  16900. }
  16901. break;
  16902. case 270:
  16903. for (let i = 0, ii = points.length; i < ii; i += 2) {
  16904. const x = points[i];
  16905. points[i] = trY - points[i + 1];
  16906. points[i + 1] = trX - x;
  16907. }
  16908. break;
  16909. default:
  16910. throw new Error("Invalid rotation");
  16911. }
  16912. return points;
  16913. }
  16914. #serializePaths(s, tx, ty, rect) {
  16915. const paths = [];
  16916. const padding = this.thickness / 2;
  16917. const shiftX = s * tx + padding;
  16918. const shiftY = s * ty + padding;
  16919. for (const bezier of this.paths) {
  16920. const buffer = [];
  16921. const points = [];
  16922. for (let j = 0, jj = bezier.length; j < jj; j++) {
  16923. const [first, control1, control2, second] = bezier[j];
  16924. const p10 = s * first[0] + shiftX;
  16925. const p11 = s * first[1] + shiftY;
  16926. const p20 = s * control1[0] + shiftX;
  16927. const p21 = s * control1[1] + shiftY;
  16928. const p30 = s * control2[0] + shiftX;
  16929. const p31 = s * control2[1] + shiftY;
  16930. const p40 = s * second[0] + shiftX;
  16931. const p41 = s * second[1] + shiftY;
  16932. if (j === 0) {
  16933. buffer.push(p10, p11);
  16934. points.push(p10, p11);
  16935. }
  16936. buffer.push(p20, p21, p30, p31, p40, p41);
  16937. points.push(p20, p21);
  16938. if (j === jj - 1) {
  16939. points.push(p40, p41);
  16940. }
  16941. }
  16942. paths.push({
  16943. bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation),
  16944. points: InkEditor.#toPDFCoordinates(points, rect, this.rotation)
  16945. });
  16946. }
  16947. return paths;
  16948. }
  16949. #getBbox() {
  16950. let xMin = Infinity;
  16951. let xMax = -Infinity;
  16952. let yMin = Infinity;
  16953. let yMax = -Infinity;
  16954. for (const path of this.paths) {
  16955. for (const [first, control1, control2, second] of path) {
  16956. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  16957. xMin = Math.min(xMin, bbox[0]);
  16958. yMin = Math.min(yMin, bbox[1]);
  16959. xMax = Math.max(xMax, bbox[2]);
  16960. yMax = Math.max(yMax, bbox[3]);
  16961. }
  16962. }
  16963. return [xMin, yMin, xMax, yMax];
  16964. }
  16965. #getPadding() {
  16966. return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  16967. }
  16968. #fitToContent(firstTime = false) {
  16969. if (this.isEmpty()) {
  16970. return;
  16971. }
  16972. if (!this.#disableEditing) {
  16973. this.#redraw();
  16974. return;
  16975. }
  16976. const bbox = this.#getBbox();
  16977. const padding = this.#getPadding();
  16978. this.#baseWidth = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  16979. this.#baseHeight = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  16980. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  16981. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  16982. const [parentWidth, parentHeight] = this.parentDimensions;
  16983. this.width = width / parentWidth;
  16984. this.height = height / parentHeight;
  16985. this.setAspectRatio(width, height);
  16986. const prevTranslationX = this.translationX;
  16987. const prevTranslationY = this.translationY;
  16988. this.translationX = -bbox[0];
  16989. this.translationY = -bbox[1];
  16990. this.#setCanvasDims();
  16991. this.#redraw();
  16992. this.#realWidth = width;
  16993. this.#realHeight = height;
  16994. this.setDims(width, height);
  16995. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  16996. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  16997. }
  16998. static deserialize(data, parent, uiManager) {
  16999. if (data instanceof _annotation_layer.InkAnnotationElement) {
  17000. return null;
  17001. }
  17002. const editor = super.deserialize(data, parent, uiManager);
  17003. editor.thickness = data.thickness;
  17004. editor.color = _util.Util.makeHexColor(...data.color);
  17005. editor.opacity = data.opacity;
  17006. const [pageWidth, pageHeight] = editor.pageDimensions;
  17007. const width = editor.width * pageWidth;
  17008. const height = editor.height * pageHeight;
  17009. const scaleFactor = editor.parentScale;
  17010. const padding = data.thickness / 2;
  17011. editor.#disableEditing = true;
  17012. editor.#realWidth = Math.round(width);
  17013. editor.#realHeight = Math.round(height);
  17014. const {
  17015. paths,
  17016. rect,
  17017. rotation
  17018. } = data;
  17019. for (let {
  17020. bezier
  17021. } of paths) {
  17022. bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation);
  17023. const path = [];
  17024. editor.paths.push(path);
  17025. let p0 = scaleFactor * (bezier[0] - padding);
  17026. let p1 = scaleFactor * (bezier[1] - padding);
  17027. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  17028. const p10 = scaleFactor * (bezier[i] - padding);
  17029. const p11 = scaleFactor * (bezier[i + 1] - padding);
  17030. const p20 = scaleFactor * (bezier[i + 2] - padding);
  17031. const p21 = scaleFactor * (bezier[i + 3] - padding);
  17032. const p30 = scaleFactor * (bezier[i + 4] - padding);
  17033. const p31 = scaleFactor * (bezier[i + 5] - padding);
  17034. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  17035. p0 = p30;
  17036. p1 = p31;
  17037. }
  17038. const path2D = this.#buildPath2D(path);
  17039. editor.bezierPath2D.push(path2D);
  17040. }
  17041. const bbox = editor.#getBbox();
  17042. editor.#baseWidth = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  17043. editor.#baseHeight = Math.max(_editor.AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  17044. editor.#setScaleFactor(width, height);
  17045. return editor;
  17046. }
  17047. serialize() {
  17048. if (this.isEmpty()) {
  17049. return null;
  17050. }
  17051. const rect = this.getRect(0, 0);
  17052. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  17053. return {
  17054. annotationType: _util.AnnotationEditorType.INK,
  17055. color,
  17056. thickness: this.thickness,
  17057. opacity: this.opacity,
  17058. paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect),
  17059. pageIndex: this.pageIndex,
  17060. rect,
  17061. rotation: this.rotation
  17062. };
  17063. }
  17064. }
  17065. exports.InkEditor = InkEditor;
  17066. /***/ }),
  17067. /* 34 */
  17068. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  17069. Object.defineProperty(exports, "__esModule", ({
  17070. value: true
  17071. }));
  17072. exports.StampEditor = void 0;
  17073. var _util = __w_pdfjs_require__(1);
  17074. var _editor = __w_pdfjs_require__(4);
  17075. var _display_utils = __w_pdfjs_require__(6);
  17076. var _annotation_layer = __w_pdfjs_require__(29);
  17077. class StampEditor extends _editor.AnnotationEditor {
  17078. #bitmap = null;
  17079. #bitmapId = null;
  17080. #bitmapPromise = null;
  17081. #bitmapUrl = null;
  17082. #bitmapFile = null;
  17083. #canvas = null;
  17084. #observer = null;
  17085. #resizeTimeoutId = null;
  17086. #isSvg = false;
  17087. #hasBeenAddedInUndoStack = false;
  17088. static _type = "stamp";
  17089. constructor(params) {
  17090. super({
  17091. ...params,
  17092. name: "stampEditor"
  17093. });
  17094. this.#bitmapUrl = params.bitmapUrl;
  17095. this.#bitmapFile = params.bitmapFile;
  17096. }
  17097. static get supportedTypes() {
  17098. const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
  17099. return (0, _util.shadow)(this, "supportedTypes", types.map(type => `image/${type}`));
  17100. }
  17101. static get supportedTypesStr() {
  17102. return (0, _util.shadow)(this, "supportedTypesStr", this.supportedTypes.join(","));
  17103. }
  17104. static isHandlingMimeForPasting(mime) {
  17105. return this.supportedTypes.includes(mime);
  17106. }
  17107. static paste(item, parent) {
  17108. parent.pasteEditor(_util.AnnotationEditorType.STAMP, {
  17109. bitmapFile: item.getAsFile()
  17110. });
  17111. }
  17112. #getBitmapFetched(data, fromId = false) {
  17113. if (!data) {
  17114. this.remove();
  17115. return;
  17116. }
  17117. this.#bitmap = data.bitmap;
  17118. if (!fromId) {
  17119. this.#bitmapId = data.id;
  17120. this.#isSvg = data.isSvg;
  17121. }
  17122. this.#createCanvas();
  17123. }
  17124. #getBitmapDone() {
  17125. this.#bitmapPromise = null;
  17126. this._uiManager.enableWaiting(false);
  17127. if (this.#canvas) {
  17128. this.div.focus();
  17129. }
  17130. }
  17131. #getBitmap() {
  17132. if (this.#bitmapId) {
  17133. this._uiManager.enableWaiting(true);
  17134. this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
  17135. return;
  17136. }
  17137. if (this.#bitmapUrl) {
  17138. const url = this.#bitmapUrl;
  17139. this.#bitmapUrl = null;
  17140. this._uiManager.enableWaiting(true);
  17141. this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  17142. return;
  17143. }
  17144. if (this.#bitmapFile) {
  17145. const file = this.#bitmapFile;
  17146. this.#bitmapFile = null;
  17147. this._uiManager.enableWaiting(true);
  17148. this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  17149. return;
  17150. }
  17151. const input = document.createElement("input");
  17152. input.type = "file";
  17153. input.accept = StampEditor.supportedTypesStr;
  17154. this.#bitmapPromise = new Promise(resolve => {
  17155. input.addEventListener("change", async () => {
  17156. if (!input.files || input.files.length === 0) {
  17157. this.remove();
  17158. } else {
  17159. this._uiManager.enableWaiting(true);
  17160. const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
  17161. this.#getBitmapFetched(data);
  17162. }
  17163. resolve();
  17164. });
  17165. input.addEventListener("cancel", () => {
  17166. this.remove();
  17167. resolve();
  17168. });
  17169. }).finally(() => this.#getBitmapDone());
  17170. input.click();
  17171. }
  17172. remove() {
  17173. if (this.#bitmapId) {
  17174. this.#bitmap = null;
  17175. this._uiManager.imageManager.deleteId(this.#bitmapId);
  17176. this.#canvas?.remove();
  17177. this.#canvas = null;
  17178. this.#observer?.disconnect();
  17179. this.#observer = null;
  17180. }
  17181. super.remove();
  17182. }
  17183. rebuild() {
  17184. if (!this.parent) {
  17185. if (this.#bitmapId) {
  17186. this.#getBitmap();
  17187. }
  17188. return;
  17189. }
  17190. super.rebuild();
  17191. if (this.div === null) {
  17192. return;
  17193. }
  17194. if (this.#bitmapId) {
  17195. this.#getBitmap();
  17196. }
  17197. if (!this.isAttachedToDOM) {
  17198. this.parent.add(this);
  17199. }
  17200. }
  17201. onceAdded() {
  17202. this._isDraggable = true;
  17203. this.div.focus();
  17204. }
  17205. isEmpty() {
  17206. return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile);
  17207. }
  17208. get isResizable() {
  17209. return true;
  17210. }
  17211. render() {
  17212. if (this.div) {
  17213. return this.div;
  17214. }
  17215. let baseX, baseY;
  17216. if (this.width) {
  17217. baseX = this.x;
  17218. baseY = this.y;
  17219. }
  17220. super.render();
  17221. this.div.hidden = true;
  17222. if (this.#bitmap) {
  17223. this.#createCanvas();
  17224. } else {
  17225. this.#getBitmap();
  17226. }
  17227. if (this.width) {
  17228. const [parentWidth, parentHeight] = this.parentDimensions;
  17229. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  17230. }
  17231. return this.div;
  17232. }
  17233. #createCanvas() {
  17234. const {
  17235. div
  17236. } = this;
  17237. let {
  17238. width,
  17239. height
  17240. } = this.#bitmap;
  17241. const [pageWidth, pageHeight] = this.pageDimensions;
  17242. const MAX_RATIO = 0.75;
  17243. if (this.width) {
  17244. width = this.width * pageWidth;
  17245. height = this.height * pageHeight;
  17246. } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
  17247. const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
  17248. width *= factor;
  17249. height *= factor;
  17250. }
  17251. const [parentWidth, parentHeight] = this.parentDimensions;
  17252. this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
  17253. this._uiManager.enableWaiting(false);
  17254. const canvas = this.#canvas = document.createElement("canvas");
  17255. div.append(canvas);
  17256. div.hidden = false;
  17257. this.#drawBitmap(width, height);
  17258. this.#createObserver();
  17259. if (!this.#hasBeenAddedInUndoStack) {
  17260. this.parent.addUndoableEditor(this);
  17261. this.#hasBeenAddedInUndoStack = true;
  17262. }
  17263. }
  17264. #setDimensions(width, height) {
  17265. const [parentWidth, parentHeight] = this.parentDimensions;
  17266. this.width = width / parentWidth;
  17267. this.height = height / parentHeight;
  17268. this.setDims(width, height);
  17269. if (this._initialOptions?.isCentered) {
  17270. this.center();
  17271. } else {
  17272. this.fixAndSetPosition();
  17273. }
  17274. this._initialOptions = null;
  17275. if (this.#resizeTimeoutId !== null) {
  17276. clearTimeout(this.#resizeTimeoutId);
  17277. }
  17278. const TIME_TO_WAIT = 200;
  17279. this.#resizeTimeoutId = setTimeout(() => {
  17280. this.#resizeTimeoutId = null;
  17281. this.#drawBitmap(width, height);
  17282. }, TIME_TO_WAIT);
  17283. }
  17284. #scaleBitmap(width, height) {
  17285. const {
  17286. width: bitmapWidth,
  17287. height: bitmapHeight
  17288. } = this.#bitmap;
  17289. let newWidth = bitmapWidth;
  17290. let newHeight = bitmapHeight;
  17291. let bitmap = this.#bitmap;
  17292. while (newWidth > 2 * width || newHeight > 2 * height) {
  17293. const prevWidth = newWidth;
  17294. const prevHeight = newHeight;
  17295. if (newWidth > 2 * width) {
  17296. newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
  17297. }
  17298. if (newHeight > 2 * height) {
  17299. newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
  17300. }
  17301. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  17302. const ctx = offscreen.getContext("2d");
  17303. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  17304. bitmap = offscreen.transferToImageBitmap();
  17305. }
  17306. return bitmap;
  17307. }
  17308. #drawBitmap(width, height) {
  17309. width = Math.ceil(width);
  17310. height = Math.ceil(height);
  17311. const canvas = this.#canvas;
  17312. if (!canvas || canvas.width === width && canvas.height === height) {
  17313. return;
  17314. }
  17315. canvas.width = width;
  17316. canvas.height = height;
  17317. const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(width, height);
  17318. const ctx = canvas.getContext("2d");
  17319. ctx.filter = this._uiManager.hcmFilter;
  17320. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, width, height);
  17321. }
  17322. #serializeBitmap(toUrl) {
  17323. if (toUrl) {
  17324. if (this.#isSvg) {
  17325. const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
  17326. if (url) {
  17327. return url;
  17328. }
  17329. }
  17330. const canvas = document.createElement("canvas");
  17331. ({
  17332. width: canvas.width,
  17333. height: canvas.height
  17334. } = this.#bitmap);
  17335. const ctx = canvas.getContext("2d");
  17336. ctx.drawImage(this.#bitmap, 0, 0);
  17337. return canvas.toDataURL();
  17338. }
  17339. if (this.#isSvg) {
  17340. const [pageWidth, pageHeight] = this.pageDimensions;
  17341. const width = Math.round(this.width * pageWidth * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  17342. const height = Math.round(this.height * pageHeight * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  17343. const offscreen = new OffscreenCanvas(width, height);
  17344. const ctx = offscreen.getContext("2d");
  17345. ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
  17346. return offscreen.transferToImageBitmap();
  17347. }
  17348. return structuredClone(this.#bitmap);
  17349. }
  17350. #createObserver() {
  17351. this.#observer = new ResizeObserver(entries => {
  17352. const rect = entries[0].contentRect;
  17353. if (rect.width && rect.height) {
  17354. this.#setDimensions(rect.width, rect.height);
  17355. }
  17356. });
  17357. this.#observer.observe(this.div);
  17358. }
  17359. static deserialize(data, parent, uiManager) {
  17360. if (data instanceof _annotation_layer.StampAnnotationElement) {
  17361. return null;
  17362. }
  17363. const editor = super.deserialize(data, parent, uiManager);
  17364. const {
  17365. rect,
  17366. bitmapUrl,
  17367. bitmapId,
  17368. isSvg
  17369. } = data;
  17370. if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
  17371. editor.#bitmapId = bitmapId;
  17372. } else {
  17373. editor.#bitmapUrl = bitmapUrl;
  17374. }
  17375. editor.#isSvg = isSvg;
  17376. const [parentWidth, parentHeight] = editor.pageDimensions;
  17377. editor.width = (rect[2] - rect[0]) / parentWidth;
  17378. editor.height = (rect[3] - rect[1]) / parentHeight;
  17379. return editor;
  17380. }
  17381. serialize(isForCopying = false, context = null) {
  17382. if (this.isEmpty()) {
  17383. return null;
  17384. }
  17385. const serialized = {
  17386. annotationType: _util.AnnotationEditorType.STAMP,
  17387. bitmapId: this.#bitmapId,
  17388. pageIndex: this.pageIndex,
  17389. rect: this.getRect(0, 0),
  17390. rotation: this.rotation,
  17391. isSvg: this.#isSvg
  17392. };
  17393. if (isForCopying) {
  17394. serialized.bitmapUrl = this.#serializeBitmap(true);
  17395. return serialized;
  17396. }
  17397. if (context === null) {
  17398. return serialized;
  17399. }
  17400. context.stamps ||= new Map();
  17401. const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
  17402. if (!context.stamps.has(this.#bitmapId)) {
  17403. context.stamps.set(this.#bitmapId, {
  17404. area,
  17405. serialized
  17406. });
  17407. serialized.bitmap = this.#serializeBitmap(false);
  17408. } else if (this.#isSvg) {
  17409. const prevData = context.stamps.get(this.#bitmapId);
  17410. if (area > prevData.area) {
  17411. prevData.area = area;
  17412. prevData.serialized.bitmap.close();
  17413. prevData.serialized.bitmap = this.#serializeBitmap(false);
  17414. }
  17415. }
  17416. return serialized;
  17417. }
  17418. }
  17419. exports.StampEditor = StampEditor;
  17420. /***/ })
  17421. /******/ ]);
  17422. /************************************************************************/
  17423. /******/ // The module cache
  17424. /******/ var __webpack_module_cache__ = {};
  17425. /******/
  17426. /******/ // The require function
  17427. /******/ function __w_pdfjs_require__(moduleId) {
  17428. /******/ // Check if module is in cache
  17429. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  17430. /******/ if (cachedModule !== undefined) {
  17431. /******/ return cachedModule.exports;
  17432. /******/ }
  17433. /******/ // Create a new module (and put it into the cache)
  17434. /******/ var module = __webpack_module_cache__[moduleId] = {
  17435. /******/ // no module.id needed
  17436. /******/ // no module.loaded needed
  17437. /******/ exports: {}
  17438. /******/ };
  17439. /******/
  17440. /******/ // Execute the module function
  17441. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  17442. /******/
  17443. /******/ // Return the exports of the module
  17444. /******/ return module.exports;
  17445. /******/ }
  17446. /******/
  17447. /************************************************************************/
  17448. var __webpack_exports__ = {};
  17449. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  17450. (() => {
  17451. var exports = __webpack_exports__;
  17452. Object.defineProperty(exports, "__esModule", ({
  17453. value: true
  17454. }));
  17455. Object.defineProperty(exports, "AbortException", ({
  17456. enumerable: true,
  17457. get: function () {
  17458. return _util.AbortException;
  17459. }
  17460. }));
  17461. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  17462. enumerable: true,
  17463. get: function () {
  17464. return _annotation_editor_layer.AnnotationEditorLayer;
  17465. }
  17466. }));
  17467. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  17468. enumerable: true,
  17469. get: function () {
  17470. return _util.AnnotationEditorParamsType;
  17471. }
  17472. }));
  17473. Object.defineProperty(exports, "AnnotationEditorType", ({
  17474. enumerable: true,
  17475. get: function () {
  17476. return _util.AnnotationEditorType;
  17477. }
  17478. }));
  17479. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  17480. enumerable: true,
  17481. get: function () {
  17482. return _tools.AnnotationEditorUIManager;
  17483. }
  17484. }));
  17485. Object.defineProperty(exports, "AnnotationLayer", ({
  17486. enumerable: true,
  17487. get: function () {
  17488. return _annotation_layer.AnnotationLayer;
  17489. }
  17490. }));
  17491. Object.defineProperty(exports, "AnnotationMode", ({
  17492. enumerable: true,
  17493. get: function () {
  17494. return _util.AnnotationMode;
  17495. }
  17496. }));
  17497. Object.defineProperty(exports, "CMapCompressionType", ({
  17498. enumerable: true,
  17499. get: function () {
  17500. return _util.CMapCompressionType;
  17501. }
  17502. }));
  17503. Object.defineProperty(exports, "FeatureTest", ({
  17504. enumerable: true,
  17505. get: function () {
  17506. return _util.FeatureTest;
  17507. }
  17508. }));
  17509. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  17510. enumerable: true,
  17511. get: function () {
  17512. return _worker_options.GlobalWorkerOptions;
  17513. }
  17514. }));
  17515. Object.defineProperty(exports, "ImageKind", ({
  17516. enumerable: true,
  17517. get: function () {
  17518. return _util.ImageKind;
  17519. }
  17520. }));
  17521. Object.defineProperty(exports, "InvalidPDFException", ({
  17522. enumerable: true,
  17523. get: function () {
  17524. return _util.InvalidPDFException;
  17525. }
  17526. }));
  17527. Object.defineProperty(exports, "MissingPDFException", ({
  17528. enumerable: true,
  17529. get: function () {
  17530. return _util.MissingPDFException;
  17531. }
  17532. }));
  17533. Object.defineProperty(exports, "OPS", ({
  17534. enumerable: true,
  17535. get: function () {
  17536. return _util.OPS;
  17537. }
  17538. }));
  17539. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  17540. enumerable: true,
  17541. get: function () {
  17542. return _api.PDFDataRangeTransport;
  17543. }
  17544. }));
  17545. Object.defineProperty(exports, "PDFDateString", ({
  17546. enumerable: true,
  17547. get: function () {
  17548. return _display_utils.PDFDateString;
  17549. }
  17550. }));
  17551. Object.defineProperty(exports, "PDFWorker", ({
  17552. enumerable: true,
  17553. get: function () {
  17554. return _api.PDFWorker;
  17555. }
  17556. }));
  17557. Object.defineProperty(exports, "PasswordResponses", ({
  17558. enumerable: true,
  17559. get: function () {
  17560. return _util.PasswordResponses;
  17561. }
  17562. }));
  17563. Object.defineProperty(exports, "PermissionFlag", ({
  17564. enumerable: true,
  17565. get: function () {
  17566. return _util.PermissionFlag;
  17567. }
  17568. }));
  17569. Object.defineProperty(exports, "PixelsPerInch", ({
  17570. enumerable: true,
  17571. get: function () {
  17572. return _display_utils.PixelsPerInch;
  17573. }
  17574. }));
  17575. Object.defineProperty(exports, "PromiseCapability", ({
  17576. enumerable: true,
  17577. get: function () {
  17578. return _util.PromiseCapability;
  17579. }
  17580. }));
  17581. Object.defineProperty(exports, "RenderingCancelledException", ({
  17582. enumerable: true,
  17583. get: function () {
  17584. return _display_utils.RenderingCancelledException;
  17585. }
  17586. }));
  17587. Object.defineProperty(exports, "SVGGraphics", ({
  17588. enumerable: true,
  17589. get: function () {
  17590. return _api.SVGGraphics;
  17591. }
  17592. }));
  17593. Object.defineProperty(exports, "UnexpectedResponseException", ({
  17594. enumerable: true,
  17595. get: function () {
  17596. return _util.UnexpectedResponseException;
  17597. }
  17598. }));
  17599. Object.defineProperty(exports, "Util", ({
  17600. enumerable: true,
  17601. get: function () {
  17602. return _util.Util;
  17603. }
  17604. }));
  17605. Object.defineProperty(exports, "VerbosityLevel", ({
  17606. enumerable: true,
  17607. get: function () {
  17608. return _util.VerbosityLevel;
  17609. }
  17610. }));
  17611. Object.defineProperty(exports, "XfaLayer", ({
  17612. enumerable: true,
  17613. get: function () {
  17614. return _xfa_layer.XfaLayer;
  17615. }
  17616. }));
  17617. Object.defineProperty(exports, "build", ({
  17618. enumerable: true,
  17619. get: function () {
  17620. return _api.build;
  17621. }
  17622. }));
  17623. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  17624. enumerable: true,
  17625. get: function () {
  17626. return _util.createValidAbsoluteUrl;
  17627. }
  17628. }));
  17629. Object.defineProperty(exports, "getDocument", ({
  17630. enumerable: true,
  17631. get: function () {
  17632. return _api.getDocument;
  17633. }
  17634. }));
  17635. Object.defineProperty(exports, "getFilenameFromUrl", ({
  17636. enumerable: true,
  17637. get: function () {
  17638. return _display_utils.getFilenameFromUrl;
  17639. }
  17640. }));
  17641. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  17642. enumerable: true,
  17643. get: function () {
  17644. return _display_utils.getPdfFilenameFromUrl;
  17645. }
  17646. }));
  17647. Object.defineProperty(exports, "getXfaPageViewport", ({
  17648. enumerable: true,
  17649. get: function () {
  17650. return _display_utils.getXfaPageViewport;
  17651. }
  17652. }));
  17653. Object.defineProperty(exports, "isDataScheme", ({
  17654. enumerable: true,
  17655. get: function () {
  17656. return _display_utils.isDataScheme;
  17657. }
  17658. }));
  17659. Object.defineProperty(exports, "isPdfFile", ({
  17660. enumerable: true,
  17661. get: function () {
  17662. return _display_utils.isPdfFile;
  17663. }
  17664. }));
  17665. Object.defineProperty(exports, "loadScript", ({
  17666. enumerable: true,
  17667. get: function () {
  17668. return _display_utils.loadScript;
  17669. }
  17670. }));
  17671. Object.defineProperty(exports, "normalizeUnicode", ({
  17672. enumerable: true,
  17673. get: function () {
  17674. return _util.normalizeUnicode;
  17675. }
  17676. }));
  17677. Object.defineProperty(exports, "renderTextLayer", ({
  17678. enumerable: true,
  17679. get: function () {
  17680. return _text_layer.renderTextLayer;
  17681. }
  17682. }));
  17683. Object.defineProperty(exports, "setLayerDimensions", ({
  17684. enumerable: true,
  17685. get: function () {
  17686. return _display_utils.setLayerDimensions;
  17687. }
  17688. }));
  17689. Object.defineProperty(exports, "shadow", ({
  17690. enumerable: true,
  17691. get: function () {
  17692. return _util.shadow;
  17693. }
  17694. }));
  17695. Object.defineProperty(exports, "updateTextLayer", ({
  17696. enumerable: true,
  17697. get: function () {
  17698. return _text_layer.updateTextLayer;
  17699. }
  17700. }));
  17701. Object.defineProperty(exports, "version", ({
  17702. enumerable: true,
  17703. get: function () {
  17704. return _api.version;
  17705. }
  17706. }));
  17707. var _util = __w_pdfjs_require__(1);
  17708. var _api = __w_pdfjs_require__(2);
  17709. var _display_utils = __w_pdfjs_require__(6);
  17710. var _text_layer = __w_pdfjs_require__(26);
  17711. var _annotation_editor_layer = __w_pdfjs_require__(27);
  17712. var _tools = __w_pdfjs_require__(5);
  17713. var _annotation_layer = __w_pdfjs_require__(29);
  17714. var _worker_options = __w_pdfjs_require__(14);
  17715. var _xfa_layer = __w_pdfjs_require__(32);
  17716. const pdfjsVersion = '3.10.111';
  17717. const pdfjsBuild = 'e142baecb';
  17718. })();
  17719. /******/ return __webpack_exports__;
  17720. /******/ })()
  17721. ;
  17722. });
  17723. //# sourceMappingURL=pdf.js.map