pdf.js 486 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 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 = factory();
  25. else if(typeof define === 'function' && define.amd)
  26. define("pdfjs-dist/build/pdf", [], factory);
  27. else if(typeof exports === 'object')
  28. exports["pdfjs-dist/build/pdf"] = 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.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
  42. exports.arrayByteLength = arrayByteLength;
  43. exports.arraysToBytes = arraysToBytes;
  44. exports.assert = assert;
  45. exports.bytesToString = bytesToString;
  46. exports.createPromiseCapability = createPromiseCapability;
  47. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  48. exports.escapeString = escapeString;
  49. exports.getModificationDate = getModificationDate;
  50. exports.getVerbosityLevel = getVerbosityLevel;
  51. exports.info = info;
  52. exports.isArrayBuffer = isArrayBuffer;
  53. exports.isArrayEqual = isArrayEqual;
  54. exports.isAscii = isAscii;
  55. exports.objectFromMap = objectFromMap;
  56. exports.objectSize = objectSize;
  57. exports.setVerbosityLevel = setVerbosityLevel;
  58. exports.shadow = shadow;
  59. exports.string32 = string32;
  60. exports.stringToBytes = stringToBytes;
  61. exports.stringToPDFString = stringToPDFString;
  62. exports.stringToUTF16BEString = stringToUTF16BEString;
  63. exports.stringToUTF8String = stringToUTF8String;
  64. exports.unreachable = unreachable;
  65. exports.utf8StringToString = utf8StringToString;
  66. exports.warn = warn;
  67. ;
  68. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  69. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  70. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  71. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  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 RenderingIntentFlag = {
  77. ANY: 0x01,
  78. DISPLAY: 0x02,
  79. PRINT: 0x04,
  80. ANNOTATIONS_FORMS: 0x10,
  81. ANNOTATIONS_STORAGE: 0x20,
  82. ANNOTATIONS_DISABLE: 0x40,
  83. OPLIST: 0x100
  84. };
  85. exports.RenderingIntentFlag = RenderingIntentFlag;
  86. const AnnotationMode = {
  87. DISABLE: 0,
  88. ENABLE: 1,
  89. ENABLE_FORMS: 2,
  90. ENABLE_STORAGE: 3
  91. };
  92. exports.AnnotationMode = AnnotationMode;
  93. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  94. exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
  95. const AnnotationEditorType = {
  96. DISABLE: -1,
  97. NONE: 0,
  98. FREETEXT: 3,
  99. INK: 15
  100. };
  101. exports.AnnotationEditorType = AnnotationEditorType;
  102. const AnnotationEditorParamsType = {
  103. FREETEXT_SIZE: 1,
  104. FREETEXT_COLOR: 2,
  105. FREETEXT_OPACITY: 3,
  106. INK_COLOR: 11,
  107. INK_THICKNESS: 12,
  108. INK_OPACITY: 13
  109. };
  110. exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
  111. const PermissionFlag = {
  112. PRINT: 0x04,
  113. MODIFY_CONTENTS: 0x08,
  114. COPY: 0x10,
  115. MODIFY_ANNOTATIONS: 0x20,
  116. FILL_INTERACTIVE_FORMS: 0x100,
  117. COPY_FOR_ACCESSIBILITY: 0x200,
  118. ASSEMBLE: 0x400,
  119. PRINT_HIGH_QUALITY: 0x800
  120. };
  121. exports.PermissionFlag = PermissionFlag;
  122. const TextRenderingMode = {
  123. FILL: 0,
  124. STROKE: 1,
  125. FILL_STROKE: 2,
  126. INVISIBLE: 3,
  127. FILL_ADD_TO_PATH: 4,
  128. STROKE_ADD_TO_PATH: 5,
  129. FILL_STROKE_ADD_TO_PATH: 6,
  130. ADD_TO_PATH: 7,
  131. FILL_STROKE_MASK: 3,
  132. ADD_TO_PATH_FLAG: 4
  133. };
  134. exports.TextRenderingMode = TextRenderingMode;
  135. const ImageKind = {
  136. GRAYSCALE_1BPP: 1,
  137. RGB_24BPP: 2,
  138. RGBA_32BPP: 3
  139. };
  140. exports.ImageKind = ImageKind;
  141. const AnnotationType = {
  142. TEXT: 1,
  143. LINK: 2,
  144. FREETEXT: 3,
  145. LINE: 4,
  146. SQUARE: 5,
  147. CIRCLE: 6,
  148. POLYGON: 7,
  149. POLYLINE: 8,
  150. HIGHLIGHT: 9,
  151. UNDERLINE: 10,
  152. SQUIGGLY: 11,
  153. STRIKEOUT: 12,
  154. STAMP: 13,
  155. CARET: 14,
  156. INK: 15,
  157. POPUP: 16,
  158. FILEATTACHMENT: 17,
  159. SOUND: 18,
  160. MOVIE: 19,
  161. WIDGET: 20,
  162. SCREEN: 21,
  163. PRINTERMARK: 22,
  164. TRAPNET: 23,
  165. WATERMARK: 24,
  166. THREED: 25,
  167. REDACT: 26
  168. };
  169. exports.AnnotationType = AnnotationType;
  170. const AnnotationStateModelType = {
  171. MARKED: "Marked",
  172. REVIEW: "Review"
  173. };
  174. exports.AnnotationStateModelType = AnnotationStateModelType;
  175. const AnnotationMarkedState = {
  176. MARKED: "Marked",
  177. UNMARKED: "Unmarked"
  178. };
  179. exports.AnnotationMarkedState = AnnotationMarkedState;
  180. const AnnotationReviewState = {
  181. ACCEPTED: "Accepted",
  182. REJECTED: "Rejected",
  183. CANCELLED: "Cancelled",
  184. COMPLETED: "Completed",
  185. NONE: "None"
  186. };
  187. exports.AnnotationReviewState = AnnotationReviewState;
  188. const AnnotationReplyType = {
  189. GROUP: "Group",
  190. REPLY: "R"
  191. };
  192. exports.AnnotationReplyType = AnnotationReplyType;
  193. const AnnotationFlag = {
  194. INVISIBLE: 0x01,
  195. HIDDEN: 0x02,
  196. PRINT: 0x04,
  197. NOZOOM: 0x08,
  198. NOROTATE: 0x10,
  199. NOVIEW: 0x20,
  200. READONLY: 0x40,
  201. LOCKED: 0x80,
  202. TOGGLENOVIEW: 0x100,
  203. LOCKEDCONTENTS: 0x200
  204. };
  205. exports.AnnotationFlag = AnnotationFlag;
  206. const AnnotationFieldFlag = {
  207. READONLY: 0x0000001,
  208. REQUIRED: 0x0000002,
  209. NOEXPORT: 0x0000004,
  210. MULTILINE: 0x0001000,
  211. PASSWORD: 0x0002000,
  212. NOTOGGLETOOFF: 0x0004000,
  213. RADIO: 0x0008000,
  214. PUSHBUTTON: 0x0010000,
  215. COMBO: 0x0020000,
  216. EDIT: 0x0040000,
  217. SORT: 0x0080000,
  218. FILESELECT: 0x0100000,
  219. MULTISELECT: 0x0200000,
  220. DONOTSPELLCHECK: 0x0400000,
  221. DONOTSCROLL: 0x0800000,
  222. COMB: 0x1000000,
  223. RICHTEXT: 0x2000000,
  224. RADIOSINUNISON: 0x2000000,
  225. COMMITONSELCHANGE: 0x4000000
  226. };
  227. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  228. const AnnotationBorderStyleType = {
  229. SOLID: 1,
  230. DASHED: 2,
  231. BEVELED: 3,
  232. INSET: 4,
  233. UNDERLINE: 5
  234. };
  235. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  236. const AnnotationActionEventType = {
  237. E: "Mouse Enter",
  238. X: "Mouse Exit",
  239. D: "Mouse Down",
  240. U: "Mouse Up",
  241. Fo: "Focus",
  242. Bl: "Blur",
  243. PO: "PageOpen",
  244. PC: "PageClose",
  245. PV: "PageVisible",
  246. PI: "PageInvisible",
  247. K: "Keystroke",
  248. F: "Format",
  249. V: "Validate",
  250. C: "Calculate"
  251. };
  252. exports.AnnotationActionEventType = AnnotationActionEventType;
  253. const DocumentActionEventType = {
  254. WC: "WillClose",
  255. WS: "WillSave",
  256. DS: "DidSave",
  257. WP: "WillPrint",
  258. DP: "DidPrint"
  259. };
  260. exports.DocumentActionEventType = DocumentActionEventType;
  261. const PageActionEventType = {
  262. O: "PageOpen",
  263. C: "PageClose"
  264. };
  265. exports.PageActionEventType = PageActionEventType;
  266. const StreamType = {
  267. UNKNOWN: "UNKNOWN",
  268. FLATE: "FLATE",
  269. LZW: "LZW",
  270. DCT: "DCT",
  271. JPX: "JPX",
  272. JBIG: "JBIG",
  273. A85: "A85",
  274. AHX: "AHX",
  275. CCF: "CCF",
  276. RLX: "RLX"
  277. };
  278. exports.StreamType = StreamType;
  279. const FontType = {
  280. UNKNOWN: "UNKNOWN",
  281. TYPE1: "TYPE1",
  282. TYPE1STANDARD: "TYPE1STANDARD",
  283. TYPE1C: "TYPE1C",
  284. CIDFONTTYPE0: "CIDFONTTYPE0",
  285. CIDFONTTYPE0C: "CIDFONTTYPE0C",
  286. TRUETYPE: "TRUETYPE",
  287. CIDFONTTYPE2: "CIDFONTTYPE2",
  288. TYPE3: "TYPE3",
  289. OPENTYPE: "OPENTYPE",
  290. TYPE0: "TYPE0",
  291. MMTYPE1: "MMTYPE1"
  292. };
  293. exports.FontType = FontType;
  294. const VerbosityLevel = {
  295. ERRORS: 0,
  296. WARNINGS: 1,
  297. INFOS: 5
  298. };
  299. exports.VerbosityLevel = VerbosityLevel;
  300. const CMapCompressionType = {
  301. NONE: 0,
  302. BINARY: 1
  303. };
  304. exports.CMapCompressionType = CMapCompressionType;
  305. const OPS = {
  306. dependency: 1,
  307. setLineWidth: 2,
  308. setLineCap: 3,
  309. setLineJoin: 4,
  310. setMiterLimit: 5,
  311. setDash: 6,
  312. setRenderingIntent: 7,
  313. setFlatness: 8,
  314. setGState: 9,
  315. save: 10,
  316. restore: 11,
  317. transform: 12,
  318. moveTo: 13,
  319. lineTo: 14,
  320. curveTo: 15,
  321. curveTo2: 16,
  322. curveTo3: 17,
  323. closePath: 18,
  324. rectangle: 19,
  325. stroke: 20,
  326. closeStroke: 21,
  327. fill: 22,
  328. eoFill: 23,
  329. fillStroke: 24,
  330. eoFillStroke: 25,
  331. closeFillStroke: 26,
  332. closeEOFillStroke: 27,
  333. endPath: 28,
  334. clip: 29,
  335. eoClip: 30,
  336. beginText: 31,
  337. endText: 32,
  338. setCharSpacing: 33,
  339. setWordSpacing: 34,
  340. setHScale: 35,
  341. setLeading: 36,
  342. setFont: 37,
  343. setTextRenderingMode: 38,
  344. setTextRise: 39,
  345. moveText: 40,
  346. setLeadingMoveText: 41,
  347. setTextMatrix: 42,
  348. nextLine: 43,
  349. showText: 44,
  350. showSpacedText: 45,
  351. nextLineShowText: 46,
  352. nextLineSetSpacingShowText: 47,
  353. setCharWidth: 48,
  354. setCharWidthAndBounds: 49,
  355. setStrokeColorSpace: 50,
  356. setFillColorSpace: 51,
  357. setStrokeColor: 52,
  358. setStrokeColorN: 53,
  359. setFillColor: 54,
  360. setFillColorN: 55,
  361. setStrokeGray: 56,
  362. setFillGray: 57,
  363. setStrokeRGBColor: 58,
  364. setFillRGBColor: 59,
  365. setStrokeCMYKColor: 60,
  366. setFillCMYKColor: 61,
  367. shadingFill: 62,
  368. beginInlineImage: 63,
  369. beginImageData: 64,
  370. endInlineImage: 65,
  371. paintXObject: 66,
  372. markPoint: 67,
  373. markPointProps: 68,
  374. beginMarkedContent: 69,
  375. beginMarkedContentProps: 70,
  376. endMarkedContent: 71,
  377. beginCompat: 72,
  378. endCompat: 73,
  379. paintFormXObjectBegin: 74,
  380. paintFormXObjectEnd: 75,
  381. beginGroup: 76,
  382. endGroup: 77,
  383. beginAnnotation: 80,
  384. endAnnotation: 81,
  385. paintImageMaskXObject: 83,
  386. paintImageMaskXObjectGroup: 84,
  387. paintImageXObject: 85,
  388. paintInlineImageXObject: 86,
  389. paintInlineImageXObjectGroup: 87,
  390. paintImageXObjectRepeat: 88,
  391. paintImageMaskXObjectRepeat: 89,
  392. paintSolidColorImageMask: 90,
  393. constructPath: 91
  394. };
  395. exports.OPS = OPS;
  396. const UNSUPPORTED_FEATURES = {
  397. forms: "forms",
  398. javaScript: "javaScript",
  399. signatures: "signatures",
  400. smask: "smask",
  401. shadingPattern: "shadingPattern",
  402. errorTilingPattern: "errorTilingPattern",
  403. errorExtGState: "errorExtGState",
  404. errorXObject: "errorXObject",
  405. errorFontLoadType3: "errorFontLoadType3",
  406. errorFontState: "errorFontState",
  407. errorFontMissing: "errorFontMissing",
  408. errorFontTranslate: "errorFontTranslate",
  409. errorColorSpace: "errorColorSpace",
  410. errorOperatorList: "errorOperatorList",
  411. errorFontToUnicode: "errorFontToUnicode",
  412. errorFontLoadNative: "errorFontLoadNative",
  413. errorFontBuildPath: "errorFontBuildPath",
  414. errorFontGetPath: "errorFontGetPath",
  415. errorMarkedContent: "errorMarkedContent",
  416. errorContentSubStream: "errorContentSubStream"
  417. };
  418. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  419. const PasswordResponses = {
  420. NEED_PASSWORD: 1,
  421. INCORRECT_PASSWORD: 2
  422. };
  423. exports.PasswordResponses = PasswordResponses;
  424. let verbosity = VerbosityLevel.WARNINGS;
  425. function setVerbosityLevel(level) {
  426. if (Number.isInteger(level)) {
  427. verbosity = level;
  428. }
  429. }
  430. function getVerbosityLevel() {
  431. return verbosity;
  432. }
  433. function info(msg) {
  434. if (verbosity >= VerbosityLevel.INFOS) {
  435. console.log(`Info: ${msg}`);
  436. }
  437. }
  438. function warn(msg) {
  439. if (verbosity >= VerbosityLevel.WARNINGS) {
  440. console.log(`Warning: ${msg}`);
  441. }
  442. }
  443. function unreachable(msg) {
  444. throw new Error(msg);
  445. }
  446. function assert(cond, msg) {
  447. if (!cond) {
  448. unreachable(msg);
  449. }
  450. }
  451. function _isValidProtocol(url) {
  452. if (!url) {
  453. return false;
  454. }
  455. switch (url.protocol) {
  456. case "http:":
  457. case "https:":
  458. case "ftp:":
  459. case "mailto:":
  460. case "tel:":
  461. return true;
  462. default:
  463. return false;
  464. }
  465. }
  466. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  467. if (!url) {
  468. return null;
  469. }
  470. try {
  471. if (options && typeof url === "string") {
  472. if (options.addDefaultProtocol && url.startsWith("www.")) {
  473. const dots = url.match(/\./g);
  474. if (dots && dots.length >= 2) {
  475. url = `http://${url}`;
  476. }
  477. }
  478. if (options.tryConvertEncoding) {
  479. try {
  480. url = stringToUTF8String(url);
  481. } catch (ex) {}
  482. }
  483. }
  484. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  485. if (_isValidProtocol(absoluteUrl)) {
  486. return absoluteUrl;
  487. }
  488. } catch (ex) {}
  489. return null;
  490. }
  491. function shadow(obj, prop, value) {
  492. Object.defineProperty(obj, prop, {
  493. value,
  494. enumerable: true,
  495. configurable: true,
  496. writable: false
  497. });
  498. return value;
  499. }
  500. const BaseException = function BaseExceptionClosure() {
  501. function BaseException(message, name) {
  502. if (this.constructor === BaseException) {
  503. unreachable("Cannot initialize BaseException.");
  504. }
  505. this.message = message;
  506. this.name = name;
  507. }
  508. BaseException.prototype = new Error();
  509. BaseException.constructor = BaseException;
  510. return BaseException;
  511. }();
  512. exports.BaseException = BaseException;
  513. class PasswordException extends BaseException {
  514. constructor(msg, code) {
  515. super(msg, "PasswordException");
  516. this.code = code;
  517. }
  518. }
  519. exports.PasswordException = PasswordException;
  520. class UnknownErrorException extends BaseException {
  521. constructor(msg, details) {
  522. super(msg, "UnknownErrorException");
  523. this.details = details;
  524. }
  525. }
  526. exports.UnknownErrorException = UnknownErrorException;
  527. class InvalidPDFException extends BaseException {
  528. constructor(msg) {
  529. super(msg, "InvalidPDFException");
  530. }
  531. }
  532. exports.InvalidPDFException = InvalidPDFException;
  533. class MissingPDFException extends BaseException {
  534. constructor(msg) {
  535. super(msg, "MissingPDFException");
  536. }
  537. }
  538. exports.MissingPDFException = MissingPDFException;
  539. class UnexpectedResponseException extends BaseException {
  540. constructor(msg, status) {
  541. super(msg, "UnexpectedResponseException");
  542. this.status = status;
  543. }
  544. }
  545. exports.UnexpectedResponseException = UnexpectedResponseException;
  546. class FormatError extends BaseException {
  547. constructor(msg) {
  548. super(msg, "FormatError");
  549. }
  550. }
  551. exports.FormatError = FormatError;
  552. class AbortException extends BaseException {
  553. constructor(msg) {
  554. super(msg, "AbortException");
  555. }
  556. }
  557. exports.AbortException = AbortException;
  558. function bytesToString(bytes) {
  559. if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
  560. unreachable("Invalid argument for bytesToString");
  561. }
  562. const length = bytes.length;
  563. const MAX_ARGUMENT_COUNT = 8192;
  564. if (length < MAX_ARGUMENT_COUNT) {
  565. return String.fromCharCode.apply(null, bytes);
  566. }
  567. const strBuf = [];
  568. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  569. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  570. const chunk = bytes.subarray(i, chunkEnd);
  571. strBuf.push(String.fromCharCode.apply(null, chunk));
  572. }
  573. return strBuf.join("");
  574. }
  575. function stringToBytes(str) {
  576. if (typeof str !== "string") {
  577. unreachable("Invalid argument for stringToBytes");
  578. }
  579. const length = str.length;
  580. const bytes = new Uint8Array(length);
  581. for (let i = 0; i < length; ++i) {
  582. bytes[i] = str.charCodeAt(i) & 0xff;
  583. }
  584. return bytes;
  585. }
  586. function arrayByteLength(arr) {
  587. if (arr.length !== undefined) {
  588. return arr.length;
  589. }
  590. if (arr.byteLength !== undefined) {
  591. return arr.byteLength;
  592. }
  593. unreachable("Invalid argument for arrayByteLength");
  594. }
  595. function arraysToBytes(arr) {
  596. const length = arr.length;
  597. if (length === 1 && arr[0] instanceof Uint8Array) {
  598. return arr[0];
  599. }
  600. let resultLength = 0;
  601. for (let i = 0; i < length; i++) {
  602. resultLength += arrayByteLength(arr[i]);
  603. }
  604. let pos = 0;
  605. const data = new Uint8Array(resultLength);
  606. for (let i = 0; i < length; i++) {
  607. let item = arr[i];
  608. if (!(item instanceof Uint8Array)) {
  609. if (typeof item === "string") {
  610. item = stringToBytes(item);
  611. } else {
  612. item = new Uint8Array(item);
  613. }
  614. }
  615. const itemLength = item.byteLength;
  616. data.set(item, pos);
  617. pos += itemLength;
  618. }
  619. return data;
  620. }
  621. function string32(value) {
  622. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  623. }
  624. function objectSize(obj) {
  625. return Object.keys(obj).length;
  626. }
  627. function objectFromMap(map) {
  628. const obj = Object.create(null);
  629. for (const [key, value] of map) {
  630. obj[key] = value;
  631. }
  632. return obj;
  633. }
  634. function isLittleEndian() {
  635. const buffer8 = new Uint8Array(4);
  636. buffer8[0] = 1;
  637. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  638. return view32[0] === 1;
  639. }
  640. function isEvalSupported() {
  641. try {
  642. new Function("");
  643. return true;
  644. } catch (e) {
  645. return false;
  646. }
  647. }
  648. class FeatureTest {
  649. static get isLittleEndian() {
  650. return shadow(this, "isLittleEndian", isLittleEndian());
  651. }
  652. static get isEvalSupported() {
  653. return shadow(this, "isEvalSupported", isEvalSupported());
  654. }
  655. static get isOffscreenCanvasSupported() {
  656. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  657. }
  658. }
  659. exports.FeatureTest = FeatureTest;
  660. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  661. class Util {
  662. static makeHexColor(r, g, b) {
  663. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  664. }
  665. static scaleMinMax(transform, minMax) {
  666. let temp;
  667. if (transform[0]) {
  668. if (transform[0] < 0) {
  669. temp = minMax[0];
  670. minMax[0] = minMax[1];
  671. minMax[1] = temp;
  672. }
  673. minMax[0] *= transform[0];
  674. minMax[1] *= transform[0];
  675. if (transform[3] < 0) {
  676. temp = minMax[2];
  677. minMax[2] = minMax[3];
  678. minMax[3] = temp;
  679. }
  680. minMax[2] *= transform[3];
  681. minMax[3] *= transform[3];
  682. } else {
  683. temp = minMax[0];
  684. minMax[0] = minMax[2];
  685. minMax[2] = temp;
  686. temp = minMax[1];
  687. minMax[1] = minMax[3];
  688. minMax[3] = temp;
  689. if (transform[1] < 0) {
  690. temp = minMax[2];
  691. minMax[2] = minMax[3];
  692. minMax[3] = temp;
  693. }
  694. minMax[2] *= transform[1];
  695. minMax[3] *= transform[1];
  696. if (transform[2] < 0) {
  697. temp = minMax[0];
  698. minMax[0] = minMax[1];
  699. minMax[1] = temp;
  700. }
  701. minMax[0] *= transform[2];
  702. minMax[1] *= transform[2];
  703. }
  704. minMax[0] += transform[4];
  705. minMax[1] += transform[4];
  706. minMax[2] += transform[5];
  707. minMax[3] += transform[5];
  708. }
  709. static transform(m1, m2) {
  710. 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]];
  711. }
  712. static applyTransform(p, m) {
  713. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  714. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  715. return [xt, yt];
  716. }
  717. static applyInverseTransform(p, m) {
  718. const d = m[0] * m[3] - m[1] * m[2];
  719. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  720. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  721. return [xt, yt];
  722. }
  723. static getAxialAlignedBoundingBox(r, m) {
  724. const p1 = Util.applyTransform(r, m);
  725. const p2 = Util.applyTransform(r.slice(2, 4), m);
  726. const p3 = Util.applyTransform([r[0], r[3]], m);
  727. const p4 = Util.applyTransform([r[2], r[1]], m);
  728. 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])];
  729. }
  730. static inverseTransform(m) {
  731. const d = m[0] * m[3] - m[1] * m[2];
  732. 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];
  733. }
  734. static singularValueDecompose2dScale(m) {
  735. const transpose = [m[0], m[2], m[1], m[3]];
  736. const a = m[0] * transpose[0] + m[1] * transpose[2];
  737. const b = m[0] * transpose[1] + m[1] * transpose[3];
  738. const c = m[2] * transpose[0] + m[3] * transpose[2];
  739. const d = m[2] * transpose[1] + m[3] * transpose[3];
  740. const first = (a + d) / 2;
  741. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  742. const sx = first + second || 1;
  743. const sy = first - second || 1;
  744. return [Math.sqrt(sx), Math.sqrt(sy)];
  745. }
  746. static normalizeRect(rect) {
  747. const r = rect.slice(0);
  748. if (rect[0] > rect[2]) {
  749. r[0] = rect[2];
  750. r[2] = rect[0];
  751. }
  752. if (rect[1] > rect[3]) {
  753. r[1] = rect[3];
  754. r[3] = rect[1];
  755. }
  756. return r;
  757. }
  758. static intersect(rect1, rect2) {
  759. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  760. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  761. if (xLow > xHigh) {
  762. return null;
  763. }
  764. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  765. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  766. if (yLow > yHigh) {
  767. return null;
  768. }
  769. return [xLow, yLow, xHigh, yHigh];
  770. }
  771. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  772. const tvalues = [],
  773. bounds = [[], []];
  774. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  775. for (let i = 0; i < 2; ++i) {
  776. if (i === 0) {
  777. b = 6 * x0 - 12 * x1 + 6 * x2;
  778. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  779. c = 3 * x1 - 3 * x0;
  780. } else {
  781. b = 6 * y0 - 12 * y1 + 6 * y2;
  782. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  783. c = 3 * y1 - 3 * y0;
  784. }
  785. if (Math.abs(a) < 1e-12) {
  786. if (Math.abs(b) < 1e-12) {
  787. continue;
  788. }
  789. t = -c / b;
  790. if (0 < t && t < 1) {
  791. tvalues.push(t);
  792. }
  793. continue;
  794. }
  795. b2ac = b * b - 4 * c * a;
  796. sqrtb2ac = Math.sqrt(b2ac);
  797. if (b2ac < 0) {
  798. continue;
  799. }
  800. t1 = (-b + sqrtb2ac) / (2 * a);
  801. if (0 < t1 && t1 < 1) {
  802. tvalues.push(t1);
  803. }
  804. t2 = (-b - sqrtb2ac) / (2 * a);
  805. if (0 < t2 && t2 < 1) {
  806. tvalues.push(t2);
  807. }
  808. }
  809. let j = tvalues.length,
  810. mt;
  811. const jlen = j;
  812. while (j--) {
  813. t = tvalues[j];
  814. mt = 1 - t;
  815. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  816. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  817. }
  818. bounds[0][jlen] = x0;
  819. bounds[1][jlen] = y0;
  820. bounds[0][jlen + 1] = x3;
  821. bounds[1][jlen + 1] = y3;
  822. bounds[0].length = bounds[1].length = jlen + 2;
  823. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  824. }
  825. }
  826. exports.Util = Util;
  827. 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];
  828. function stringToPDFString(str) {
  829. if (str[0] >= "\xEF") {
  830. let encoding;
  831. if (str[0] === "\xFE" && str[1] === "\xFF") {
  832. encoding = "utf-16be";
  833. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  834. encoding = "utf-16le";
  835. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  836. encoding = "utf-8";
  837. }
  838. if (encoding) {
  839. try {
  840. const decoder = new TextDecoder(encoding, {
  841. fatal: true
  842. });
  843. const buffer = stringToBytes(str);
  844. return decoder.decode(buffer);
  845. } catch (ex) {
  846. warn(`stringToPDFString: "${ex}".`);
  847. }
  848. }
  849. }
  850. const strBuf = [];
  851. for (let i = 0, ii = str.length; i < ii; i++) {
  852. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  853. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  854. }
  855. return strBuf.join("");
  856. }
  857. function escapeString(str) {
  858. return str.replace(/([()\\\n\r])/g, match => {
  859. if (match === "\n") {
  860. return "\\n";
  861. } else if (match === "\r") {
  862. return "\\r";
  863. }
  864. return `\\${match}`;
  865. });
  866. }
  867. function isAscii(str) {
  868. return /^[\x00-\x7F]*$/.test(str);
  869. }
  870. function stringToUTF16BEString(str) {
  871. const buf = ["\xFE\xFF"];
  872. for (let i = 0, ii = str.length; i < ii; i++) {
  873. const char = str.charCodeAt(i);
  874. buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  875. }
  876. return buf.join("");
  877. }
  878. function stringToUTF8String(str) {
  879. return decodeURIComponent(escape(str));
  880. }
  881. function utf8StringToString(str) {
  882. return unescape(encodeURIComponent(str));
  883. }
  884. function isArrayBuffer(v) {
  885. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  886. }
  887. function isArrayEqual(arr1, arr2) {
  888. if (arr1.length !== arr2.length) {
  889. return false;
  890. }
  891. for (let i = 0, ii = arr1.length; i < ii; i++) {
  892. if (arr1[i] !== arr2[i]) {
  893. return false;
  894. }
  895. }
  896. return true;
  897. }
  898. function getModificationDate(date = new Date()) {
  899. 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")];
  900. return buffer.join("");
  901. }
  902. function createPromiseCapability() {
  903. const capability = Object.create(null);
  904. let isSettled = false;
  905. Object.defineProperty(capability, "settled", {
  906. get() {
  907. return isSettled;
  908. }
  909. });
  910. capability.promise = new Promise(function (resolve, reject) {
  911. capability.resolve = function (data) {
  912. isSettled = true;
  913. resolve(data);
  914. };
  915. capability.reject = function (reason) {
  916. isSettled = true;
  917. reject(reason);
  918. };
  919. });
  920. return capability;
  921. }
  922. /***/ }),
  923. /* 2 */
  924. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  925. Object.defineProperty(exports, "__esModule", ({
  926. value: true
  927. }));
  928. exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
  929. exports.getDocument = getDocument;
  930. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  931. exports.version = void 0;
  932. var _util = __w_pdfjs_require__(1);
  933. var _annotation_storage = __w_pdfjs_require__(3);
  934. var _display_utils = __w_pdfjs_require__(6);
  935. var _font_loader = __w_pdfjs_require__(9);
  936. var _canvas = __w_pdfjs_require__(10);
  937. var _worker_options = __w_pdfjs_require__(14);
  938. var _is_node = __w_pdfjs_require__(12);
  939. var _message_handler = __w_pdfjs_require__(15);
  940. var _metadata = __w_pdfjs_require__(16);
  941. var _optional_content_config = __w_pdfjs_require__(17);
  942. var _transport_stream = __w_pdfjs_require__(18);
  943. var _xfa_text = __w_pdfjs_require__(19);
  944. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  945. const RENDERING_CANCELLED_TIMEOUT = 100;
  946. let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
  947. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  948. let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
  949. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  950. let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
  951. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  952. if (_is_node.isNodeJS) {
  953. const {
  954. NodeCanvasFactory,
  955. NodeCMapReaderFactory,
  956. NodeStandardFontDataFactory
  957. } = __w_pdfjs_require__(20);
  958. exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  959. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  960. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
  961. }
  962. let createPDFNetworkStream;
  963. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  964. createPDFNetworkStream = pdfNetworkStreamFactory;
  965. }
  966. function getDocument(src) {
  967. const task = new PDFDocumentLoadingTask();
  968. let source;
  969. if (typeof src === "string" || src instanceof URL) {
  970. source = {
  971. url: src
  972. };
  973. } else if ((0, _util.isArrayBuffer)(src)) {
  974. source = {
  975. data: src
  976. };
  977. } else if (src instanceof PDFDataRangeTransport) {
  978. source = {
  979. range: src
  980. };
  981. } else {
  982. if (typeof src !== "object") {
  983. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
  984. }
  985. if (!src.url && !src.data && !src.range) {
  986. throw new Error("Invalid parameter object: need either .data, .range or .url");
  987. }
  988. source = src;
  989. }
  990. const params = Object.create(null);
  991. let rangeTransport = null,
  992. worker = null;
  993. for (const key in source) {
  994. const value = source[key];
  995. switch (key) {
  996. case "url":
  997. if (typeof window !== "undefined") {
  998. try {
  999. params[key] = new URL(value, window.location).href;
  1000. continue;
  1001. } catch (ex) {
  1002. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  1003. }
  1004. } else if (typeof value === "string" || value instanceof URL) {
  1005. params[key] = value.toString();
  1006. continue;
  1007. }
  1008. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1009. case "range":
  1010. rangeTransport = value;
  1011. continue;
  1012. case "worker":
  1013. worker = value;
  1014. continue;
  1015. case "data":
  1016. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1017. params[key] = new Uint8Array(value);
  1018. } else if (value instanceof Uint8Array) {
  1019. break;
  1020. } else if (typeof value === "string") {
  1021. params[key] = (0, _util.stringToBytes)(value);
  1022. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1023. params[key] = new Uint8Array(value);
  1024. } else if ((0, _util.isArrayBuffer)(value)) {
  1025. params[key] = new Uint8Array(value);
  1026. } else {
  1027. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  1028. }
  1029. continue;
  1030. }
  1031. params[key] = value;
  1032. }
  1033. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1034. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1035. params.ignoreErrors = params.stopAtErrors !== true;
  1036. params.fontExtraProperties = params.fontExtraProperties === true;
  1037. params.pdfBug = params.pdfBug === true;
  1038. params.enableXfa = params.enableXfa === true;
  1039. if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
  1040. params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
  1041. }
  1042. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1043. params.docBaseUrl = null;
  1044. }
  1045. if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
  1046. params.maxImageSize = -1;
  1047. }
  1048. if (typeof params.cMapUrl !== "string") {
  1049. params.cMapUrl = null;
  1050. }
  1051. if (typeof params.standardFontDataUrl !== "string") {
  1052. params.standardFontDataUrl = null;
  1053. }
  1054. if (typeof params.useWorkerFetch !== "boolean") {
  1055. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1056. }
  1057. if (typeof params.isEvalSupported !== "boolean") {
  1058. params.isEvalSupported = true;
  1059. }
  1060. if (typeof params.isOffscreenCanvasSupported !== "boolean") {
  1061. params.isOffscreenCanvasSupported = !_is_node.isNodeJS;
  1062. }
  1063. if (typeof params.disableFontFace !== "boolean") {
  1064. params.disableFontFace = _is_node.isNodeJS;
  1065. }
  1066. if (typeof params.useSystemFonts !== "boolean") {
  1067. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1068. }
  1069. if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
  1070. params.ownerDocument = globalThis.document;
  1071. }
  1072. if (typeof params.disableRange !== "boolean") {
  1073. params.disableRange = false;
  1074. }
  1075. if (typeof params.disableStream !== "boolean") {
  1076. params.disableStream = false;
  1077. }
  1078. if (typeof params.disableAutoFetch !== "boolean") {
  1079. params.disableAutoFetch = false;
  1080. }
  1081. (0, _util.setVerbosityLevel)(params.verbosity);
  1082. if (!worker) {
  1083. const workerParams = {
  1084. verbosity: params.verbosity,
  1085. port: _worker_options.GlobalWorkerOptions.workerPort
  1086. };
  1087. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1088. task._worker = worker;
  1089. }
  1090. const docId = task.docId;
  1091. worker.promise.then(function () {
  1092. if (task.destroyed) {
  1093. throw new Error("Loading aborted");
  1094. }
  1095. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1096. const networkStreamPromise = new Promise(function (resolve) {
  1097. let networkStream;
  1098. if (rangeTransport) {
  1099. networkStream = new _transport_stream.PDFDataTransportStream({
  1100. length: params.length,
  1101. initialData: params.initialData,
  1102. progressiveDone: params.progressiveDone,
  1103. contentDispositionFilename: params.contentDispositionFilename,
  1104. disableRange: params.disableRange,
  1105. disableStream: params.disableStream
  1106. }, rangeTransport);
  1107. } else if (!params.data) {
  1108. networkStream = createPDFNetworkStream({
  1109. url: params.url,
  1110. length: params.length,
  1111. httpHeaders: params.httpHeaders,
  1112. withCredentials: params.withCredentials,
  1113. rangeChunkSize: params.rangeChunkSize,
  1114. disableRange: params.disableRange,
  1115. disableStream: params.disableStream
  1116. });
  1117. }
  1118. resolve(networkStream);
  1119. });
  1120. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1121. if (task.destroyed) {
  1122. throw new Error("Loading aborted");
  1123. }
  1124. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1125. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1126. task._transport = transport;
  1127. messageHandler.send("Ready", null);
  1128. });
  1129. }).catch(task._capability.reject);
  1130. return task;
  1131. }
  1132. async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1133. if (worker.destroyed) {
  1134. throw new Error("Worker was destroyed");
  1135. }
  1136. if (pdfDataRangeTransport) {
  1137. source.length = pdfDataRangeTransport.length;
  1138. source.initialData = pdfDataRangeTransport.initialData;
  1139. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1140. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1141. }
  1142. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
  1143. docId,
  1144. apiVersion: '3.0.279',
  1145. data: source.data,
  1146. password: source.password,
  1147. disableAutoFetch: source.disableAutoFetch,
  1148. rangeChunkSize: source.rangeChunkSize,
  1149. length: source.length,
  1150. docBaseUrl: source.docBaseUrl,
  1151. enableXfa: source.enableXfa,
  1152. evaluatorOptions: {
  1153. maxImageSize: source.maxImageSize,
  1154. disableFontFace: source.disableFontFace,
  1155. ignoreErrors: source.ignoreErrors,
  1156. isEvalSupported: source.isEvalSupported,
  1157. isOffscreenCanvasSupported: source.isOffscreenCanvasSupported,
  1158. fontExtraProperties: source.fontExtraProperties,
  1159. useSystemFonts: source.useSystemFonts,
  1160. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1161. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1162. }
  1163. });
  1164. if (source.data) {
  1165. source.data = null;
  1166. }
  1167. if (worker.destroyed) {
  1168. throw new Error("Worker was destroyed");
  1169. }
  1170. return workerId;
  1171. }
  1172. class PDFDocumentLoadingTask {
  1173. static #docId = 0;
  1174. constructor() {
  1175. this._capability = (0, _util.createPromiseCapability)();
  1176. this._transport = null;
  1177. this._worker = null;
  1178. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1179. this.destroyed = false;
  1180. this.onPassword = null;
  1181. this.onProgress = null;
  1182. this.onUnsupportedFeature = null;
  1183. }
  1184. get promise() {
  1185. return this._capability.promise;
  1186. }
  1187. async destroy() {
  1188. this.destroyed = true;
  1189. await this._transport?.destroy();
  1190. this._transport = null;
  1191. if (this._worker) {
  1192. this._worker.destroy();
  1193. this._worker = null;
  1194. }
  1195. }
  1196. }
  1197. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1198. class PDFDataRangeTransport {
  1199. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1200. this.length = length;
  1201. this.initialData = initialData;
  1202. this.progressiveDone = progressiveDone;
  1203. this.contentDispositionFilename = contentDispositionFilename;
  1204. this._rangeListeners = [];
  1205. this._progressListeners = [];
  1206. this._progressiveReadListeners = [];
  1207. this._progressiveDoneListeners = [];
  1208. this._readyCapability = (0, _util.createPromiseCapability)();
  1209. }
  1210. addRangeListener(listener) {
  1211. this._rangeListeners.push(listener);
  1212. }
  1213. addProgressListener(listener) {
  1214. this._progressListeners.push(listener);
  1215. }
  1216. addProgressiveReadListener(listener) {
  1217. this._progressiveReadListeners.push(listener);
  1218. }
  1219. addProgressiveDoneListener(listener) {
  1220. this._progressiveDoneListeners.push(listener);
  1221. }
  1222. onDataRange(begin, chunk) {
  1223. for (const listener of this._rangeListeners) {
  1224. listener(begin, chunk);
  1225. }
  1226. }
  1227. onDataProgress(loaded, total) {
  1228. this._readyCapability.promise.then(() => {
  1229. for (const listener of this._progressListeners) {
  1230. listener(loaded, total);
  1231. }
  1232. });
  1233. }
  1234. onDataProgressiveRead(chunk) {
  1235. this._readyCapability.promise.then(() => {
  1236. for (const listener of this._progressiveReadListeners) {
  1237. listener(chunk);
  1238. }
  1239. });
  1240. }
  1241. onDataProgressiveDone() {
  1242. this._readyCapability.promise.then(() => {
  1243. for (const listener of this._progressiveDoneListeners) {
  1244. listener();
  1245. }
  1246. });
  1247. }
  1248. transportReady() {
  1249. this._readyCapability.resolve();
  1250. }
  1251. requestDataRange(begin, end) {
  1252. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1253. }
  1254. abort() {}
  1255. }
  1256. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1257. class PDFDocumentProxy {
  1258. constructor(pdfInfo, transport) {
  1259. this._pdfInfo = pdfInfo;
  1260. this._transport = transport;
  1261. }
  1262. get annotationStorage() {
  1263. return this._transport.annotationStorage;
  1264. }
  1265. get numPages() {
  1266. return this._pdfInfo.numPages;
  1267. }
  1268. get fingerprints() {
  1269. return this._pdfInfo.fingerprints;
  1270. }
  1271. get stats() {
  1272. return this._transport.stats;
  1273. }
  1274. get isPureXfa() {
  1275. return !!this._transport._htmlForXfa;
  1276. }
  1277. get allXfaHtml() {
  1278. return this._transport._htmlForXfa;
  1279. }
  1280. getPage(pageNumber) {
  1281. return this._transport.getPage(pageNumber);
  1282. }
  1283. getPageIndex(ref) {
  1284. return this._transport.getPageIndex(ref);
  1285. }
  1286. getDestinations() {
  1287. return this._transport.getDestinations();
  1288. }
  1289. getDestination(id) {
  1290. return this._transport.getDestination(id);
  1291. }
  1292. getPageLabels() {
  1293. return this._transport.getPageLabels();
  1294. }
  1295. getPageLayout() {
  1296. return this._transport.getPageLayout();
  1297. }
  1298. getPageMode() {
  1299. return this._transport.getPageMode();
  1300. }
  1301. getViewerPreferences() {
  1302. return this._transport.getViewerPreferences();
  1303. }
  1304. getOpenAction() {
  1305. return this._transport.getOpenAction();
  1306. }
  1307. getAttachments() {
  1308. return this._transport.getAttachments();
  1309. }
  1310. getJavaScript() {
  1311. return this._transport.getJavaScript();
  1312. }
  1313. getJSActions() {
  1314. return this._transport.getDocJSActions();
  1315. }
  1316. getOutline() {
  1317. return this._transport.getOutline();
  1318. }
  1319. getOptionalContentConfig() {
  1320. return this._transport.getOptionalContentConfig();
  1321. }
  1322. getPermissions() {
  1323. return this._transport.getPermissions();
  1324. }
  1325. getMetadata() {
  1326. return this._transport.getMetadata();
  1327. }
  1328. getMarkInfo() {
  1329. return this._transport.getMarkInfo();
  1330. }
  1331. getData() {
  1332. return this._transport.getData();
  1333. }
  1334. saveDocument() {
  1335. return this._transport.saveDocument();
  1336. }
  1337. getDownloadInfo() {
  1338. return this._transport.downloadInfoCapability.promise;
  1339. }
  1340. cleanup(keepLoadedFonts = false) {
  1341. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1342. }
  1343. destroy() {
  1344. return this.loadingTask.destroy();
  1345. }
  1346. get loadingParams() {
  1347. return this._transport.loadingParams;
  1348. }
  1349. get loadingTask() {
  1350. return this._transport.loadingTask;
  1351. }
  1352. getFieldObjects() {
  1353. return this._transport.getFieldObjects();
  1354. }
  1355. hasJSActions() {
  1356. return this._transport.hasJSActions();
  1357. }
  1358. getCalculationOrderIds() {
  1359. return this._transport.getCalculationOrderIds();
  1360. }
  1361. }
  1362. exports.PDFDocumentProxy = PDFDocumentProxy;
  1363. class PDFPageProxy {
  1364. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1365. this._pageIndex = pageIndex;
  1366. this._pageInfo = pageInfo;
  1367. this._ownerDocument = ownerDocument;
  1368. this._transport = transport;
  1369. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1370. this._pdfBug = pdfBug;
  1371. this.commonObjs = transport.commonObjs;
  1372. this.objs = new PDFObjects();
  1373. this._bitmaps = new Set();
  1374. this.cleanupAfterRender = false;
  1375. this.pendingCleanup = false;
  1376. this._intentStates = new Map();
  1377. this._annotationPromises = new Map();
  1378. this.destroyed = false;
  1379. }
  1380. get pageNumber() {
  1381. return this._pageIndex + 1;
  1382. }
  1383. get rotate() {
  1384. return this._pageInfo.rotate;
  1385. }
  1386. get ref() {
  1387. return this._pageInfo.ref;
  1388. }
  1389. get userUnit() {
  1390. return this._pageInfo.userUnit;
  1391. }
  1392. get view() {
  1393. return this._pageInfo.view;
  1394. }
  1395. getViewport({
  1396. scale,
  1397. rotation = this.rotate,
  1398. offsetX = 0,
  1399. offsetY = 0,
  1400. dontFlip = false
  1401. } = {}) {
  1402. return new _display_utils.PageViewport({
  1403. viewBox: this.view,
  1404. scale,
  1405. rotation,
  1406. offsetX,
  1407. offsetY,
  1408. dontFlip
  1409. });
  1410. }
  1411. getAnnotations({
  1412. intent = "display"
  1413. } = {}) {
  1414. const intentArgs = this._transport.getRenderingIntent(intent);
  1415. let promise = this._annotationPromises.get(intentArgs.cacheKey);
  1416. if (!promise) {
  1417. promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1418. this._annotationPromises.set(intentArgs.cacheKey, promise);
  1419. }
  1420. return promise;
  1421. }
  1422. getJSActions() {
  1423. return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
  1424. }
  1425. async getXfa() {
  1426. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1427. }
  1428. render({
  1429. canvasContext,
  1430. viewport,
  1431. intent = "display",
  1432. annotationMode = _util.AnnotationMode.ENABLE,
  1433. transform = null,
  1434. canvasFactory = null,
  1435. background = null,
  1436. optionalContentConfigPromise = null,
  1437. annotationCanvasMap = null,
  1438. pageColors = null,
  1439. printAnnotationStorage = null
  1440. }) {
  1441. this._stats?.time("Overall");
  1442. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  1443. this.pendingCleanup = false;
  1444. if (!optionalContentConfigPromise) {
  1445. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1446. }
  1447. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1448. if (!intentState) {
  1449. intentState = Object.create(null);
  1450. this._intentStates.set(intentArgs.cacheKey, intentState);
  1451. }
  1452. if (intentState.streamReaderCancelTimeout) {
  1453. clearTimeout(intentState.streamReaderCancelTimeout);
  1454. intentState.streamReaderCancelTimeout = null;
  1455. }
  1456. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1457. ownerDocument: this._ownerDocument
  1458. });
  1459. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1460. if (!intentState.displayReadyCapability) {
  1461. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1462. intentState.operatorList = {
  1463. fnArray: [],
  1464. argsArray: [],
  1465. lastChunk: false,
  1466. separateAnnots: null
  1467. };
  1468. this._stats?.time("Page Request");
  1469. this._pumpOperatorList(intentArgs);
  1470. }
  1471. const complete = error => {
  1472. intentState.renderTasks.delete(internalRenderTask);
  1473. if (this.cleanupAfterRender || intentPrint) {
  1474. this.pendingCleanup = true;
  1475. }
  1476. this._tryCleanup();
  1477. if (error) {
  1478. internalRenderTask.capability.reject(error);
  1479. this._abortOperatorList({
  1480. intentState,
  1481. reason: error instanceof Error ? error : new Error(error)
  1482. });
  1483. } else {
  1484. internalRenderTask.capability.resolve();
  1485. }
  1486. this._stats?.timeEnd("Rendering");
  1487. this._stats?.timeEnd("Overall");
  1488. };
  1489. const internalRenderTask = new InternalRenderTask({
  1490. callback: complete,
  1491. params: {
  1492. canvasContext,
  1493. viewport,
  1494. transform,
  1495. background
  1496. },
  1497. objs: this.objs,
  1498. commonObjs: this.commonObjs,
  1499. annotationCanvasMap,
  1500. operatorList: intentState.operatorList,
  1501. pageIndex: this._pageIndex,
  1502. canvasFactory: canvasFactoryInstance,
  1503. useRequestAnimationFrame: !intentPrint,
  1504. pdfBug: this._pdfBug,
  1505. pageColors
  1506. });
  1507. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  1508. const renderTask = internalRenderTask.task;
  1509. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1510. if (this.pendingCleanup) {
  1511. complete();
  1512. return;
  1513. }
  1514. this._stats?.time("Rendering");
  1515. internalRenderTask.initializeGraphics({
  1516. transparency,
  1517. optionalContentConfig
  1518. });
  1519. internalRenderTask.operatorListChanged();
  1520. }).catch(complete);
  1521. return renderTask;
  1522. }
  1523. getOperatorList({
  1524. intent = "display",
  1525. annotationMode = _util.AnnotationMode.ENABLE,
  1526. printAnnotationStorage = null
  1527. } = {}) {
  1528. function operatorListChanged() {
  1529. if (intentState.operatorList.lastChunk) {
  1530. intentState.opListReadCapability.resolve(intentState.operatorList);
  1531. intentState.renderTasks.delete(opListTask);
  1532. }
  1533. }
  1534. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  1535. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1536. if (!intentState) {
  1537. intentState = Object.create(null);
  1538. this._intentStates.set(intentArgs.cacheKey, intentState);
  1539. }
  1540. let opListTask;
  1541. if (!intentState.opListReadCapability) {
  1542. opListTask = Object.create(null);
  1543. opListTask.operatorListChanged = operatorListChanged;
  1544. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1545. (intentState.renderTasks ||= new Set()).add(opListTask);
  1546. intentState.operatorList = {
  1547. fnArray: [],
  1548. argsArray: [],
  1549. lastChunk: false,
  1550. separateAnnots: null
  1551. };
  1552. this._stats?.time("Page Request");
  1553. this._pumpOperatorList(intentArgs);
  1554. }
  1555. return intentState.opListReadCapability.promise;
  1556. }
  1557. streamTextContent({
  1558. disableCombineTextItems = false,
  1559. includeMarkedContent = false
  1560. } = {}) {
  1561. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1562. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1563. pageIndex: this._pageIndex,
  1564. combineTextItems: disableCombineTextItems !== true,
  1565. includeMarkedContent: includeMarkedContent === true
  1566. }, {
  1567. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1568. size(textContent) {
  1569. return textContent.items.length;
  1570. }
  1571. });
  1572. }
  1573. getTextContent(params = {}) {
  1574. if (this._transport._htmlForXfa) {
  1575. return this.getXfa().then(xfa => {
  1576. return _xfa_text.XfaText.textContent(xfa);
  1577. });
  1578. }
  1579. const readableStream = this.streamTextContent(params);
  1580. return new Promise(function (resolve, reject) {
  1581. function pump() {
  1582. reader.read().then(function ({
  1583. value,
  1584. done
  1585. }) {
  1586. if (done) {
  1587. resolve(textContent);
  1588. return;
  1589. }
  1590. Object.assign(textContent.styles, value.styles);
  1591. textContent.items.push(...value.items);
  1592. pump();
  1593. }, reject);
  1594. }
  1595. const reader = readableStream.getReader();
  1596. const textContent = {
  1597. items: [],
  1598. styles: Object.create(null)
  1599. };
  1600. pump();
  1601. });
  1602. }
  1603. getStructTree() {
  1604. return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
  1605. }
  1606. _destroy() {
  1607. this.destroyed = true;
  1608. const waitOn = [];
  1609. for (const intentState of this._intentStates.values()) {
  1610. this._abortOperatorList({
  1611. intentState,
  1612. reason: new Error("Page was destroyed."),
  1613. force: true
  1614. });
  1615. if (intentState.opListReadCapability) {
  1616. continue;
  1617. }
  1618. for (const internalRenderTask of intentState.renderTasks) {
  1619. waitOn.push(internalRenderTask.completed);
  1620. internalRenderTask.cancel();
  1621. }
  1622. }
  1623. this.objs.clear();
  1624. for (const bitmap of this._bitmaps) {
  1625. bitmap.close();
  1626. }
  1627. this._bitmaps.clear();
  1628. this._annotationPromises.clear();
  1629. this._jsActionsPromise = null;
  1630. this._structTreePromise = null;
  1631. this.pendingCleanup = false;
  1632. return Promise.all(waitOn);
  1633. }
  1634. cleanup(resetStats = false) {
  1635. this.pendingCleanup = true;
  1636. return this._tryCleanup(resetStats);
  1637. }
  1638. _tryCleanup(resetStats = false) {
  1639. if (!this.pendingCleanup) {
  1640. return false;
  1641. }
  1642. for (const {
  1643. renderTasks,
  1644. operatorList
  1645. } of this._intentStates.values()) {
  1646. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  1647. return false;
  1648. }
  1649. }
  1650. this._intentStates.clear();
  1651. this.objs.clear();
  1652. this._annotationPromises.clear();
  1653. this._jsActionsPromise = null;
  1654. this._structTreePromise = null;
  1655. if (resetStats && this._stats) {
  1656. this._stats = new _display_utils.StatTimer();
  1657. }
  1658. for (const bitmap of this._bitmaps) {
  1659. bitmap.close();
  1660. }
  1661. this._bitmaps.clear();
  1662. this.pendingCleanup = false;
  1663. return true;
  1664. }
  1665. _startRenderPage(transparency, cacheKey) {
  1666. const intentState = this._intentStates.get(cacheKey);
  1667. if (!intentState) {
  1668. return;
  1669. }
  1670. this._stats?.timeEnd("Page Request");
  1671. intentState.displayReadyCapability?.resolve(transparency);
  1672. }
  1673. _renderPageChunk(operatorListChunk, intentState) {
  1674. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  1675. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  1676. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  1677. }
  1678. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  1679. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  1680. for (const internalRenderTask of intentState.renderTasks) {
  1681. internalRenderTask.operatorListChanged();
  1682. }
  1683. if (operatorListChunk.lastChunk) {
  1684. this._tryCleanup();
  1685. }
  1686. }
  1687. _pumpOperatorList({
  1688. renderingIntent,
  1689. cacheKey,
  1690. annotationStorageMap
  1691. }) {
  1692. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  1693. pageIndex: this._pageIndex,
  1694. intent: renderingIntent,
  1695. cacheKey,
  1696. annotationStorage: annotationStorageMap
  1697. });
  1698. const reader = readableStream.getReader();
  1699. const intentState = this._intentStates.get(cacheKey);
  1700. intentState.streamReader = reader;
  1701. const pump = () => {
  1702. reader.read().then(({
  1703. value,
  1704. done
  1705. }) => {
  1706. if (done) {
  1707. intentState.streamReader = null;
  1708. return;
  1709. }
  1710. if (this._transport.destroyed) {
  1711. return;
  1712. }
  1713. this._renderPageChunk(value, intentState);
  1714. pump();
  1715. }, reason => {
  1716. intentState.streamReader = null;
  1717. if (this._transport.destroyed) {
  1718. return;
  1719. }
  1720. if (intentState.operatorList) {
  1721. intentState.operatorList.lastChunk = true;
  1722. for (const internalRenderTask of intentState.renderTasks) {
  1723. internalRenderTask.operatorListChanged();
  1724. }
  1725. this._tryCleanup();
  1726. }
  1727. if (intentState.displayReadyCapability) {
  1728. intentState.displayReadyCapability.reject(reason);
  1729. } else if (intentState.opListReadCapability) {
  1730. intentState.opListReadCapability.reject(reason);
  1731. } else {
  1732. throw reason;
  1733. }
  1734. });
  1735. };
  1736. pump();
  1737. }
  1738. _abortOperatorList({
  1739. intentState,
  1740. reason,
  1741. force = false
  1742. }) {
  1743. if (!intentState.streamReader) {
  1744. return;
  1745. }
  1746. if (!force) {
  1747. if (intentState.renderTasks.size > 0) {
  1748. return;
  1749. }
  1750. if (reason instanceof _display_utils.RenderingCancelledException) {
  1751. intentState.streamReaderCancelTimeout = setTimeout(() => {
  1752. this._abortOperatorList({
  1753. intentState,
  1754. reason,
  1755. force: true
  1756. });
  1757. intentState.streamReaderCancelTimeout = null;
  1758. }, RENDERING_CANCELLED_TIMEOUT);
  1759. return;
  1760. }
  1761. }
  1762. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  1763. intentState.streamReader = null;
  1764. if (this._transport.destroyed) {
  1765. return;
  1766. }
  1767. for (const [curCacheKey, curIntentState] of this._intentStates) {
  1768. if (curIntentState === intentState) {
  1769. this._intentStates.delete(curCacheKey);
  1770. break;
  1771. }
  1772. }
  1773. this.cleanup();
  1774. }
  1775. get stats() {
  1776. return this._stats;
  1777. }
  1778. }
  1779. exports.PDFPageProxy = PDFPageProxy;
  1780. class LoopbackPort {
  1781. #listeners = [];
  1782. #deferred = Promise.resolve();
  1783. postMessage(obj, transfers) {
  1784. const event = {
  1785. data: structuredClone(obj, transfers)
  1786. };
  1787. this.#deferred.then(() => {
  1788. for (const listener of this.#listeners) {
  1789. listener.call(this, event);
  1790. }
  1791. });
  1792. }
  1793. addEventListener(name, listener) {
  1794. this.#listeners.push(listener);
  1795. }
  1796. removeEventListener(name, listener) {
  1797. const i = this.#listeners.indexOf(listener);
  1798. this.#listeners.splice(i, 1);
  1799. }
  1800. terminate() {
  1801. this.#listeners.length = 0;
  1802. }
  1803. }
  1804. exports.LoopbackPort = LoopbackPort;
  1805. const PDFWorkerUtil = {
  1806. isWorkerDisabled: false,
  1807. fallbackWorkerSrc: null,
  1808. fakeWorkerId: 0
  1809. };
  1810. exports.PDFWorkerUtil = PDFWorkerUtil;
  1811. {
  1812. if (_is_node.isNodeJS && typeof require === "function") {
  1813. PDFWorkerUtil.isWorkerDisabled = true;
  1814. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  1815. } else if (typeof document === "object") {
  1816. const pdfjsFilePath = document?.currentScript?.src;
  1817. if (pdfjsFilePath) {
  1818. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  1819. }
  1820. }
  1821. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  1822. let base;
  1823. try {
  1824. base = new URL(baseUrl);
  1825. if (!base.origin || base.origin === "null") {
  1826. return false;
  1827. }
  1828. } catch (e) {
  1829. return false;
  1830. }
  1831. const other = new URL(otherUrl, base);
  1832. return base.origin === other.origin;
  1833. };
  1834. PDFWorkerUtil.createCDNWrapper = function (url) {
  1835. const wrapper = `importScripts("${url}");`;
  1836. return URL.createObjectURL(new Blob([wrapper]));
  1837. };
  1838. }
  1839. class PDFWorker {
  1840. static #workerPorts = new WeakMap();
  1841. constructor({
  1842. name = null,
  1843. port = null,
  1844. verbosity = (0, _util.getVerbosityLevel)()
  1845. } = {}) {
  1846. if (port && PDFWorker.#workerPorts.has(port)) {
  1847. throw new Error("Cannot use more than one PDFWorker per port.");
  1848. }
  1849. this.name = name;
  1850. this.destroyed = false;
  1851. this.verbosity = verbosity;
  1852. this._readyCapability = (0, _util.createPromiseCapability)();
  1853. this._port = null;
  1854. this._webWorker = null;
  1855. this._messageHandler = null;
  1856. if (port) {
  1857. PDFWorker.#workerPorts.set(port, this);
  1858. this._initializeFromPort(port);
  1859. return;
  1860. }
  1861. this._initialize();
  1862. }
  1863. get promise() {
  1864. return this._readyCapability.promise;
  1865. }
  1866. get port() {
  1867. return this._port;
  1868. }
  1869. get messageHandler() {
  1870. return this._messageHandler;
  1871. }
  1872. _initializeFromPort(port) {
  1873. this._port = port;
  1874. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  1875. this._messageHandler.on("ready", function () {});
  1876. this._readyCapability.resolve();
  1877. this._messageHandler.send("configure", {
  1878. verbosity: this.verbosity
  1879. });
  1880. }
  1881. _initialize() {
  1882. if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  1883. let {
  1884. workerSrc
  1885. } = PDFWorker;
  1886. try {
  1887. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  1888. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  1889. }
  1890. const worker = new Worker(workerSrc);
  1891. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  1892. const terminateEarly = () => {
  1893. worker.removeEventListener("error", onWorkerError);
  1894. messageHandler.destroy();
  1895. worker.terminate();
  1896. if (this.destroyed) {
  1897. this._readyCapability.reject(new Error("Worker was destroyed"));
  1898. } else {
  1899. this._setupFakeWorker();
  1900. }
  1901. };
  1902. const onWorkerError = () => {
  1903. if (!this._webWorker) {
  1904. terminateEarly();
  1905. }
  1906. };
  1907. worker.addEventListener("error", onWorkerError);
  1908. messageHandler.on("test", data => {
  1909. worker.removeEventListener("error", onWorkerError);
  1910. if (this.destroyed) {
  1911. terminateEarly();
  1912. return;
  1913. }
  1914. if (data) {
  1915. this._messageHandler = messageHandler;
  1916. this._port = worker;
  1917. this._webWorker = worker;
  1918. this._readyCapability.resolve();
  1919. messageHandler.send("configure", {
  1920. verbosity: this.verbosity
  1921. });
  1922. } else {
  1923. this._setupFakeWorker();
  1924. messageHandler.destroy();
  1925. worker.terminate();
  1926. }
  1927. });
  1928. messageHandler.on("ready", data => {
  1929. worker.removeEventListener("error", onWorkerError);
  1930. if (this.destroyed) {
  1931. terminateEarly();
  1932. return;
  1933. }
  1934. try {
  1935. sendTest();
  1936. } catch (e) {
  1937. this._setupFakeWorker();
  1938. }
  1939. });
  1940. const sendTest = () => {
  1941. const testObj = new Uint8Array();
  1942. messageHandler.send("test", testObj, [testObj.buffer]);
  1943. };
  1944. sendTest();
  1945. return;
  1946. } catch (e) {
  1947. (0, _util.info)("The worker has been disabled.");
  1948. }
  1949. }
  1950. this._setupFakeWorker();
  1951. }
  1952. _setupFakeWorker() {
  1953. if (!PDFWorkerUtil.isWorkerDisabled) {
  1954. (0, _util.warn)("Setting up fake worker.");
  1955. PDFWorkerUtil.isWorkerDisabled = true;
  1956. }
  1957. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  1958. if (this.destroyed) {
  1959. this._readyCapability.reject(new Error("Worker was destroyed"));
  1960. return;
  1961. }
  1962. const port = new LoopbackPort();
  1963. this._port = port;
  1964. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  1965. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  1966. WorkerMessageHandler.setup(workerHandler, port);
  1967. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  1968. this._messageHandler = messageHandler;
  1969. this._readyCapability.resolve();
  1970. messageHandler.send("configure", {
  1971. verbosity: this.verbosity
  1972. });
  1973. }).catch(reason => {
  1974. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  1975. });
  1976. }
  1977. destroy() {
  1978. this.destroyed = true;
  1979. if (this._webWorker) {
  1980. this._webWorker.terminate();
  1981. this._webWorker = null;
  1982. }
  1983. PDFWorker.#workerPorts.delete(this._port);
  1984. this._port = null;
  1985. if (this._messageHandler) {
  1986. this._messageHandler.destroy();
  1987. this._messageHandler = null;
  1988. }
  1989. }
  1990. static fromPort(params) {
  1991. if (!params?.port) {
  1992. throw new Error("PDFWorker.fromPort - invalid method signature.");
  1993. }
  1994. if (this.#workerPorts.has(params.port)) {
  1995. return this.#workerPorts.get(params.port);
  1996. }
  1997. return new PDFWorker(params);
  1998. }
  1999. static get workerSrc() {
  2000. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  2001. return _worker_options.GlobalWorkerOptions.workerSrc;
  2002. }
  2003. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  2004. if (!_is_node.isNodeJS) {
  2005. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2006. }
  2007. return PDFWorkerUtil.fallbackWorkerSrc;
  2008. }
  2009. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2010. }
  2011. static get _mainThreadWorkerMessageHandler() {
  2012. try {
  2013. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  2014. } catch (ex) {
  2015. return null;
  2016. }
  2017. }
  2018. static get _setupFakeWorkerGlobal() {
  2019. const loader = async () => {
  2020. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  2021. if (mainWorkerMessageHandler) {
  2022. return mainWorkerMessageHandler;
  2023. }
  2024. if (_is_node.isNodeJS && typeof require === "function") {
  2025. const worker = eval("require")(this.workerSrc);
  2026. return worker.WorkerMessageHandler;
  2027. }
  2028. await (0, _display_utils.loadScript)(this.workerSrc);
  2029. return window.pdfjsWorker.WorkerMessageHandler;
  2030. };
  2031. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  2032. }
  2033. }
  2034. exports.PDFWorker = PDFWorker;
  2035. class WorkerTransport {
  2036. #docStats = null;
  2037. #pageCache = new Map();
  2038. #pagePromises = new Map();
  2039. #metadataPromise = null;
  2040. constructor(messageHandler, loadingTask, networkStream, params) {
  2041. this.messageHandler = messageHandler;
  2042. this.loadingTask = loadingTask;
  2043. this.commonObjs = new PDFObjects();
  2044. this.fontLoader = new _font_loader.FontLoader({
  2045. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2046. ownerDocument: params.ownerDocument,
  2047. styleElement: params.styleElement
  2048. });
  2049. this._params = params;
  2050. if (!params.useWorkerFetch) {
  2051. this.CMapReaderFactory = new params.CMapReaderFactory({
  2052. baseUrl: params.cMapUrl,
  2053. isCompressed: params.cMapPacked
  2054. });
  2055. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2056. baseUrl: params.standardFontDataUrl
  2057. });
  2058. }
  2059. this.destroyed = false;
  2060. this.destroyCapability = null;
  2061. this._passwordCapability = null;
  2062. this._networkStream = networkStream;
  2063. this._fullReader = null;
  2064. this._lastProgress = null;
  2065. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2066. this.setupMessageHandler();
  2067. }
  2068. get annotationStorage() {
  2069. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2070. }
  2071. get stats() {
  2072. return this.#docStats;
  2073. }
  2074. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  2075. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2076. let annotationMap = null;
  2077. switch (intent) {
  2078. case "any":
  2079. renderingIntent = _util.RenderingIntentFlag.ANY;
  2080. break;
  2081. case "display":
  2082. break;
  2083. case "print":
  2084. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2085. break;
  2086. default:
  2087. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2088. }
  2089. switch (annotationMode) {
  2090. case _util.AnnotationMode.DISABLE:
  2091. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2092. break;
  2093. case _util.AnnotationMode.ENABLE:
  2094. break;
  2095. case _util.AnnotationMode.ENABLE_FORMS:
  2096. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2097. break;
  2098. case _util.AnnotationMode.ENABLE_STORAGE:
  2099. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2100. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2101. annotationMap = annotationStorage.serializable;
  2102. break;
  2103. default:
  2104. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2105. }
  2106. if (isOpList) {
  2107. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2108. }
  2109. return {
  2110. renderingIntent,
  2111. cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
  2112. annotationStorageMap: annotationMap
  2113. };
  2114. }
  2115. destroy() {
  2116. if (this.destroyCapability) {
  2117. return this.destroyCapability.promise;
  2118. }
  2119. this.destroyed = true;
  2120. this.destroyCapability = (0, _util.createPromiseCapability)();
  2121. if (this._passwordCapability) {
  2122. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2123. }
  2124. const waitOn = [];
  2125. for (const page of this.#pageCache.values()) {
  2126. waitOn.push(page._destroy());
  2127. }
  2128. this.#pageCache.clear();
  2129. this.#pagePromises.clear();
  2130. if (this.hasOwnProperty("annotationStorage")) {
  2131. this.annotationStorage.resetModified();
  2132. }
  2133. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2134. waitOn.push(terminated);
  2135. Promise.all(waitOn).then(() => {
  2136. this.commonObjs.clear();
  2137. this.fontLoader.clear();
  2138. this.#metadataPromise = null;
  2139. this._getFieldObjectsPromise = null;
  2140. this._hasJSActionsPromise = null;
  2141. if (this._networkStream) {
  2142. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2143. }
  2144. if (this.messageHandler) {
  2145. this.messageHandler.destroy();
  2146. this.messageHandler = null;
  2147. }
  2148. this.destroyCapability.resolve();
  2149. }, this.destroyCapability.reject);
  2150. return this.destroyCapability.promise;
  2151. }
  2152. setupMessageHandler() {
  2153. const {
  2154. messageHandler,
  2155. loadingTask
  2156. } = this;
  2157. messageHandler.on("GetReader", (data, sink) => {
  2158. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2159. this._fullReader = this._networkStream.getFullReader();
  2160. this._fullReader.onProgress = evt => {
  2161. this._lastProgress = {
  2162. loaded: evt.loaded,
  2163. total: evt.total
  2164. };
  2165. };
  2166. sink.onPull = () => {
  2167. this._fullReader.read().then(function ({
  2168. value,
  2169. done
  2170. }) {
  2171. if (done) {
  2172. sink.close();
  2173. return;
  2174. }
  2175. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2176. sink.enqueue(new Uint8Array(value), 1, [value]);
  2177. }).catch(reason => {
  2178. sink.error(reason);
  2179. });
  2180. };
  2181. sink.onCancel = reason => {
  2182. this._fullReader.cancel(reason);
  2183. sink.ready.catch(readyReason => {
  2184. if (this.destroyed) {
  2185. return;
  2186. }
  2187. throw readyReason;
  2188. });
  2189. };
  2190. });
  2191. messageHandler.on("ReaderHeadersReady", data => {
  2192. const headersCapability = (0, _util.createPromiseCapability)();
  2193. const fullReader = this._fullReader;
  2194. fullReader.headersReady.then(() => {
  2195. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2196. if (this._lastProgress) {
  2197. loadingTask.onProgress?.(this._lastProgress);
  2198. }
  2199. fullReader.onProgress = evt => {
  2200. loadingTask.onProgress?.({
  2201. loaded: evt.loaded,
  2202. total: evt.total
  2203. });
  2204. };
  2205. }
  2206. headersCapability.resolve({
  2207. isStreamingSupported: fullReader.isStreamingSupported,
  2208. isRangeSupported: fullReader.isRangeSupported,
  2209. contentLength: fullReader.contentLength
  2210. });
  2211. }, headersCapability.reject);
  2212. return headersCapability.promise;
  2213. });
  2214. messageHandler.on("GetRangeReader", (data, sink) => {
  2215. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2216. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2217. if (!rangeReader) {
  2218. sink.close();
  2219. return;
  2220. }
  2221. sink.onPull = () => {
  2222. rangeReader.read().then(function ({
  2223. value,
  2224. done
  2225. }) {
  2226. if (done) {
  2227. sink.close();
  2228. return;
  2229. }
  2230. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2231. sink.enqueue(new Uint8Array(value), 1, [value]);
  2232. }).catch(reason => {
  2233. sink.error(reason);
  2234. });
  2235. };
  2236. sink.onCancel = reason => {
  2237. rangeReader.cancel(reason);
  2238. sink.ready.catch(readyReason => {
  2239. if (this.destroyed) {
  2240. return;
  2241. }
  2242. throw readyReason;
  2243. });
  2244. };
  2245. });
  2246. messageHandler.on("GetDoc", ({
  2247. pdfInfo
  2248. }) => {
  2249. this._numPages = pdfInfo.numPages;
  2250. this._htmlForXfa = pdfInfo.htmlForXfa;
  2251. delete pdfInfo.htmlForXfa;
  2252. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2253. });
  2254. messageHandler.on("DocException", function (ex) {
  2255. let reason;
  2256. switch (ex.name) {
  2257. case "PasswordException":
  2258. reason = new _util.PasswordException(ex.message, ex.code);
  2259. break;
  2260. case "InvalidPDFException":
  2261. reason = new _util.InvalidPDFException(ex.message);
  2262. break;
  2263. case "MissingPDFException":
  2264. reason = new _util.MissingPDFException(ex.message);
  2265. break;
  2266. case "UnexpectedResponseException":
  2267. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2268. break;
  2269. case "UnknownErrorException":
  2270. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2271. break;
  2272. default:
  2273. (0, _util.unreachable)("DocException - expected a valid Error.");
  2274. }
  2275. loadingTask._capability.reject(reason);
  2276. });
  2277. messageHandler.on("PasswordRequest", exception => {
  2278. this._passwordCapability = (0, _util.createPromiseCapability)();
  2279. if (loadingTask.onPassword) {
  2280. const updatePassword = password => {
  2281. if (password instanceof Error) {
  2282. this._passwordCapability.reject(password);
  2283. } else {
  2284. this._passwordCapability.resolve({
  2285. password
  2286. });
  2287. }
  2288. };
  2289. try {
  2290. loadingTask.onPassword(updatePassword, exception.code);
  2291. } catch (ex) {
  2292. this._passwordCapability.reject(ex);
  2293. }
  2294. } else {
  2295. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2296. }
  2297. return this._passwordCapability.promise;
  2298. });
  2299. messageHandler.on("DataLoaded", data => {
  2300. loadingTask.onProgress?.({
  2301. loaded: data.length,
  2302. total: data.length
  2303. });
  2304. this.downloadInfoCapability.resolve(data);
  2305. });
  2306. messageHandler.on("StartRenderPage", data => {
  2307. if (this.destroyed) {
  2308. return;
  2309. }
  2310. const page = this.#pageCache.get(data.pageIndex);
  2311. page._startRenderPage(data.transparency, data.cacheKey);
  2312. });
  2313. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2314. if (this.destroyed) {
  2315. return;
  2316. }
  2317. if (this.commonObjs.has(id)) {
  2318. return;
  2319. }
  2320. switch (type) {
  2321. case "Font":
  2322. const params = this._params;
  2323. if ("error" in exportedData) {
  2324. const exportedError = exportedData.error;
  2325. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2326. this.commonObjs.resolve(id, exportedError);
  2327. break;
  2328. }
  2329. let fontRegistry = null;
  2330. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2331. fontRegistry = {
  2332. registerFont(font, url) {
  2333. globalThis.FontInspector.fontAdded(font, url);
  2334. }
  2335. };
  2336. }
  2337. const font = new _font_loader.FontFaceObject(exportedData, {
  2338. isEvalSupported: params.isEvalSupported,
  2339. disableFontFace: params.disableFontFace,
  2340. ignoreErrors: params.ignoreErrors,
  2341. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2342. fontRegistry
  2343. });
  2344. this.fontLoader.bind(font).catch(reason => {
  2345. return messageHandler.sendWithPromise("FontFallback", {
  2346. id
  2347. });
  2348. }).finally(() => {
  2349. if (!params.fontExtraProperties && font.data) {
  2350. font.data = null;
  2351. }
  2352. this.commonObjs.resolve(id, font);
  2353. });
  2354. break;
  2355. case "FontPath":
  2356. case "Image":
  2357. this.commonObjs.resolve(id, exportedData);
  2358. break;
  2359. default:
  2360. throw new Error(`Got unknown common object type ${type}`);
  2361. }
  2362. });
  2363. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  2364. if (this.destroyed) {
  2365. return;
  2366. }
  2367. const pageProxy = this.#pageCache.get(pageIndex);
  2368. if (pageProxy.objs.has(id)) {
  2369. return;
  2370. }
  2371. switch (type) {
  2372. case "Image":
  2373. pageProxy.objs.resolve(id, imageData);
  2374. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2375. if (imageData) {
  2376. let length;
  2377. if (imageData.bitmap) {
  2378. const {
  2379. bitmap,
  2380. width,
  2381. height
  2382. } = imageData;
  2383. length = width * height * 4;
  2384. pageProxy._bitmaps.add(bitmap);
  2385. } else {
  2386. length = imageData.data?.length || 0;
  2387. }
  2388. if (length > MAX_IMAGE_SIZE_TO_STORE) {
  2389. pageProxy.cleanupAfterRender = true;
  2390. }
  2391. }
  2392. break;
  2393. case "Pattern":
  2394. pageProxy.objs.resolve(id, imageData);
  2395. break;
  2396. default:
  2397. throw new Error(`Got unknown object type ${type}`);
  2398. }
  2399. });
  2400. messageHandler.on("DocProgress", data => {
  2401. if (this.destroyed) {
  2402. return;
  2403. }
  2404. loadingTask.onProgress?.({
  2405. loaded: data.loaded,
  2406. total: data.total
  2407. });
  2408. });
  2409. messageHandler.on("DocStats", data => {
  2410. if (this.destroyed) {
  2411. return;
  2412. }
  2413. this.#docStats = Object.freeze({
  2414. streamTypes: Object.freeze(data.streamTypes),
  2415. fontTypes: Object.freeze(data.fontTypes)
  2416. });
  2417. });
  2418. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2419. messageHandler.on("FetchBuiltInCMap", data => {
  2420. if (this.destroyed) {
  2421. return Promise.reject(new Error("Worker was destroyed."));
  2422. }
  2423. if (!this.CMapReaderFactory) {
  2424. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2425. }
  2426. return this.CMapReaderFactory.fetch(data);
  2427. });
  2428. messageHandler.on("FetchStandardFontData", data => {
  2429. if (this.destroyed) {
  2430. return Promise.reject(new Error("Worker was destroyed."));
  2431. }
  2432. if (!this.StandardFontDataFactory) {
  2433. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2434. }
  2435. return this.StandardFontDataFactory.fetch(data);
  2436. });
  2437. }
  2438. _onUnsupportedFeature({
  2439. featureId
  2440. }) {
  2441. if (this.destroyed) {
  2442. return;
  2443. }
  2444. this.loadingTask.onUnsupportedFeature?.(featureId);
  2445. }
  2446. getData() {
  2447. return this.messageHandler.sendWithPromise("GetData", null);
  2448. }
  2449. saveDocument() {
  2450. if (this.annotationStorage.size <= 0) {
  2451. (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  2452. }
  2453. return this.messageHandler.sendWithPromise("SaveDocument", {
  2454. isPureXfa: !!this._htmlForXfa,
  2455. numPages: this._numPages,
  2456. annotationStorage: this.annotationStorage.serializable,
  2457. filename: this._fullReader?.filename ?? null
  2458. }).finally(() => {
  2459. this.annotationStorage.resetModified();
  2460. });
  2461. }
  2462. getPage(pageNumber) {
  2463. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2464. return Promise.reject(new Error("Invalid page request."));
  2465. }
  2466. const pageIndex = pageNumber - 1,
  2467. cachedPromise = this.#pagePromises.get(pageIndex);
  2468. if (cachedPromise) {
  2469. return cachedPromise;
  2470. }
  2471. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2472. pageIndex
  2473. }).then(pageInfo => {
  2474. if (this.destroyed) {
  2475. throw new Error("Transport destroyed");
  2476. }
  2477. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  2478. this.#pageCache.set(pageIndex, page);
  2479. return page;
  2480. });
  2481. this.#pagePromises.set(pageIndex, promise);
  2482. return promise;
  2483. }
  2484. getPageIndex(ref) {
  2485. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  2486. return Promise.reject(new Error("Invalid pageIndex request."));
  2487. }
  2488. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2489. num: ref.num,
  2490. gen: ref.gen
  2491. });
  2492. }
  2493. getAnnotations(pageIndex, intent) {
  2494. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2495. pageIndex,
  2496. intent
  2497. });
  2498. }
  2499. getFieldObjects() {
  2500. return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
  2501. }
  2502. hasJSActions() {
  2503. return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
  2504. }
  2505. getCalculationOrderIds() {
  2506. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2507. }
  2508. getDestinations() {
  2509. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2510. }
  2511. getDestination(id) {
  2512. if (typeof id !== "string") {
  2513. return Promise.reject(new Error("Invalid destination request."));
  2514. }
  2515. return this.messageHandler.sendWithPromise("GetDestination", {
  2516. id
  2517. });
  2518. }
  2519. getPageLabels() {
  2520. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2521. }
  2522. getPageLayout() {
  2523. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2524. }
  2525. getPageMode() {
  2526. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2527. }
  2528. getViewerPreferences() {
  2529. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2530. }
  2531. getOpenAction() {
  2532. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2533. }
  2534. getAttachments() {
  2535. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2536. }
  2537. getJavaScript() {
  2538. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2539. }
  2540. getDocJSActions() {
  2541. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2542. }
  2543. getPageJSActions(pageIndex) {
  2544. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2545. pageIndex
  2546. });
  2547. }
  2548. getStructTree(pageIndex) {
  2549. return this.messageHandler.sendWithPromise("GetStructTree", {
  2550. pageIndex
  2551. });
  2552. }
  2553. getOutline() {
  2554. return this.messageHandler.sendWithPromise("GetOutline", null);
  2555. }
  2556. getOptionalContentConfig() {
  2557. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2558. return new _optional_content_config.OptionalContentConfig(results);
  2559. });
  2560. }
  2561. getPermissions() {
  2562. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2563. }
  2564. getMetadata() {
  2565. return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  2566. return {
  2567. info: results[0],
  2568. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2569. contentDispositionFilename: this._fullReader?.filename ?? null,
  2570. contentLength: this._fullReader?.contentLength ?? null
  2571. };
  2572. });
  2573. }
  2574. getMarkInfo() {
  2575. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2576. }
  2577. async startCleanup(keepLoadedFonts = false) {
  2578. if (this.destroyed) {
  2579. return;
  2580. }
  2581. await this.messageHandler.sendWithPromise("Cleanup", null);
  2582. for (const page of this.#pageCache.values()) {
  2583. const cleanupSuccessful = page.cleanup();
  2584. if (!cleanupSuccessful) {
  2585. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  2586. }
  2587. }
  2588. this.commonObjs.clear();
  2589. if (!keepLoadedFonts) {
  2590. this.fontLoader.clear();
  2591. }
  2592. this.#metadataPromise = null;
  2593. this._getFieldObjectsPromise = null;
  2594. this._hasJSActionsPromise = null;
  2595. }
  2596. get loadingParams() {
  2597. const params = this._params;
  2598. return (0, _util.shadow)(this, "loadingParams", {
  2599. disableAutoFetch: params.disableAutoFetch,
  2600. enableXfa: params.enableXfa
  2601. });
  2602. }
  2603. }
  2604. class PDFObjects {
  2605. #objs = Object.create(null);
  2606. #ensureObj(objId) {
  2607. const obj = this.#objs[objId];
  2608. if (obj) {
  2609. return obj;
  2610. }
  2611. return this.#objs[objId] = {
  2612. capability: (0, _util.createPromiseCapability)(),
  2613. data: null
  2614. };
  2615. }
  2616. get(objId, callback = null) {
  2617. if (callback) {
  2618. const obj = this.#ensureObj(objId);
  2619. obj.capability.promise.then(() => callback(obj.data));
  2620. return null;
  2621. }
  2622. const obj = this.#objs[objId];
  2623. if (!obj?.capability.settled) {
  2624. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2625. }
  2626. return obj.data;
  2627. }
  2628. has(objId) {
  2629. const obj = this.#objs[objId];
  2630. return obj?.capability.settled || false;
  2631. }
  2632. resolve(objId, data = null) {
  2633. const obj = this.#ensureObj(objId);
  2634. obj.data = data;
  2635. obj.capability.resolve();
  2636. }
  2637. clear() {
  2638. this.#objs = Object.create(null);
  2639. }
  2640. }
  2641. class RenderTask {
  2642. #internalRenderTask = null;
  2643. constructor(internalRenderTask) {
  2644. this.#internalRenderTask = internalRenderTask;
  2645. this.onContinue = null;
  2646. }
  2647. get promise() {
  2648. return this.#internalRenderTask.capability.promise;
  2649. }
  2650. cancel() {
  2651. this.#internalRenderTask.cancel();
  2652. }
  2653. get separateAnnots() {
  2654. const {
  2655. separateAnnots
  2656. } = this.#internalRenderTask.operatorList;
  2657. if (!separateAnnots) {
  2658. return false;
  2659. }
  2660. const {
  2661. annotationCanvasMap
  2662. } = this.#internalRenderTask;
  2663. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  2664. }
  2665. }
  2666. exports.RenderTask = RenderTask;
  2667. class InternalRenderTask {
  2668. static #canvasInUse = new WeakSet();
  2669. constructor({
  2670. callback,
  2671. params,
  2672. objs,
  2673. commonObjs,
  2674. annotationCanvasMap,
  2675. operatorList,
  2676. pageIndex,
  2677. canvasFactory,
  2678. useRequestAnimationFrame = false,
  2679. pdfBug = false,
  2680. pageColors = null
  2681. }) {
  2682. this.callback = callback;
  2683. this.params = params;
  2684. this.objs = objs;
  2685. this.commonObjs = commonObjs;
  2686. this.annotationCanvasMap = annotationCanvasMap;
  2687. this.operatorListIdx = null;
  2688. this.operatorList = operatorList;
  2689. this._pageIndex = pageIndex;
  2690. this.canvasFactory = canvasFactory;
  2691. this._pdfBug = pdfBug;
  2692. this.pageColors = pageColors;
  2693. this.running = false;
  2694. this.graphicsReadyCallback = null;
  2695. this.graphicsReady = false;
  2696. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  2697. this.cancelled = false;
  2698. this.capability = (0, _util.createPromiseCapability)();
  2699. this.task = new RenderTask(this);
  2700. this._cancelBound = this.cancel.bind(this);
  2701. this._continueBound = this._continue.bind(this);
  2702. this._scheduleNextBound = this._scheduleNext.bind(this);
  2703. this._nextBound = this._next.bind(this);
  2704. this._canvas = params.canvasContext.canvas;
  2705. }
  2706. get completed() {
  2707. return this.capability.promise.catch(function () {});
  2708. }
  2709. initializeGraphics({
  2710. transparency = false,
  2711. optionalContentConfig
  2712. }) {
  2713. if (this.cancelled) {
  2714. return;
  2715. }
  2716. if (this._canvas) {
  2717. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  2718. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  2719. }
  2720. InternalRenderTask.#canvasInUse.add(this._canvas);
  2721. }
  2722. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  2723. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  2724. this.stepper.init(this.operatorList);
  2725. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2726. }
  2727. const {
  2728. canvasContext,
  2729. viewport,
  2730. transform,
  2731. background
  2732. } = this.params;
  2733. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, optionalContentConfig, this.annotationCanvasMap, this.pageColors);
  2734. this.gfx.beginDrawing({
  2735. transform,
  2736. viewport,
  2737. transparency,
  2738. background
  2739. });
  2740. this.operatorListIdx = 0;
  2741. this.graphicsReady = true;
  2742. this.graphicsReadyCallback?.();
  2743. }
  2744. cancel(error = null) {
  2745. this.running = false;
  2746. this.cancelled = true;
  2747. this.gfx?.endDrawing();
  2748. if (this._canvas) {
  2749. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2750. }
  2751. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
  2752. }
  2753. operatorListChanged() {
  2754. if (!this.graphicsReady) {
  2755. if (!this.graphicsReadyCallback) {
  2756. this.graphicsReadyCallback = this._continueBound;
  2757. }
  2758. return;
  2759. }
  2760. this.stepper?.updateOperatorList(this.operatorList);
  2761. if (this.running) {
  2762. return;
  2763. }
  2764. this._continue();
  2765. }
  2766. _continue() {
  2767. this.running = true;
  2768. if (this.cancelled) {
  2769. return;
  2770. }
  2771. if (this.task.onContinue) {
  2772. this.task.onContinue(this._scheduleNextBound);
  2773. } else {
  2774. this._scheduleNext();
  2775. }
  2776. }
  2777. _scheduleNext() {
  2778. if (this._useRequestAnimationFrame) {
  2779. window.requestAnimationFrame(() => {
  2780. this._nextBound().catch(this._cancelBound);
  2781. });
  2782. } else {
  2783. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  2784. }
  2785. }
  2786. async _next() {
  2787. if (this.cancelled) {
  2788. return;
  2789. }
  2790. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  2791. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2792. this.running = false;
  2793. if (this.operatorList.lastChunk) {
  2794. this.gfx.endDrawing();
  2795. if (this._canvas) {
  2796. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2797. }
  2798. this.callback();
  2799. }
  2800. }
  2801. }
  2802. }
  2803. const version = '3.0.279';
  2804. exports.version = version;
  2805. const build = 'd0823066c';
  2806. exports.build = build;
  2807. /***/ }),
  2808. /* 3 */
  2809. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2810. Object.defineProperty(exports, "__esModule", ({
  2811. value: true
  2812. }));
  2813. exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
  2814. var _util = __w_pdfjs_require__(1);
  2815. var _editor = __w_pdfjs_require__(4);
  2816. var _murmurhash = __w_pdfjs_require__(8);
  2817. class AnnotationStorage {
  2818. constructor() {
  2819. this._storage = new Map();
  2820. this._modified = false;
  2821. this.onSetModified = null;
  2822. this.onResetModified = null;
  2823. this.onAnnotationEditor = null;
  2824. }
  2825. getValue(key, defaultValue) {
  2826. const value = this._storage.get(key);
  2827. if (value === undefined) {
  2828. return defaultValue;
  2829. }
  2830. return Object.assign(defaultValue, value);
  2831. }
  2832. getRawValue(key) {
  2833. return this._storage.get(key);
  2834. }
  2835. remove(key) {
  2836. this._storage.delete(key);
  2837. if (this._storage.size === 0) {
  2838. this.resetModified();
  2839. }
  2840. if (typeof this.onAnnotationEditor === "function") {
  2841. for (const value of this._storage.values()) {
  2842. if (value instanceof _editor.AnnotationEditor) {
  2843. return;
  2844. }
  2845. }
  2846. this.onAnnotationEditor(null);
  2847. }
  2848. }
  2849. setValue(key, value) {
  2850. const obj = this._storage.get(key);
  2851. let modified = false;
  2852. if (obj !== undefined) {
  2853. for (const [entry, val] of Object.entries(value)) {
  2854. if (obj[entry] !== val) {
  2855. modified = true;
  2856. obj[entry] = val;
  2857. }
  2858. }
  2859. } else {
  2860. modified = true;
  2861. this._storage.set(key, value);
  2862. }
  2863. if (modified) {
  2864. this.#setModified();
  2865. }
  2866. if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  2867. this.onAnnotationEditor(value.constructor._type);
  2868. }
  2869. }
  2870. has(key) {
  2871. return this._storage.has(key);
  2872. }
  2873. getAll() {
  2874. return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
  2875. }
  2876. get size() {
  2877. return this._storage.size;
  2878. }
  2879. #setModified() {
  2880. if (!this._modified) {
  2881. this._modified = true;
  2882. if (typeof this.onSetModified === "function") {
  2883. this.onSetModified();
  2884. }
  2885. }
  2886. }
  2887. resetModified() {
  2888. if (this._modified) {
  2889. this._modified = false;
  2890. if (typeof this.onResetModified === "function") {
  2891. this.onResetModified();
  2892. }
  2893. }
  2894. }
  2895. get print() {
  2896. return new PrintAnnotationStorage(this);
  2897. }
  2898. get serializable() {
  2899. if (this._storage.size === 0) {
  2900. return null;
  2901. }
  2902. const clone = new Map();
  2903. for (const [key, val] of this._storage) {
  2904. const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
  2905. if (serialized) {
  2906. clone.set(key, serialized);
  2907. }
  2908. }
  2909. return clone;
  2910. }
  2911. static getHash(map) {
  2912. if (!map) {
  2913. return "";
  2914. }
  2915. const hash = new _murmurhash.MurmurHash3_64();
  2916. for (const [key, val] of map) {
  2917. hash.update(`${key}:${JSON.stringify(val)}`);
  2918. }
  2919. return hash.hexdigest();
  2920. }
  2921. }
  2922. exports.AnnotationStorage = AnnotationStorage;
  2923. class PrintAnnotationStorage extends AnnotationStorage {
  2924. #serializable = null;
  2925. constructor(parent) {
  2926. super();
  2927. this.#serializable = structuredClone(parent.serializable);
  2928. }
  2929. get print() {
  2930. (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  2931. }
  2932. get serializable() {
  2933. return this.#serializable;
  2934. }
  2935. }
  2936. exports.PrintAnnotationStorage = PrintAnnotationStorage;
  2937. /***/ }),
  2938. /* 4 */
  2939. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2940. Object.defineProperty(exports, "__esModule", ({
  2941. value: true
  2942. }));
  2943. exports.AnnotationEditor = void 0;
  2944. var _tools = __w_pdfjs_require__(5);
  2945. var _util = __w_pdfjs_require__(1);
  2946. class AnnotationEditor {
  2947. #boundFocusin = this.focusin.bind(this);
  2948. #boundFocusout = this.focusout.bind(this);
  2949. #hasBeenSelected = false;
  2950. #isEditing = false;
  2951. #isInEditMode = false;
  2952. #zIndex = AnnotationEditor._zIndex++;
  2953. static _colorManager = new _tools.ColorManager();
  2954. static _zIndex = 1;
  2955. constructor(parameters) {
  2956. if (this.constructor === AnnotationEditor) {
  2957. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  2958. }
  2959. this.parent = parameters.parent;
  2960. this.id = parameters.id;
  2961. this.width = this.height = null;
  2962. this.pageIndex = parameters.parent.pageIndex;
  2963. this.name = parameters.name;
  2964. this.div = null;
  2965. const [width, height] = this.parent.viewportBaseDimensions;
  2966. this.x = parameters.x / width;
  2967. this.y = parameters.y / height;
  2968. this.rotation = this.parent.viewport.rotation;
  2969. this.isAttachedToDOM = false;
  2970. }
  2971. static get _defaultLineColor() {
  2972. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  2973. }
  2974. setInBackground() {
  2975. this.div.style.zIndex = 0;
  2976. }
  2977. setInForeground() {
  2978. this.div.style.zIndex = this.#zIndex;
  2979. }
  2980. focusin(event) {
  2981. if (!this.#hasBeenSelected) {
  2982. this.parent.setSelected(this);
  2983. } else {
  2984. this.#hasBeenSelected = false;
  2985. }
  2986. }
  2987. focusout(event) {
  2988. if (!this.isAttachedToDOM) {
  2989. return;
  2990. }
  2991. const target = event.relatedTarget;
  2992. if (target?.closest(`#${this.id}`)) {
  2993. return;
  2994. }
  2995. event.preventDefault();
  2996. if (!this.parent.isMultipleSelection) {
  2997. this.commitOrRemove();
  2998. }
  2999. }
  3000. commitOrRemove() {
  3001. if (this.isEmpty()) {
  3002. this.remove();
  3003. } else {
  3004. this.commit();
  3005. }
  3006. }
  3007. commit() {
  3008. this.parent.addToAnnotationStorage(this);
  3009. }
  3010. dragstart(event) {
  3011. const rect = this.parent.div.getBoundingClientRect();
  3012. this.startX = event.clientX - rect.x;
  3013. this.startY = event.clientY - rect.y;
  3014. event.dataTransfer.setData("text/plain", this.id);
  3015. event.dataTransfer.effectAllowed = "move";
  3016. }
  3017. setAt(x, y, tx, ty) {
  3018. const [width, height] = this.parent.viewportBaseDimensions;
  3019. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3020. this.x = (x + tx) / width;
  3021. this.y = (y + ty) / height;
  3022. this.div.style.left = `${100 * this.x}%`;
  3023. this.div.style.top = `${100 * this.y}%`;
  3024. }
  3025. translate(x, y) {
  3026. const [width, height] = this.parent.viewportBaseDimensions;
  3027. [x, y] = this.screenToPageTranslation(x, y);
  3028. this.x += x / width;
  3029. this.y += y / height;
  3030. this.div.style.left = `${100 * this.x}%`;
  3031. this.div.style.top = `${100 * this.y}%`;
  3032. }
  3033. screenToPageTranslation(x, y) {
  3034. const {
  3035. rotation
  3036. } = this.parent.viewport;
  3037. switch (rotation) {
  3038. case 90:
  3039. return [y, -x];
  3040. case 180:
  3041. return [-x, -y];
  3042. case 270:
  3043. return [-y, x];
  3044. default:
  3045. return [x, y];
  3046. }
  3047. }
  3048. setDims(width, height) {
  3049. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3050. this.div.style.width = `${100 * width / parentWidth}%`;
  3051. this.div.style.height = `${100 * height / parentHeight}%`;
  3052. }
  3053. fixDims() {
  3054. const {
  3055. style
  3056. } = this.div;
  3057. const {
  3058. height,
  3059. width
  3060. } = style;
  3061. const widthPercent = width.endsWith("%");
  3062. const heightPercent = height.endsWith("%");
  3063. if (widthPercent && heightPercent) {
  3064. return;
  3065. }
  3066. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3067. if (!widthPercent) {
  3068. style.width = `${100 * parseFloat(width) / parentWidth}%`;
  3069. }
  3070. if (!heightPercent) {
  3071. style.height = `${100 * parseFloat(height) / parentHeight}%`;
  3072. }
  3073. }
  3074. getInitialTranslation() {
  3075. return [0, 0];
  3076. }
  3077. render() {
  3078. this.div = document.createElement("div");
  3079. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3080. this.div.className = this.name;
  3081. this.div.setAttribute("id", this.id);
  3082. this.div.setAttribute("tabIndex", 0);
  3083. this.setInForeground();
  3084. this.div.addEventListener("focusin", this.#boundFocusin);
  3085. this.div.addEventListener("focusout", this.#boundFocusout);
  3086. const [tx, ty] = this.getInitialTranslation();
  3087. this.translate(tx, ty);
  3088. (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
  3089. return this.div;
  3090. }
  3091. pointerdown(event) {
  3092. const isMac = _tools.KeyboardManager.platform.isMac;
  3093. if (event.button !== 0 || event.ctrlKey && isMac) {
  3094. event.preventDefault();
  3095. return;
  3096. }
  3097. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3098. this.parent.toggleSelected(this);
  3099. } else {
  3100. this.parent.setSelected(this);
  3101. }
  3102. this.#hasBeenSelected = true;
  3103. }
  3104. getRect(tx, ty) {
  3105. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  3106. const [pageWidth, pageHeight] = this.parent.pageDimensions;
  3107. const shiftX = pageWidth * tx / parentWidth;
  3108. const shiftY = pageHeight * ty / parentHeight;
  3109. const x = this.x * pageWidth;
  3110. const y = this.y * pageHeight;
  3111. const width = this.width * pageWidth;
  3112. const height = this.height * pageHeight;
  3113. switch (this.rotation) {
  3114. case 0:
  3115. return [x + shiftX, pageHeight - y - shiftY - height, x + shiftX + width, pageHeight - y - shiftY];
  3116. case 90:
  3117. return [x + shiftY, pageHeight - y + shiftX, x + shiftY + height, pageHeight - y + shiftX + width];
  3118. case 180:
  3119. return [x - shiftX - width, pageHeight - y + shiftY, x - shiftX, pageHeight - y + shiftY + height];
  3120. case 270:
  3121. return [x - shiftY - height, pageHeight - y - shiftX - width, x - shiftY, pageHeight - y - shiftX];
  3122. default:
  3123. throw new Error("Invalid rotation");
  3124. }
  3125. }
  3126. getRectInCurrentCoords(rect, pageHeight) {
  3127. const [x1, y1, x2, y2] = rect;
  3128. const width = x2 - x1;
  3129. const height = y2 - y1;
  3130. switch (this.rotation) {
  3131. case 0:
  3132. return [x1, pageHeight - y2, width, height];
  3133. case 90:
  3134. return [x1, pageHeight - y1, height, width];
  3135. case 180:
  3136. return [x2, pageHeight - y1, width, height];
  3137. case 270:
  3138. return [x2, pageHeight - y2, height, width];
  3139. default:
  3140. throw new Error("Invalid rotation");
  3141. }
  3142. }
  3143. onceAdded() {}
  3144. isEmpty() {
  3145. return false;
  3146. }
  3147. enableEditMode() {
  3148. this.#isInEditMode = true;
  3149. }
  3150. disableEditMode() {
  3151. this.#isInEditMode = false;
  3152. }
  3153. isInEditMode() {
  3154. return this.#isInEditMode;
  3155. }
  3156. shouldGetKeyboardEvents() {
  3157. return false;
  3158. }
  3159. needsToBeRebuilt() {
  3160. return this.div && !this.isAttachedToDOM;
  3161. }
  3162. rebuild() {
  3163. this.div?.addEventListener("focusin", this.#boundFocusin);
  3164. }
  3165. serialize() {
  3166. (0, _util.unreachable)("An editor must be serializable");
  3167. }
  3168. static deserialize(data, parent) {
  3169. const editor = new this.prototype.constructor({
  3170. parent,
  3171. id: parent.getNextId()
  3172. });
  3173. editor.rotation = data.rotation;
  3174. const [pageWidth, pageHeight] = parent.pageDimensions;
  3175. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3176. editor.x = x / pageWidth;
  3177. editor.y = y / pageHeight;
  3178. editor.width = width / pageWidth;
  3179. editor.height = height / pageHeight;
  3180. return editor;
  3181. }
  3182. remove() {
  3183. this.div.removeEventListener("focusin", this.#boundFocusin);
  3184. this.div.removeEventListener("focusout", this.#boundFocusout);
  3185. if (!this.isEmpty()) {
  3186. this.commit();
  3187. }
  3188. this.parent.remove(this);
  3189. }
  3190. select() {
  3191. this.div?.classList.add("selectedEditor");
  3192. }
  3193. unselect() {
  3194. this.div?.classList.remove("selectedEditor");
  3195. }
  3196. updateParams(type, value) {}
  3197. disableEditing() {}
  3198. enableEditing() {}
  3199. get propertiesToUpdate() {
  3200. return {};
  3201. }
  3202. get contentDiv() {
  3203. return this.div;
  3204. }
  3205. get isEditing() {
  3206. return this.#isEditing;
  3207. }
  3208. set isEditing(value) {
  3209. this.#isEditing = value;
  3210. if (value) {
  3211. this.parent.setSelected(this);
  3212. this.parent.setActiveEditor(this);
  3213. } else {
  3214. this.parent.setActiveEditor(null);
  3215. }
  3216. }
  3217. }
  3218. exports.AnnotationEditor = AnnotationEditor;
  3219. /***/ }),
  3220. /* 5 */
  3221. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3222. Object.defineProperty(exports, "__esModule", ({
  3223. value: true
  3224. }));
  3225. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3226. exports.bindEvents = bindEvents;
  3227. exports.opacityToHex = opacityToHex;
  3228. var _util = __w_pdfjs_require__(1);
  3229. var _display_utils = __w_pdfjs_require__(6);
  3230. function bindEvents(obj, element, names) {
  3231. for (const name of names) {
  3232. element.addEventListener(name, obj[name].bind(obj));
  3233. }
  3234. }
  3235. function opacityToHex(opacity) {
  3236. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3237. }
  3238. class IdManager {
  3239. #id = 0;
  3240. getId() {
  3241. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3242. }
  3243. }
  3244. class CommandManager {
  3245. #commands = [];
  3246. #locked = false;
  3247. #maxSize;
  3248. #position = -1;
  3249. constructor(maxSize = 128) {
  3250. this.#maxSize = maxSize;
  3251. }
  3252. add({
  3253. cmd,
  3254. undo,
  3255. mustExec,
  3256. type = NaN,
  3257. overwriteIfSameType = false,
  3258. keepUndo = false
  3259. }) {
  3260. if (mustExec) {
  3261. cmd();
  3262. }
  3263. if (this.#locked) {
  3264. return;
  3265. }
  3266. const save = {
  3267. cmd,
  3268. undo,
  3269. type
  3270. };
  3271. if (this.#position === -1) {
  3272. if (this.#commands.length > 0) {
  3273. this.#commands.length = 0;
  3274. }
  3275. this.#position = 0;
  3276. this.#commands.push(save);
  3277. return;
  3278. }
  3279. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3280. if (keepUndo) {
  3281. save.undo = this.#commands[this.#position].undo;
  3282. }
  3283. this.#commands[this.#position] = save;
  3284. return;
  3285. }
  3286. const next = this.#position + 1;
  3287. if (next === this.#maxSize) {
  3288. this.#commands.splice(0, 1);
  3289. } else {
  3290. this.#position = next;
  3291. if (next < this.#commands.length) {
  3292. this.#commands.splice(next);
  3293. }
  3294. }
  3295. this.#commands.push(save);
  3296. }
  3297. undo() {
  3298. if (this.#position === -1) {
  3299. return;
  3300. }
  3301. this.#locked = true;
  3302. this.#commands[this.#position].undo();
  3303. this.#locked = false;
  3304. this.#position -= 1;
  3305. }
  3306. redo() {
  3307. if (this.#position < this.#commands.length - 1) {
  3308. this.#position += 1;
  3309. this.#locked = true;
  3310. this.#commands[this.#position].cmd();
  3311. this.#locked = false;
  3312. }
  3313. }
  3314. hasSomethingToUndo() {
  3315. return this.#position !== -1;
  3316. }
  3317. hasSomethingToRedo() {
  3318. return this.#position < this.#commands.length - 1;
  3319. }
  3320. destroy() {
  3321. this.#commands = null;
  3322. }
  3323. }
  3324. exports.CommandManager = CommandManager;
  3325. class KeyboardManager {
  3326. constructor(callbacks) {
  3327. this.buffer = [];
  3328. this.callbacks = new Map();
  3329. this.allKeys = new Set();
  3330. const isMac = KeyboardManager.platform.isMac;
  3331. for (const [keys, callback] of callbacks) {
  3332. for (const key of keys) {
  3333. const isMacKey = key.startsWith("mac+");
  3334. if (isMac && isMacKey) {
  3335. this.callbacks.set(key.slice(4), callback);
  3336. this.allKeys.add(key.split("+").at(-1));
  3337. } else if (!isMac && !isMacKey) {
  3338. this.callbacks.set(key, callback);
  3339. this.allKeys.add(key.split("+").at(-1));
  3340. }
  3341. }
  3342. }
  3343. }
  3344. static get platform() {
  3345. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  3346. return (0, _util.shadow)(this, "platform", {
  3347. isWin: platform.includes("Win"),
  3348. isMac: platform.includes("Mac")
  3349. });
  3350. }
  3351. #serialize(event) {
  3352. if (event.altKey) {
  3353. this.buffer.push("alt");
  3354. }
  3355. if (event.ctrlKey) {
  3356. this.buffer.push("ctrl");
  3357. }
  3358. if (event.metaKey) {
  3359. this.buffer.push("meta");
  3360. }
  3361. if (event.shiftKey) {
  3362. this.buffer.push("shift");
  3363. }
  3364. this.buffer.push(event.key);
  3365. const str = this.buffer.join("+");
  3366. this.buffer.length = 0;
  3367. return str;
  3368. }
  3369. exec(self, event) {
  3370. if (!this.allKeys.has(event.key)) {
  3371. return;
  3372. }
  3373. const callback = this.callbacks.get(this.#serialize(event));
  3374. if (!callback) {
  3375. return;
  3376. }
  3377. callback.bind(self)();
  3378. event.stopPropagation();
  3379. event.preventDefault();
  3380. }
  3381. }
  3382. exports.KeyboardManager = KeyboardManager;
  3383. class ColorManager {
  3384. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  3385. get _colors() {
  3386. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  3387. (0, _display_utils.getColorValues)(colors);
  3388. return (0, _util.shadow)(this, "_colors", colors);
  3389. }
  3390. convert(color) {
  3391. const rgb = (0, _display_utils.getRGB)(color);
  3392. if (!window.matchMedia("(forced-colors: active)").matches) {
  3393. return rgb;
  3394. }
  3395. for (const [name, RGB] of this._colors) {
  3396. if (RGB.every((x, i) => x === rgb[i])) {
  3397. return ColorManager._colorsMapping.get(name);
  3398. }
  3399. }
  3400. return rgb;
  3401. }
  3402. getHexCode(name) {
  3403. const rgb = this._colors.get(name);
  3404. if (!rgb) {
  3405. return name;
  3406. }
  3407. return _util.Util.makeHexColor(...rgb);
  3408. }
  3409. }
  3410. exports.ColorManager = ColorManager;
  3411. class AnnotationEditorUIManager {
  3412. #activeEditor = null;
  3413. #allEditors = new Map();
  3414. #allLayers = new Map();
  3415. #commandManager = new CommandManager();
  3416. #currentPageIndex = 0;
  3417. #editorTypes = null;
  3418. #eventBus = null;
  3419. #idManager = new IdManager();
  3420. #isEnabled = false;
  3421. #mode = _util.AnnotationEditorType.NONE;
  3422. #selectedEditors = new Set();
  3423. #boundCopy = this.copy.bind(this);
  3424. #boundCut = this.cut.bind(this);
  3425. #boundPaste = this.paste.bind(this);
  3426. #boundKeydown = this.keydown.bind(this);
  3427. #boundOnEditingAction = this.onEditingAction.bind(this);
  3428. #boundOnPageChanging = this.onPageChanging.bind(this);
  3429. #previousStates = {
  3430. isEditing: false,
  3431. isEmpty: true,
  3432. hasSomethingToUndo: false,
  3433. hasSomethingToRedo: false,
  3434. hasSelectedEditor: false
  3435. };
  3436. #container = null;
  3437. static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
  3438. constructor(container, eventBus) {
  3439. this.#container = container;
  3440. this.#eventBus = eventBus;
  3441. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  3442. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  3443. }
  3444. destroy() {
  3445. this.#removeKeyboardManager();
  3446. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  3447. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  3448. for (const layer of this.#allLayers.values()) {
  3449. layer.destroy();
  3450. }
  3451. this.#allLayers.clear();
  3452. this.#allEditors.clear();
  3453. this.#activeEditor = null;
  3454. this.#selectedEditors.clear();
  3455. this.#commandManager.destroy();
  3456. }
  3457. onPageChanging({
  3458. pageNumber
  3459. }) {
  3460. this.#currentPageIndex = pageNumber - 1;
  3461. }
  3462. focusMainContainer() {
  3463. this.#container.focus();
  3464. }
  3465. #addKeyboardManager() {
  3466. this.#container.addEventListener("keydown", this.#boundKeydown);
  3467. }
  3468. #removeKeyboardManager() {
  3469. this.#container.removeEventListener("keydown", this.#boundKeydown);
  3470. }
  3471. #addCopyPasteListeners() {
  3472. document.addEventListener("copy", this.#boundCopy);
  3473. document.addEventListener("cut", this.#boundCut);
  3474. document.addEventListener("paste", this.#boundPaste);
  3475. }
  3476. #removeCopyPasteListeners() {
  3477. document.removeEventListener("copy", this.#boundCopy);
  3478. document.removeEventListener("cut", this.#boundCut);
  3479. document.removeEventListener("paste", this.#boundPaste);
  3480. }
  3481. copy(event) {
  3482. event.preventDefault();
  3483. if (this.#activeEditor) {
  3484. this.#activeEditor.commitOrRemove();
  3485. }
  3486. if (!this.hasSelection) {
  3487. return;
  3488. }
  3489. const editors = [];
  3490. for (const editor of this.#selectedEditors) {
  3491. if (!editor.isEmpty()) {
  3492. editors.push(editor.serialize());
  3493. }
  3494. }
  3495. if (editors.length === 0) {
  3496. return;
  3497. }
  3498. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  3499. }
  3500. cut(event) {
  3501. this.copy(event);
  3502. this.delete();
  3503. }
  3504. paste(event) {
  3505. event.preventDefault();
  3506. let data = event.clipboardData.getData("application/pdfjs");
  3507. if (!data) {
  3508. return;
  3509. }
  3510. try {
  3511. data = JSON.parse(data);
  3512. } catch (ex) {
  3513. (0, _util.warn)(`paste: "${ex.message}".`);
  3514. return;
  3515. }
  3516. if (!Array.isArray(data)) {
  3517. return;
  3518. }
  3519. this.unselectAll();
  3520. const layer = this.#allLayers.get(this.#currentPageIndex);
  3521. try {
  3522. const newEditors = [];
  3523. for (const editor of data) {
  3524. const deserializedEditor = layer.deserialize(editor);
  3525. if (!deserializedEditor) {
  3526. return;
  3527. }
  3528. newEditors.push(deserializedEditor);
  3529. }
  3530. const cmd = () => {
  3531. for (const editor of newEditors) {
  3532. this.#addEditorToLayer(editor);
  3533. }
  3534. this.#selectEditors(newEditors);
  3535. };
  3536. const undo = () => {
  3537. for (const editor of newEditors) {
  3538. editor.remove();
  3539. }
  3540. };
  3541. this.addCommands({
  3542. cmd,
  3543. undo,
  3544. mustExec: true
  3545. });
  3546. } catch (ex) {
  3547. (0, _util.warn)(`paste: "${ex.message}".`);
  3548. }
  3549. }
  3550. keydown(event) {
  3551. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  3552. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  3553. }
  3554. }
  3555. onEditingAction(details) {
  3556. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  3557. this[details.name]();
  3558. }
  3559. }
  3560. #dispatchUpdateStates(details) {
  3561. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  3562. if (hasChanged) {
  3563. this.#eventBus.dispatch("annotationeditorstateschanged", {
  3564. source: this,
  3565. details: Object.assign(this.#previousStates, details)
  3566. });
  3567. }
  3568. }
  3569. #dispatchUpdateUI(details) {
  3570. this.#eventBus.dispatch("annotationeditorparamschanged", {
  3571. source: this,
  3572. details
  3573. });
  3574. }
  3575. setEditingState(isEditing) {
  3576. if (isEditing) {
  3577. this.#addKeyboardManager();
  3578. this.#addCopyPasteListeners();
  3579. this.#dispatchUpdateStates({
  3580. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  3581. isEmpty: this.#isEmpty(),
  3582. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3583. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3584. hasSelectedEditor: false
  3585. });
  3586. } else {
  3587. this.#removeKeyboardManager();
  3588. this.#removeCopyPasteListeners();
  3589. this.#dispatchUpdateStates({
  3590. isEditing: false
  3591. });
  3592. }
  3593. }
  3594. registerEditorTypes(types) {
  3595. if (this.#editorTypes) {
  3596. return;
  3597. }
  3598. this.#editorTypes = types;
  3599. for (const editorType of this.#editorTypes) {
  3600. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  3601. }
  3602. }
  3603. getId() {
  3604. return this.#idManager.getId();
  3605. }
  3606. addLayer(layer) {
  3607. this.#allLayers.set(layer.pageIndex, layer);
  3608. if (this.#isEnabled) {
  3609. layer.enable();
  3610. } else {
  3611. layer.disable();
  3612. }
  3613. }
  3614. removeLayer(layer) {
  3615. this.#allLayers.delete(layer.pageIndex);
  3616. }
  3617. updateMode(mode) {
  3618. this.#mode = mode;
  3619. if (mode === _util.AnnotationEditorType.NONE) {
  3620. this.setEditingState(false);
  3621. this.#disableAll();
  3622. } else {
  3623. this.setEditingState(true);
  3624. this.#enableAll();
  3625. for (const layer of this.#allLayers.values()) {
  3626. layer.updateMode(mode);
  3627. }
  3628. }
  3629. }
  3630. updateToolbar(mode) {
  3631. if (mode === this.#mode) {
  3632. return;
  3633. }
  3634. this.#eventBus.dispatch("switchannotationeditormode", {
  3635. source: this,
  3636. mode
  3637. });
  3638. }
  3639. updateParams(type, value) {
  3640. if (!this.#editorTypes) {
  3641. return;
  3642. }
  3643. for (const editor of this.#selectedEditors) {
  3644. editor.updateParams(type, value);
  3645. }
  3646. for (const editorType of this.#editorTypes) {
  3647. editorType.updateDefaultParams(type, value);
  3648. }
  3649. }
  3650. #enableAll() {
  3651. if (!this.#isEnabled) {
  3652. this.#isEnabled = true;
  3653. for (const layer of this.#allLayers.values()) {
  3654. layer.enable();
  3655. }
  3656. }
  3657. }
  3658. #disableAll() {
  3659. this.unselectAll();
  3660. if (this.#isEnabled) {
  3661. this.#isEnabled = false;
  3662. for (const layer of this.#allLayers.values()) {
  3663. layer.disable();
  3664. }
  3665. }
  3666. }
  3667. getEditors(pageIndex) {
  3668. const editors = [];
  3669. for (const editor of this.#allEditors.values()) {
  3670. if (editor.pageIndex === pageIndex) {
  3671. editors.push(editor);
  3672. }
  3673. }
  3674. return editors;
  3675. }
  3676. getEditor(id) {
  3677. return this.#allEditors.get(id);
  3678. }
  3679. addEditor(editor) {
  3680. this.#allEditors.set(editor.id, editor);
  3681. }
  3682. removeEditor(editor) {
  3683. this.#allEditors.delete(editor.id);
  3684. this.unselect(editor);
  3685. }
  3686. #addEditorToLayer(editor) {
  3687. const layer = this.#allLayers.get(editor.pageIndex);
  3688. if (layer) {
  3689. layer.addOrRebuild(editor);
  3690. } else {
  3691. this.addEditor(editor);
  3692. }
  3693. }
  3694. setActiveEditor(editor) {
  3695. if (this.#activeEditor === editor) {
  3696. return;
  3697. }
  3698. this.#activeEditor = editor;
  3699. if (editor) {
  3700. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3701. }
  3702. }
  3703. toggleSelected(editor) {
  3704. if (this.#selectedEditors.has(editor)) {
  3705. this.#selectedEditors.delete(editor);
  3706. editor.unselect();
  3707. this.#dispatchUpdateStates({
  3708. hasSelectedEditor: this.hasSelection
  3709. });
  3710. return;
  3711. }
  3712. this.#selectedEditors.add(editor);
  3713. editor.select();
  3714. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3715. this.#dispatchUpdateStates({
  3716. hasSelectedEditor: true
  3717. });
  3718. }
  3719. setSelected(editor) {
  3720. for (const ed of this.#selectedEditors) {
  3721. if (ed !== editor) {
  3722. ed.unselect();
  3723. }
  3724. }
  3725. this.#selectedEditors.clear();
  3726. this.#selectedEditors.add(editor);
  3727. editor.select();
  3728. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3729. this.#dispatchUpdateStates({
  3730. hasSelectedEditor: true
  3731. });
  3732. }
  3733. isSelected(editor) {
  3734. return this.#selectedEditors.has(editor);
  3735. }
  3736. unselect(editor) {
  3737. editor.unselect();
  3738. this.#selectedEditors.delete(editor);
  3739. this.#dispatchUpdateStates({
  3740. hasSelectedEditor: this.hasSelection
  3741. });
  3742. }
  3743. get hasSelection() {
  3744. return this.#selectedEditors.size !== 0;
  3745. }
  3746. undo() {
  3747. this.#commandManager.undo();
  3748. this.#dispatchUpdateStates({
  3749. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3750. hasSomethingToRedo: true,
  3751. isEmpty: this.#isEmpty()
  3752. });
  3753. }
  3754. redo() {
  3755. this.#commandManager.redo();
  3756. this.#dispatchUpdateStates({
  3757. hasSomethingToUndo: true,
  3758. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3759. isEmpty: this.#isEmpty()
  3760. });
  3761. }
  3762. addCommands(params) {
  3763. this.#commandManager.add(params);
  3764. this.#dispatchUpdateStates({
  3765. hasSomethingToUndo: true,
  3766. hasSomethingToRedo: false,
  3767. isEmpty: this.#isEmpty()
  3768. });
  3769. }
  3770. #isEmpty() {
  3771. if (this.#allEditors.size === 0) {
  3772. return true;
  3773. }
  3774. if (this.#allEditors.size === 1) {
  3775. for (const editor of this.#allEditors.values()) {
  3776. return editor.isEmpty();
  3777. }
  3778. }
  3779. return false;
  3780. }
  3781. delete() {
  3782. this.commitOrRemove();
  3783. if (!this.hasSelection) {
  3784. return;
  3785. }
  3786. const editors = [...this.#selectedEditors];
  3787. const cmd = () => {
  3788. for (const editor of editors) {
  3789. editor.remove();
  3790. }
  3791. };
  3792. const undo = () => {
  3793. for (const editor of editors) {
  3794. this.#addEditorToLayer(editor);
  3795. }
  3796. };
  3797. this.addCommands({
  3798. cmd,
  3799. undo,
  3800. mustExec: true
  3801. });
  3802. }
  3803. commitOrRemove() {
  3804. this.#activeEditor?.commitOrRemove();
  3805. }
  3806. #selectEditors(editors) {
  3807. this.#selectedEditors.clear();
  3808. for (const editor of editors) {
  3809. if (editor.isEmpty()) {
  3810. continue;
  3811. }
  3812. this.#selectedEditors.add(editor);
  3813. editor.select();
  3814. }
  3815. this.#dispatchUpdateStates({
  3816. hasSelectedEditor: true
  3817. });
  3818. }
  3819. selectAll() {
  3820. for (const editor of this.#selectedEditors) {
  3821. editor.commit();
  3822. }
  3823. this.#selectEditors(this.#allEditors.values());
  3824. }
  3825. unselectAll() {
  3826. if (this.#activeEditor) {
  3827. this.#activeEditor.commitOrRemove();
  3828. return;
  3829. }
  3830. if (this.#selectedEditors.size === 0) {
  3831. return;
  3832. }
  3833. for (const editor of this.#selectedEditors) {
  3834. editor.unselect();
  3835. }
  3836. this.#selectedEditors.clear();
  3837. this.#dispatchUpdateStates({
  3838. hasSelectedEditor: false
  3839. });
  3840. }
  3841. isActive(editor) {
  3842. return this.#activeEditor === editor;
  3843. }
  3844. getActive() {
  3845. return this.#activeEditor;
  3846. }
  3847. getMode() {
  3848. return this.#mode;
  3849. }
  3850. }
  3851. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  3852. /***/ }),
  3853. /* 6 */
  3854. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3855. Object.defineProperty(exports, "__esModule", ({
  3856. value: true
  3857. }));
  3858. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  3859. exports.deprecated = deprecated;
  3860. exports.getColorValues = getColorValues;
  3861. exports.getCurrentTransform = getCurrentTransform;
  3862. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  3863. exports.getFilenameFromUrl = getFilenameFromUrl;
  3864. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  3865. exports.getRGB = getRGB;
  3866. exports.getXfaPageViewport = getXfaPageViewport;
  3867. exports.isDataScheme = isDataScheme;
  3868. exports.isPdfFile = isPdfFile;
  3869. exports.isValidFetchUrl = isValidFetchUrl;
  3870. exports.loadScript = loadScript;
  3871. var _base_factory = __w_pdfjs_require__(7);
  3872. var _util = __w_pdfjs_require__(1);
  3873. const SVG_NS = "http://www.w3.org/2000/svg";
  3874. const AnnotationPrefix = "pdfjs_internal_id_";
  3875. exports.AnnotationPrefix = AnnotationPrefix;
  3876. class PixelsPerInch {
  3877. static CSS = 96.0;
  3878. static PDF = 72.0;
  3879. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  3880. }
  3881. exports.PixelsPerInch = PixelsPerInch;
  3882. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  3883. constructor({
  3884. ownerDocument = globalThis.document
  3885. } = {}) {
  3886. super();
  3887. this._document = ownerDocument;
  3888. }
  3889. _createCanvas(width, height) {
  3890. const canvas = this._document.createElement("canvas");
  3891. canvas.width = width;
  3892. canvas.height = height;
  3893. return canvas;
  3894. }
  3895. }
  3896. exports.DOMCanvasFactory = DOMCanvasFactory;
  3897. async function fetchData(url, asTypedArray = false) {
  3898. if (isValidFetchUrl(url, document.baseURI)) {
  3899. const response = await fetch(url);
  3900. if (!response.ok) {
  3901. throw new Error(response.statusText);
  3902. }
  3903. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  3904. }
  3905. return new Promise((resolve, reject) => {
  3906. const request = new XMLHttpRequest();
  3907. request.open("GET", url, true);
  3908. if (asTypedArray) {
  3909. request.responseType = "arraybuffer";
  3910. }
  3911. request.onreadystatechange = () => {
  3912. if (request.readyState !== XMLHttpRequest.DONE) {
  3913. return;
  3914. }
  3915. if (request.status === 200 || request.status === 0) {
  3916. let data;
  3917. if (asTypedArray && request.response) {
  3918. data = new Uint8Array(request.response);
  3919. } else if (!asTypedArray && request.responseText) {
  3920. data = (0, _util.stringToBytes)(request.responseText);
  3921. }
  3922. if (data) {
  3923. resolve(data);
  3924. return;
  3925. }
  3926. }
  3927. reject(new Error(request.statusText));
  3928. };
  3929. request.send(null);
  3930. });
  3931. }
  3932. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  3933. _fetchData(url, compressionType) {
  3934. return fetchData(url, this.isCompressed).then(data => {
  3935. return {
  3936. cMapData: data,
  3937. compressionType
  3938. };
  3939. });
  3940. }
  3941. }
  3942. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  3943. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  3944. _fetchData(url) {
  3945. return fetchData(url, true);
  3946. }
  3947. }
  3948. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  3949. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  3950. _createSVG(type) {
  3951. return document.createElementNS(SVG_NS, type);
  3952. }
  3953. }
  3954. exports.DOMSVGFactory = DOMSVGFactory;
  3955. class PageViewport {
  3956. constructor({
  3957. viewBox,
  3958. scale,
  3959. rotation,
  3960. offsetX = 0,
  3961. offsetY = 0,
  3962. dontFlip = false
  3963. }) {
  3964. this.viewBox = viewBox;
  3965. this.scale = scale;
  3966. this.rotation = rotation;
  3967. this.offsetX = offsetX;
  3968. this.offsetY = offsetY;
  3969. const centerX = (viewBox[2] + viewBox[0]) / 2;
  3970. const centerY = (viewBox[3] + viewBox[1]) / 2;
  3971. let rotateA, rotateB, rotateC, rotateD;
  3972. rotation %= 360;
  3973. if (rotation < 0) {
  3974. rotation += 360;
  3975. }
  3976. switch (rotation) {
  3977. case 180:
  3978. rotateA = -1;
  3979. rotateB = 0;
  3980. rotateC = 0;
  3981. rotateD = 1;
  3982. break;
  3983. case 90:
  3984. rotateA = 0;
  3985. rotateB = 1;
  3986. rotateC = 1;
  3987. rotateD = 0;
  3988. break;
  3989. case 270:
  3990. rotateA = 0;
  3991. rotateB = -1;
  3992. rotateC = -1;
  3993. rotateD = 0;
  3994. break;
  3995. case 0:
  3996. rotateA = 1;
  3997. rotateB = 0;
  3998. rotateC = 0;
  3999. rotateD = -1;
  4000. break;
  4001. default:
  4002. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  4003. }
  4004. if (dontFlip) {
  4005. rotateC = -rotateC;
  4006. rotateD = -rotateD;
  4007. }
  4008. let offsetCanvasX, offsetCanvasY;
  4009. let width, height;
  4010. if (rotateA === 0) {
  4011. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  4012. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  4013. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  4014. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  4015. } else {
  4016. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  4017. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  4018. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  4019. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  4020. }
  4021. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4022. this.width = width;
  4023. this.height = height;
  4024. }
  4025. clone({
  4026. scale = this.scale,
  4027. rotation = this.rotation,
  4028. offsetX = this.offsetX,
  4029. offsetY = this.offsetY,
  4030. dontFlip = false
  4031. } = {}) {
  4032. return new PageViewport({
  4033. viewBox: this.viewBox.slice(),
  4034. scale,
  4035. rotation,
  4036. offsetX,
  4037. offsetY,
  4038. dontFlip
  4039. });
  4040. }
  4041. convertToViewportPoint(x, y) {
  4042. return _util.Util.applyTransform([x, y], this.transform);
  4043. }
  4044. convertToViewportRectangle(rect) {
  4045. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  4046. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  4047. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  4048. }
  4049. convertToPdfPoint(x, y) {
  4050. return _util.Util.applyInverseTransform([x, y], this.transform);
  4051. }
  4052. }
  4053. exports.PageViewport = PageViewport;
  4054. class RenderingCancelledException extends _util.BaseException {
  4055. constructor(msg, type) {
  4056. super(msg, "RenderingCancelledException");
  4057. this.type = type;
  4058. }
  4059. }
  4060. exports.RenderingCancelledException = RenderingCancelledException;
  4061. function isDataScheme(url) {
  4062. const ii = url.length;
  4063. let i = 0;
  4064. while (i < ii && url[i].trim() === "") {
  4065. i++;
  4066. }
  4067. return url.substring(i, i + 5).toLowerCase() === "data:";
  4068. }
  4069. function isPdfFile(filename) {
  4070. return typeof filename === "string" && /\.pdf$/i.test(filename);
  4071. }
  4072. function getFilenameFromUrl(url) {
  4073. const anchor = url.indexOf("#");
  4074. const query = url.indexOf("?");
  4075. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  4076. return url.substring(url.lastIndexOf("/", end) + 1, end);
  4077. }
  4078. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  4079. if (typeof url !== "string") {
  4080. return defaultFilename;
  4081. }
  4082. if (isDataScheme(url)) {
  4083. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  4084. return defaultFilename;
  4085. }
  4086. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  4087. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  4088. const splitURI = reURI.exec(url);
  4089. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  4090. if (suggestedFilename) {
  4091. suggestedFilename = suggestedFilename[0];
  4092. if (suggestedFilename.includes("%")) {
  4093. try {
  4094. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  4095. } catch (ex) {}
  4096. }
  4097. }
  4098. return suggestedFilename || defaultFilename;
  4099. }
  4100. class StatTimer {
  4101. constructor() {
  4102. this.started = Object.create(null);
  4103. this.times = [];
  4104. }
  4105. time(name) {
  4106. if (name in this.started) {
  4107. (0, _util.warn)(`Timer is already running for ${name}`);
  4108. }
  4109. this.started[name] = Date.now();
  4110. }
  4111. timeEnd(name) {
  4112. if (!(name in this.started)) {
  4113. (0, _util.warn)(`Timer has not been started for ${name}`);
  4114. }
  4115. this.times.push({
  4116. name,
  4117. start: this.started[name],
  4118. end: Date.now()
  4119. });
  4120. delete this.started[name];
  4121. }
  4122. toString() {
  4123. const outBuf = [];
  4124. let longest = 0;
  4125. for (const time of this.times) {
  4126. const name = time.name;
  4127. if (name.length > longest) {
  4128. longest = name.length;
  4129. }
  4130. }
  4131. for (const time of this.times) {
  4132. const duration = time.end - time.start;
  4133. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  4134. }
  4135. return outBuf.join("");
  4136. }
  4137. }
  4138. exports.StatTimer = StatTimer;
  4139. function isValidFetchUrl(url, baseUrl) {
  4140. try {
  4141. const {
  4142. protocol
  4143. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  4144. return protocol === "http:" || protocol === "https:";
  4145. } catch (ex) {
  4146. return false;
  4147. }
  4148. }
  4149. function loadScript(src, removeScriptElement = false) {
  4150. return new Promise((resolve, reject) => {
  4151. const script = document.createElement("script");
  4152. script.src = src;
  4153. script.onload = function (evt) {
  4154. if (removeScriptElement) {
  4155. script.remove();
  4156. }
  4157. resolve(evt);
  4158. };
  4159. script.onerror = function () {
  4160. reject(new Error(`Cannot load script at: ${script.src}`));
  4161. };
  4162. (document.head || document.documentElement).append(script);
  4163. });
  4164. }
  4165. function deprecated(details) {
  4166. console.log("Deprecated API usage: " + details);
  4167. }
  4168. let pdfDateStringRegex;
  4169. class PDFDateString {
  4170. static toDateObject(input) {
  4171. if (!input || typeof input !== "string") {
  4172. return null;
  4173. }
  4174. if (!pdfDateStringRegex) {
  4175. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  4176. }
  4177. const matches = pdfDateStringRegex.exec(input);
  4178. if (!matches) {
  4179. return null;
  4180. }
  4181. const year = parseInt(matches[1], 10);
  4182. let month = parseInt(matches[2], 10);
  4183. month = month >= 1 && month <= 12 ? month - 1 : 0;
  4184. let day = parseInt(matches[3], 10);
  4185. day = day >= 1 && day <= 31 ? day : 1;
  4186. let hour = parseInt(matches[4], 10);
  4187. hour = hour >= 0 && hour <= 23 ? hour : 0;
  4188. let minute = parseInt(matches[5], 10);
  4189. minute = minute >= 0 && minute <= 59 ? minute : 0;
  4190. let second = parseInt(matches[6], 10);
  4191. second = second >= 0 && second <= 59 ? second : 0;
  4192. const universalTimeRelation = matches[7] || "Z";
  4193. let offsetHour = parseInt(matches[8], 10);
  4194. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  4195. let offsetMinute = parseInt(matches[9], 10) || 0;
  4196. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  4197. if (universalTimeRelation === "-") {
  4198. hour += offsetHour;
  4199. minute += offsetMinute;
  4200. } else if (universalTimeRelation === "+") {
  4201. hour -= offsetHour;
  4202. minute -= offsetMinute;
  4203. }
  4204. return new Date(Date.UTC(year, month, day, hour, minute, second));
  4205. }
  4206. }
  4207. exports.PDFDateString = PDFDateString;
  4208. function getXfaPageViewport(xfaPage, {
  4209. scale = 1,
  4210. rotation = 0
  4211. }) {
  4212. const {
  4213. width,
  4214. height
  4215. } = xfaPage.attributes.style;
  4216. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  4217. return new PageViewport({
  4218. viewBox,
  4219. scale,
  4220. rotation
  4221. });
  4222. }
  4223. function getRGB(color) {
  4224. if (color.startsWith("#")) {
  4225. const colorRGB = parseInt(color.slice(1), 16);
  4226. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  4227. }
  4228. if (color.startsWith("rgb(")) {
  4229. return color.slice(4, -1).split(",").map(x => parseInt(x));
  4230. }
  4231. if (color.startsWith("rgba(")) {
  4232. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  4233. }
  4234. (0, _util.warn)(`Not a valid color format: "${color}"`);
  4235. return [0, 0, 0];
  4236. }
  4237. function getColorValues(colors) {
  4238. const span = document.createElement("span");
  4239. span.style.visibility = "hidden";
  4240. document.body.append(span);
  4241. for (const name of colors.keys()) {
  4242. span.style.color = name;
  4243. const computedColor = window.getComputedStyle(span).color;
  4244. colors.set(name, getRGB(computedColor));
  4245. }
  4246. span.remove();
  4247. }
  4248. function getCurrentTransform(ctx) {
  4249. const {
  4250. a,
  4251. b,
  4252. c,
  4253. d,
  4254. e,
  4255. f
  4256. } = ctx.getTransform();
  4257. return [a, b, c, d, e, f];
  4258. }
  4259. function getCurrentTransformInverse(ctx) {
  4260. const {
  4261. a,
  4262. b,
  4263. c,
  4264. d,
  4265. e,
  4266. f
  4267. } = ctx.getTransform().invertSelf();
  4268. return [a, b, c, d, e, f];
  4269. }
  4270. /***/ }),
  4271. /* 7 */
  4272. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4273. Object.defineProperty(exports, "__esModule", ({
  4274. value: true
  4275. }));
  4276. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  4277. var _util = __w_pdfjs_require__(1);
  4278. class BaseCanvasFactory {
  4279. constructor() {
  4280. if (this.constructor === BaseCanvasFactory) {
  4281. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  4282. }
  4283. }
  4284. create(width, height) {
  4285. if (width <= 0 || height <= 0) {
  4286. throw new Error("Invalid canvas size");
  4287. }
  4288. const canvas = this._createCanvas(width, height);
  4289. return {
  4290. canvas,
  4291. context: canvas.getContext("2d")
  4292. };
  4293. }
  4294. reset(canvasAndContext, width, height) {
  4295. if (!canvasAndContext.canvas) {
  4296. throw new Error("Canvas is not specified");
  4297. }
  4298. if (width <= 0 || height <= 0) {
  4299. throw new Error("Invalid canvas size");
  4300. }
  4301. canvasAndContext.canvas.width = width;
  4302. canvasAndContext.canvas.height = height;
  4303. }
  4304. destroy(canvasAndContext) {
  4305. if (!canvasAndContext.canvas) {
  4306. throw new Error("Canvas is not specified");
  4307. }
  4308. canvasAndContext.canvas.width = 0;
  4309. canvasAndContext.canvas.height = 0;
  4310. canvasAndContext.canvas = null;
  4311. canvasAndContext.context = null;
  4312. }
  4313. _createCanvas(width, height) {
  4314. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  4315. }
  4316. }
  4317. exports.BaseCanvasFactory = BaseCanvasFactory;
  4318. class BaseCMapReaderFactory {
  4319. constructor({
  4320. baseUrl = null,
  4321. isCompressed = false
  4322. }) {
  4323. if (this.constructor === BaseCMapReaderFactory) {
  4324. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  4325. }
  4326. this.baseUrl = baseUrl;
  4327. this.isCompressed = isCompressed;
  4328. }
  4329. async fetch({
  4330. name
  4331. }) {
  4332. if (!this.baseUrl) {
  4333. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  4334. }
  4335. if (!name) {
  4336. throw new Error("CMap name must be specified.");
  4337. }
  4338. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  4339. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  4340. return this._fetchData(url, compressionType).catch(reason => {
  4341. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  4342. });
  4343. }
  4344. _fetchData(url, compressionType) {
  4345. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4346. }
  4347. }
  4348. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  4349. class BaseStandardFontDataFactory {
  4350. constructor({
  4351. baseUrl = null
  4352. }) {
  4353. if (this.constructor === BaseStandardFontDataFactory) {
  4354. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  4355. }
  4356. this.baseUrl = baseUrl;
  4357. }
  4358. async fetch({
  4359. filename
  4360. }) {
  4361. if (!this.baseUrl) {
  4362. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  4363. }
  4364. if (!filename) {
  4365. throw new Error("Font filename must be specified.");
  4366. }
  4367. const url = `${this.baseUrl}${filename}`;
  4368. return this._fetchData(url).catch(reason => {
  4369. throw new Error(`Unable to load font data at: ${url}`);
  4370. });
  4371. }
  4372. _fetchData(url) {
  4373. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4374. }
  4375. }
  4376. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  4377. class BaseSVGFactory {
  4378. constructor() {
  4379. if (this.constructor === BaseSVGFactory) {
  4380. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  4381. }
  4382. }
  4383. create(width, height, skipDimensions = false) {
  4384. if (width <= 0 || height <= 0) {
  4385. throw new Error("Invalid SVG dimensions");
  4386. }
  4387. const svg = this._createSVG("svg:svg");
  4388. svg.setAttribute("version", "1.1");
  4389. if (!skipDimensions) {
  4390. svg.setAttribute("width", `${width}px`);
  4391. svg.setAttribute("height", `${height}px`);
  4392. }
  4393. svg.setAttribute("preserveAspectRatio", "none");
  4394. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  4395. return svg;
  4396. }
  4397. createElement(type) {
  4398. if (typeof type !== "string") {
  4399. throw new Error("Invalid SVG element type");
  4400. }
  4401. return this._createSVG(type);
  4402. }
  4403. _createSVG(type) {
  4404. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  4405. }
  4406. }
  4407. exports.BaseSVGFactory = BaseSVGFactory;
  4408. /***/ }),
  4409. /* 8 */
  4410. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4411. Object.defineProperty(exports, "__esModule", ({
  4412. value: true
  4413. }));
  4414. exports.MurmurHash3_64 = void 0;
  4415. var _util = __w_pdfjs_require__(1);
  4416. const SEED = 0xc3d2e1f0;
  4417. const MASK_HIGH = 0xffff0000;
  4418. const MASK_LOW = 0xffff;
  4419. class MurmurHash3_64 {
  4420. constructor(seed) {
  4421. this.h1 = seed ? seed & 0xffffffff : SEED;
  4422. this.h2 = seed ? seed & 0xffffffff : SEED;
  4423. }
  4424. update(input) {
  4425. let data, length;
  4426. if (typeof input === "string") {
  4427. data = new Uint8Array(input.length * 2);
  4428. length = 0;
  4429. for (let i = 0, ii = input.length; i < ii; i++) {
  4430. const code = input.charCodeAt(i);
  4431. if (code <= 0xff) {
  4432. data[length++] = code;
  4433. } else {
  4434. data[length++] = code >>> 8;
  4435. data[length++] = code & 0xff;
  4436. }
  4437. }
  4438. } else if ((0, _util.isArrayBuffer)(input)) {
  4439. data = input.slice();
  4440. length = data.byteLength;
  4441. } else {
  4442. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  4443. }
  4444. const blockCounts = length >> 2;
  4445. const tailLength = length - blockCounts * 4;
  4446. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4447. let k1 = 0,
  4448. k2 = 0;
  4449. let h1 = this.h1,
  4450. h2 = this.h2;
  4451. const C1 = 0xcc9e2d51,
  4452. C2 = 0x1b873593;
  4453. const C1_LOW = C1 & MASK_LOW,
  4454. C2_LOW = C2 & MASK_LOW;
  4455. for (let i = 0; i < blockCounts; i++) {
  4456. if (i & 1) {
  4457. k1 = dataUint32[i];
  4458. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4459. k1 = k1 << 15 | k1 >>> 17;
  4460. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4461. h1 ^= k1;
  4462. h1 = h1 << 13 | h1 >>> 19;
  4463. h1 = h1 * 5 + 0xe6546b64;
  4464. } else {
  4465. k2 = dataUint32[i];
  4466. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4467. k2 = k2 << 15 | k2 >>> 17;
  4468. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4469. h2 ^= k2;
  4470. h2 = h2 << 13 | h2 >>> 19;
  4471. h2 = h2 * 5 + 0xe6546b64;
  4472. }
  4473. }
  4474. k1 = 0;
  4475. switch (tailLength) {
  4476. case 3:
  4477. k1 ^= data[blockCounts * 4 + 2] << 16;
  4478. case 2:
  4479. k1 ^= data[blockCounts * 4 + 1] << 8;
  4480. case 1:
  4481. k1 ^= data[blockCounts * 4];
  4482. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4483. k1 = k1 << 15 | k1 >>> 17;
  4484. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4485. if (blockCounts & 1) {
  4486. h1 ^= k1;
  4487. } else {
  4488. h2 ^= k1;
  4489. }
  4490. }
  4491. this.h1 = h1;
  4492. this.h2 = h2;
  4493. }
  4494. hexdigest() {
  4495. let h1 = this.h1,
  4496. h2 = this.h2;
  4497. h1 ^= h2 >>> 1;
  4498. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4499. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4500. h1 ^= h2 >>> 1;
  4501. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4502. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4503. h1 ^= h2 >>> 1;
  4504. const hex1 = (h1 >>> 0).toString(16),
  4505. hex2 = (h2 >>> 0).toString(16);
  4506. return hex1.padStart(8, "0") + hex2.padStart(8, "0");
  4507. }
  4508. }
  4509. exports.MurmurHash3_64 = MurmurHash3_64;
  4510. /***/ }),
  4511. /* 9 */
  4512. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4513. Object.defineProperty(exports, "__esModule", ({
  4514. value: true
  4515. }));
  4516. exports.FontLoader = exports.FontFaceObject = void 0;
  4517. var _util = __w_pdfjs_require__(1);
  4518. class FontLoader {
  4519. constructor({
  4520. onUnsupportedFeature,
  4521. ownerDocument = globalThis.document,
  4522. styleElement = null
  4523. }) {
  4524. this._onUnsupportedFeature = onUnsupportedFeature;
  4525. this._document = ownerDocument;
  4526. this.nativeFontFaces = [];
  4527. this.styleElement = null;
  4528. this.loadingRequests = [];
  4529. this.loadTestFontId = 0;
  4530. }
  4531. addNativeFontFace(nativeFontFace) {
  4532. this.nativeFontFaces.push(nativeFontFace);
  4533. this._document.fonts.add(nativeFontFace);
  4534. }
  4535. insertRule(rule) {
  4536. if (!this.styleElement) {
  4537. this.styleElement = this._document.createElement("style");
  4538. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  4539. }
  4540. const styleSheet = this.styleElement.sheet;
  4541. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4542. }
  4543. clear() {
  4544. for (const nativeFontFace of this.nativeFontFaces) {
  4545. this._document.fonts.delete(nativeFontFace);
  4546. }
  4547. this.nativeFontFaces.length = 0;
  4548. if (this.styleElement) {
  4549. this.styleElement.remove();
  4550. this.styleElement = null;
  4551. }
  4552. }
  4553. async bind(font) {
  4554. if (font.attached || font.missingFile) {
  4555. return;
  4556. }
  4557. font.attached = true;
  4558. if (this.isFontLoadingAPISupported) {
  4559. const nativeFontFace = font.createNativeFontFace();
  4560. if (nativeFontFace) {
  4561. this.addNativeFontFace(nativeFontFace);
  4562. try {
  4563. await nativeFontFace.loaded;
  4564. } catch (ex) {
  4565. this._onUnsupportedFeature({
  4566. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  4567. });
  4568. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  4569. font.disableFontFace = true;
  4570. throw ex;
  4571. }
  4572. }
  4573. return;
  4574. }
  4575. const rule = font.createFontFaceRule();
  4576. if (rule) {
  4577. this.insertRule(rule);
  4578. if (this.isSyncFontLoadingSupported) {
  4579. return;
  4580. }
  4581. await new Promise(resolve => {
  4582. const request = this._queueLoadingCallback(resolve);
  4583. this._prepareFontLoadEvent(font, request);
  4584. });
  4585. }
  4586. }
  4587. get isFontLoadingAPISupported() {
  4588. const hasFonts = !!this._document?.fonts;
  4589. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  4590. }
  4591. get isSyncFontLoadingSupported() {
  4592. let supported = false;
  4593. if (typeof navigator === "undefined") {
  4594. supported = true;
  4595. } else {
  4596. const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  4597. if (m?.[1] >= 14) {
  4598. supported = true;
  4599. }
  4600. }
  4601. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  4602. }
  4603. _queueLoadingCallback(callback) {
  4604. function completeRequest() {
  4605. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  4606. request.done = true;
  4607. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  4608. const otherRequest = loadingRequests.shift();
  4609. setTimeout(otherRequest.callback, 0);
  4610. }
  4611. }
  4612. const {
  4613. loadingRequests
  4614. } = this;
  4615. const request = {
  4616. done: false,
  4617. complete: completeRequest,
  4618. callback
  4619. };
  4620. loadingRequests.push(request);
  4621. return request;
  4622. }
  4623. get _loadTestFont() {
  4624. 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==");
  4625. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  4626. }
  4627. _prepareFontLoadEvent(font, request) {
  4628. function int32(data, offset) {
  4629. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  4630. }
  4631. function spliceString(s, offset, remove, insert) {
  4632. const chunk1 = s.substring(0, offset);
  4633. const chunk2 = s.substring(offset + remove);
  4634. return chunk1 + insert + chunk2;
  4635. }
  4636. let i, ii;
  4637. const canvas = this._document.createElement("canvas");
  4638. canvas.width = 1;
  4639. canvas.height = 1;
  4640. const ctx = canvas.getContext("2d");
  4641. let called = 0;
  4642. function isFontReady(name, callback) {
  4643. if (++called > 30) {
  4644. (0, _util.warn)("Load test font never loaded.");
  4645. callback();
  4646. return;
  4647. }
  4648. ctx.font = "30px " + name;
  4649. ctx.fillText(".", 0, 20);
  4650. const imageData = ctx.getImageData(0, 0, 1, 1);
  4651. if (imageData.data[3] > 0) {
  4652. callback();
  4653. return;
  4654. }
  4655. setTimeout(isFontReady.bind(null, name, callback));
  4656. }
  4657. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  4658. let data = this._loadTestFont;
  4659. const COMMENT_OFFSET = 976;
  4660. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  4661. const CFF_CHECKSUM_OFFSET = 16;
  4662. const XXXX_VALUE = 0x58585858;
  4663. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  4664. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  4665. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  4666. }
  4667. if (i < loadTestFontId.length) {
  4668. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  4669. }
  4670. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  4671. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  4672. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  4673. this.insertRule(rule);
  4674. const div = this._document.createElement("div");
  4675. div.style.visibility = "hidden";
  4676. div.style.width = div.style.height = "10px";
  4677. div.style.position = "absolute";
  4678. div.style.top = div.style.left = "0px";
  4679. for (const name of [font.loadedName, loadTestFontId]) {
  4680. const span = this._document.createElement("span");
  4681. span.textContent = "Hi";
  4682. span.style.fontFamily = name;
  4683. div.append(span);
  4684. }
  4685. this._document.body.append(div);
  4686. isFontReady(loadTestFontId, () => {
  4687. div.remove();
  4688. request.complete();
  4689. });
  4690. }
  4691. }
  4692. exports.FontLoader = FontLoader;
  4693. class FontFaceObject {
  4694. constructor(translatedData, {
  4695. isEvalSupported = true,
  4696. disableFontFace = false,
  4697. ignoreErrors = false,
  4698. onUnsupportedFeature,
  4699. fontRegistry = null
  4700. }) {
  4701. this.compiledGlyphs = Object.create(null);
  4702. for (const i in translatedData) {
  4703. this[i] = translatedData[i];
  4704. }
  4705. this.isEvalSupported = isEvalSupported !== false;
  4706. this.disableFontFace = disableFontFace === true;
  4707. this.ignoreErrors = ignoreErrors === true;
  4708. this._onUnsupportedFeature = onUnsupportedFeature;
  4709. this.fontRegistry = fontRegistry;
  4710. }
  4711. createNativeFontFace() {
  4712. if (!this.data || this.disableFontFace) {
  4713. return null;
  4714. }
  4715. let nativeFontFace;
  4716. if (!this.cssFontInfo) {
  4717. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  4718. } else {
  4719. const css = {
  4720. weight: this.cssFontInfo.fontWeight
  4721. };
  4722. if (this.cssFontInfo.italicAngle) {
  4723. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  4724. }
  4725. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  4726. }
  4727. this.fontRegistry?.registerFont(this);
  4728. return nativeFontFace;
  4729. }
  4730. createFontFaceRule() {
  4731. if (!this.data || this.disableFontFace) {
  4732. return null;
  4733. }
  4734. const data = (0, _util.bytesToString)(this.data);
  4735. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  4736. let rule;
  4737. if (!this.cssFontInfo) {
  4738. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  4739. } else {
  4740. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  4741. if (this.cssFontInfo.italicAngle) {
  4742. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  4743. }
  4744. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  4745. }
  4746. this.fontRegistry?.registerFont(this, url);
  4747. return rule;
  4748. }
  4749. getPathGenerator(objs, character) {
  4750. if (this.compiledGlyphs[character] !== undefined) {
  4751. return this.compiledGlyphs[character];
  4752. }
  4753. let cmds;
  4754. try {
  4755. cmds = objs.get(this.loadedName + "_path_" + character);
  4756. } catch (ex) {
  4757. if (!this.ignoreErrors) {
  4758. throw ex;
  4759. }
  4760. this._onUnsupportedFeature({
  4761. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  4762. });
  4763. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  4764. return this.compiledGlyphs[character] = function (c, size) {};
  4765. }
  4766. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  4767. const jsBuf = [];
  4768. for (const current of cmds) {
  4769. const args = current.args !== undefined ? current.args.join(",") : "";
  4770. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  4771. }
  4772. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  4773. }
  4774. return this.compiledGlyphs[character] = function (c, size) {
  4775. for (const current of cmds) {
  4776. if (current.cmd === "scale") {
  4777. current.args = [size, -size];
  4778. }
  4779. c[current.cmd].apply(c, current.args);
  4780. }
  4781. };
  4782. }
  4783. }
  4784. exports.FontFaceObject = FontFaceObject;
  4785. /***/ }),
  4786. /* 10 */
  4787. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4788. Object.defineProperty(exports, "__esModule", ({
  4789. value: true
  4790. }));
  4791. exports.CanvasGraphics = void 0;
  4792. var _util = __w_pdfjs_require__(1);
  4793. var _display_utils = __w_pdfjs_require__(6);
  4794. var _pattern_helper = __w_pdfjs_require__(11);
  4795. var _image_utils = __w_pdfjs_require__(13);
  4796. var _is_node = __w_pdfjs_require__(12);
  4797. const MIN_FONT_SIZE = 16;
  4798. const MAX_FONT_SIZE = 100;
  4799. const MAX_GROUP_SIZE = 4096;
  4800. const EXECUTION_TIME = 15;
  4801. const EXECUTION_STEPS = 10;
  4802. const MAX_SIZE_TO_COMPILE = _is_node.isNodeJS && typeof Path2D === "undefined" ? -1 : 1000;
  4803. const FULL_CHUNK_HEIGHT = 16;
  4804. function mirrorContextOperations(ctx, destCtx) {
  4805. if (ctx._removeMirroring) {
  4806. throw new Error("Context is already forwarding operations.");
  4807. }
  4808. ctx.__originalSave = ctx.save;
  4809. ctx.__originalRestore = ctx.restore;
  4810. ctx.__originalRotate = ctx.rotate;
  4811. ctx.__originalScale = ctx.scale;
  4812. ctx.__originalTranslate = ctx.translate;
  4813. ctx.__originalTransform = ctx.transform;
  4814. ctx.__originalSetTransform = ctx.setTransform;
  4815. ctx.__originalResetTransform = ctx.resetTransform;
  4816. ctx.__originalClip = ctx.clip;
  4817. ctx.__originalMoveTo = ctx.moveTo;
  4818. ctx.__originalLineTo = ctx.lineTo;
  4819. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  4820. ctx.__originalRect = ctx.rect;
  4821. ctx.__originalClosePath = ctx.closePath;
  4822. ctx.__originalBeginPath = ctx.beginPath;
  4823. ctx._removeMirroring = () => {
  4824. ctx.save = ctx.__originalSave;
  4825. ctx.restore = ctx.__originalRestore;
  4826. ctx.rotate = ctx.__originalRotate;
  4827. ctx.scale = ctx.__originalScale;
  4828. ctx.translate = ctx.__originalTranslate;
  4829. ctx.transform = ctx.__originalTransform;
  4830. ctx.setTransform = ctx.__originalSetTransform;
  4831. ctx.resetTransform = ctx.__originalResetTransform;
  4832. ctx.clip = ctx.__originalClip;
  4833. ctx.moveTo = ctx.__originalMoveTo;
  4834. ctx.lineTo = ctx.__originalLineTo;
  4835. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  4836. ctx.rect = ctx.__originalRect;
  4837. ctx.closePath = ctx.__originalClosePath;
  4838. ctx.beginPath = ctx.__originalBeginPath;
  4839. delete ctx._removeMirroring;
  4840. };
  4841. ctx.save = function ctxSave() {
  4842. destCtx.save();
  4843. this.__originalSave();
  4844. };
  4845. ctx.restore = function ctxRestore() {
  4846. destCtx.restore();
  4847. this.__originalRestore();
  4848. };
  4849. ctx.translate = function ctxTranslate(x, y) {
  4850. destCtx.translate(x, y);
  4851. this.__originalTranslate(x, y);
  4852. };
  4853. ctx.scale = function ctxScale(x, y) {
  4854. destCtx.scale(x, y);
  4855. this.__originalScale(x, y);
  4856. };
  4857. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4858. destCtx.transform(a, b, c, d, e, f);
  4859. this.__originalTransform(a, b, c, d, e, f);
  4860. };
  4861. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4862. destCtx.setTransform(a, b, c, d, e, f);
  4863. this.__originalSetTransform(a, b, c, d, e, f);
  4864. };
  4865. ctx.resetTransform = function ctxResetTransform() {
  4866. destCtx.resetTransform();
  4867. this.__originalResetTransform();
  4868. };
  4869. ctx.rotate = function ctxRotate(angle) {
  4870. destCtx.rotate(angle);
  4871. this.__originalRotate(angle);
  4872. };
  4873. ctx.clip = function ctxRotate(rule) {
  4874. destCtx.clip(rule);
  4875. this.__originalClip(rule);
  4876. };
  4877. ctx.moveTo = function (x, y) {
  4878. destCtx.moveTo(x, y);
  4879. this.__originalMoveTo(x, y);
  4880. };
  4881. ctx.lineTo = function (x, y) {
  4882. destCtx.lineTo(x, y);
  4883. this.__originalLineTo(x, y);
  4884. };
  4885. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  4886. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4887. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  4888. };
  4889. ctx.rect = function (x, y, width, height) {
  4890. destCtx.rect(x, y, width, height);
  4891. this.__originalRect(x, y, width, height);
  4892. };
  4893. ctx.closePath = function () {
  4894. destCtx.closePath();
  4895. this.__originalClosePath();
  4896. };
  4897. ctx.beginPath = function () {
  4898. destCtx.beginPath();
  4899. this.__originalBeginPath();
  4900. };
  4901. }
  4902. class CachedCanvases {
  4903. constructor(canvasFactory) {
  4904. this.canvasFactory = canvasFactory;
  4905. this.cache = Object.create(null);
  4906. }
  4907. getCanvas(id, width, height) {
  4908. let canvasEntry;
  4909. if (this.cache[id] !== undefined) {
  4910. canvasEntry = this.cache[id];
  4911. this.canvasFactory.reset(canvasEntry, width, height);
  4912. } else {
  4913. canvasEntry = this.canvasFactory.create(width, height);
  4914. this.cache[id] = canvasEntry;
  4915. }
  4916. return canvasEntry;
  4917. }
  4918. delete(id) {
  4919. delete this.cache[id];
  4920. }
  4921. clear() {
  4922. for (const id in this.cache) {
  4923. const canvasEntry = this.cache[id];
  4924. this.canvasFactory.destroy(canvasEntry);
  4925. delete this.cache[id];
  4926. }
  4927. }
  4928. }
  4929. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  4930. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  4931. if (b === 0 && c === 0) {
  4932. const tlX = destX * a + tx;
  4933. const rTlX = Math.round(tlX);
  4934. const tlY = destY * d + ty;
  4935. const rTlY = Math.round(tlY);
  4936. const brX = (destX + destW) * a + tx;
  4937. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  4938. const brY = (destY + destH) * d + ty;
  4939. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  4940. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  4941. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  4942. ctx.setTransform(a, b, c, d, tx, ty);
  4943. return [rWidth, rHeight];
  4944. }
  4945. if (a === 0 && d === 0) {
  4946. const tlX = destY * c + tx;
  4947. const rTlX = Math.round(tlX);
  4948. const tlY = destX * b + ty;
  4949. const rTlY = Math.round(tlY);
  4950. const brX = (destY + destH) * c + tx;
  4951. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  4952. const brY = (destX + destW) * b + ty;
  4953. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  4954. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  4955. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  4956. ctx.setTransform(a, b, c, d, tx, ty);
  4957. return [rHeight, rWidth];
  4958. }
  4959. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  4960. const scaleX = Math.hypot(a, b);
  4961. const scaleY = Math.hypot(c, d);
  4962. return [scaleX * destW, scaleY * destH];
  4963. }
  4964. function compileType3Glyph(imgData) {
  4965. const {
  4966. width,
  4967. height
  4968. } = imgData;
  4969. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  4970. return null;
  4971. }
  4972. const POINT_TO_PROCESS_LIMIT = 1000;
  4973. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  4974. const width1 = width + 1;
  4975. let points = new Uint8Array(width1 * (height + 1));
  4976. let i, j, j0;
  4977. const lineSize = width + 7 & ~7;
  4978. let data = new Uint8Array(lineSize * height),
  4979. pos = 0;
  4980. for (const elem of imgData.data) {
  4981. let mask = 128;
  4982. while (mask > 0) {
  4983. data[pos++] = elem & mask ? 0 : 255;
  4984. mask >>= 1;
  4985. }
  4986. }
  4987. let count = 0;
  4988. pos = 0;
  4989. if (data[pos] !== 0) {
  4990. points[0] = 1;
  4991. ++count;
  4992. }
  4993. for (j = 1; j < width; j++) {
  4994. if (data[pos] !== data[pos + 1]) {
  4995. points[j] = data[pos] ? 2 : 1;
  4996. ++count;
  4997. }
  4998. pos++;
  4999. }
  5000. if (data[pos] !== 0) {
  5001. points[j] = 2;
  5002. ++count;
  5003. }
  5004. for (i = 1; i < height; i++) {
  5005. pos = i * lineSize;
  5006. j0 = i * width1;
  5007. if (data[pos - lineSize] !== data[pos]) {
  5008. points[j0] = data[pos] ? 1 : 8;
  5009. ++count;
  5010. }
  5011. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5012. for (j = 1; j < width; j++) {
  5013. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  5014. if (POINT_TYPES[sum]) {
  5015. points[j0 + j] = POINT_TYPES[sum];
  5016. ++count;
  5017. }
  5018. pos++;
  5019. }
  5020. if (data[pos - lineSize] !== data[pos]) {
  5021. points[j0 + j] = data[pos] ? 2 : 4;
  5022. ++count;
  5023. }
  5024. if (count > POINT_TO_PROCESS_LIMIT) {
  5025. return null;
  5026. }
  5027. }
  5028. pos = lineSize * (height - 1);
  5029. j0 = i * width1;
  5030. if (data[pos] !== 0) {
  5031. points[j0] = 8;
  5032. ++count;
  5033. }
  5034. for (j = 1; j < width; j++) {
  5035. if (data[pos] !== data[pos + 1]) {
  5036. points[j0 + j] = data[pos] ? 4 : 8;
  5037. ++count;
  5038. }
  5039. pos++;
  5040. }
  5041. if (data[pos] !== 0) {
  5042. points[j0 + j] = 4;
  5043. ++count;
  5044. }
  5045. if (count > POINT_TO_PROCESS_LIMIT) {
  5046. return null;
  5047. }
  5048. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5049. const path = new Path2D();
  5050. for (i = 0; count && i <= height; i++) {
  5051. let p = i * width1;
  5052. const end = p + width;
  5053. while (p < end && !points[p]) {
  5054. p++;
  5055. }
  5056. if (p === end) {
  5057. continue;
  5058. }
  5059. path.moveTo(p % width1, i);
  5060. const p0 = p;
  5061. let type = points[p];
  5062. do {
  5063. const step = steps[type];
  5064. do {
  5065. p += step;
  5066. } while (!points[p]);
  5067. const pp = points[p];
  5068. if (pp !== 5 && pp !== 10) {
  5069. type = pp;
  5070. points[p] = 0;
  5071. } else {
  5072. type = pp & 0x33 * type >> 4;
  5073. points[p] &= type >> 2 | type << 2;
  5074. }
  5075. path.lineTo(p % width1, p / width1 | 0);
  5076. if (!points[p]) {
  5077. --count;
  5078. }
  5079. } while (p0 !== p);
  5080. --i;
  5081. }
  5082. data = null;
  5083. points = null;
  5084. const drawOutline = function (c) {
  5085. c.save();
  5086. c.scale(1 / width, -1 / height);
  5087. c.translate(0, -height);
  5088. c.fill(path);
  5089. c.beginPath();
  5090. c.restore();
  5091. };
  5092. return drawOutline;
  5093. }
  5094. class CanvasExtraState {
  5095. constructor(width, height) {
  5096. this.alphaIsShape = false;
  5097. this.fontSize = 0;
  5098. this.fontSizeScale = 1;
  5099. this.textMatrix = _util.IDENTITY_MATRIX;
  5100. this.textMatrixScale = 1;
  5101. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  5102. this.leading = 0;
  5103. this.x = 0;
  5104. this.y = 0;
  5105. this.lineX = 0;
  5106. this.lineY = 0;
  5107. this.charSpacing = 0;
  5108. this.wordSpacing = 0;
  5109. this.textHScale = 1;
  5110. this.textRenderingMode = _util.TextRenderingMode.FILL;
  5111. this.textRise = 0;
  5112. this.fillColor = "#000000";
  5113. this.strokeColor = "#000000";
  5114. this.patternFill = false;
  5115. this.fillAlpha = 1;
  5116. this.strokeAlpha = 1;
  5117. this.lineWidth = 1;
  5118. this.activeSMask = null;
  5119. this.transferMaps = null;
  5120. this.startNewPathAndClipBox([0, 0, width, height]);
  5121. }
  5122. clone() {
  5123. const clone = Object.create(this);
  5124. clone.clipBox = this.clipBox.slice();
  5125. return clone;
  5126. }
  5127. setCurrentPoint(x, y) {
  5128. this.x = x;
  5129. this.y = y;
  5130. }
  5131. updatePathMinMax(transform, x, y) {
  5132. [x, y] = _util.Util.applyTransform([x, y], transform);
  5133. this.minX = Math.min(this.minX, x);
  5134. this.minY = Math.min(this.minY, y);
  5135. this.maxX = Math.max(this.maxX, x);
  5136. this.maxY = Math.max(this.maxY, y);
  5137. }
  5138. updateRectMinMax(transform, rect) {
  5139. const p1 = _util.Util.applyTransform(rect, transform);
  5140. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  5141. this.minX = Math.min(this.minX, p1[0], p2[0]);
  5142. this.minY = Math.min(this.minY, p1[1], p2[1]);
  5143. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  5144. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  5145. }
  5146. updateScalingPathMinMax(transform, minMax) {
  5147. _util.Util.scaleMinMax(transform, minMax);
  5148. this.minX = Math.min(this.minX, minMax[0]);
  5149. this.maxX = Math.max(this.maxX, minMax[1]);
  5150. this.minY = Math.min(this.minY, minMax[2]);
  5151. this.maxY = Math.max(this.maxY, minMax[3]);
  5152. }
  5153. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  5154. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  5155. if (minMax) {
  5156. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  5157. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  5158. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  5159. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  5160. return;
  5161. }
  5162. this.updateRectMinMax(transform, box);
  5163. }
  5164. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5165. const box = [this.minX, this.minY, this.maxX, this.maxY];
  5166. if (pathType === _pattern_helper.PathType.STROKE) {
  5167. if (!transform) {
  5168. (0, _util.unreachable)("Stroke bounding box must include transform.");
  5169. }
  5170. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5171. const xStrokePad = scale[0] * this.lineWidth / 2;
  5172. const yStrokePad = scale[1] * this.lineWidth / 2;
  5173. box[0] -= xStrokePad;
  5174. box[1] -= yStrokePad;
  5175. box[2] += xStrokePad;
  5176. box[3] += yStrokePad;
  5177. }
  5178. return box;
  5179. }
  5180. updateClipFromPath() {
  5181. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  5182. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  5183. }
  5184. isEmptyClip() {
  5185. return this.minX === Infinity;
  5186. }
  5187. startNewPathAndClipBox(box) {
  5188. this.clipBox = box;
  5189. this.minX = Infinity;
  5190. this.minY = Infinity;
  5191. this.maxX = 0;
  5192. this.maxY = 0;
  5193. }
  5194. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5195. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  5196. }
  5197. }
  5198. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  5199. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  5200. ctx.putImageData(imgData, 0, 0);
  5201. return;
  5202. }
  5203. const height = imgData.height,
  5204. width = imgData.width;
  5205. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5206. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5207. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5208. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5209. let srcPos = 0,
  5210. destPos;
  5211. const src = imgData.data;
  5212. const dest = chunkImgData.data;
  5213. let i, j, thisChunkHeight, elemsInThisChunk;
  5214. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  5215. if (transferMaps) {
  5216. switch (transferMaps.length) {
  5217. case 1:
  5218. transferMapRed = transferMaps[0];
  5219. transferMapGreen = transferMaps[0];
  5220. transferMapBlue = transferMaps[0];
  5221. transferMapGray = transferMaps[0];
  5222. break;
  5223. case 4:
  5224. transferMapRed = transferMaps[0];
  5225. transferMapGreen = transferMaps[1];
  5226. transferMapBlue = transferMaps[2];
  5227. transferMapGray = transferMaps[3];
  5228. break;
  5229. }
  5230. }
  5231. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  5232. const srcLength = src.byteLength;
  5233. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  5234. const dest32DataLength = dest32.length;
  5235. const fullSrcDiff = width + 7 >> 3;
  5236. let white = 0xffffffff;
  5237. let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  5238. if (transferMapGray) {
  5239. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  5240. [white, black] = [black, white];
  5241. }
  5242. }
  5243. for (i = 0; i < totalChunks; i++) {
  5244. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5245. destPos = 0;
  5246. for (j = 0; j < thisChunkHeight; j++) {
  5247. const srcDiff = srcLength - srcPos;
  5248. let k = 0;
  5249. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  5250. const kEndUnrolled = kEnd & ~7;
  5251. let mask = 0;
  5252. let srcByte = 0;
  5253. for (; k < kEndUnrolled; k += 8) {
  5254. srcByte = src[srcPos++];
  5255. dest32[destPos++] = srcByte & 128 ? white : black;
  5256. dest32[destPos++] = srcByte & 64 ? white : black;
  5257. dest32[destPos++] = srcByte & 32 ? white : black;
  5258. dest32[destPos++] = srcByte & 16 ? white : black;
  5259. dest32[destPos++] = srcByte & 8 ? white : black;
  5260. dest32[destPos++] = srcByte & 4 ? white : black;
  5261. dest32[destPos++] = srcByte & 2 ? white : black;
  5262. dest32[destPos++] = srcByte & 1 ? white : black;
  5263. }
  5264. for (; k < kEnd; k++) {
  5265. if (mask === 0) {
  5266. srcByte = src[srcPos++];
  5267. mask = 128;
  5268. }
  5269. dest32[destPos++] = srcByte & mask ? white : black;
  5270. mask >>= 1;
  5271. }
  5272. }
  5273. while (destPos < dest32DataLength) {
  5274. dest32[destPos++] = 0;
  5275. }
  5276. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5277. }
  5278. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  5279. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5280. j = 0;
  5281. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5282. for (i = 0; i < fullChunks; i++) {
  5283. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5284. srcPos += elemsInThisChunk;
  5285. if (hasTransferMaps) {
  5286. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5287. if (transferMapRed) {
  5288. dest[k + 0] = transferMapRed[dest[k + 0]];
  5289. }
  5290. if (transferMapGreen) {
  5291. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5292. }
  5293. if (transferMapBlue) {
  5294. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5295. }
  5296. }
  5297. }
  5298. ctx.putImageData(chunkImgData, 0, j);
  5299. j += FULL_CHUNK_HEIGHT;
  5300. }
  5301. if (i < totalChunks) {
  5302. elemsInThisChunk = width * partialChunkHeight * 4;
  5303. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5304. if (hasTransferMaps) {
  5305. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5306. if (transferMapRed) {
  5307. dest[k + 0] = transferMapRed[dest[k + 0]];
  5308. }
  5309. if (transferMapGreen) {
  5310. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5311. }
  5312. if (transferMapBlue) {
  5313. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5314. }
  5315. }
  5316. }
  5317. ctx.putImageData(chunkImgData, 0, j);
  5318. }
  5319. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  5320. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5321. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5322. elemsInThisChunk = width * thisChunkHeight;
  5323. for (i = 0; i < totalChunks; i++) {
  5324. if (i >= fullChunks) {
  5325. thisChunkHeight = partialChunkHeight;
  5326. elemsInThisChunk = width * thisChunkHeight;
  5327. }
  5328. destPos = 0;
  5329. for (j = elemsInThisChunk; j--;) {
  5330. dest[destPos++] = src[srcPos++];
  5331. dest[destPos++] = src[srcPos++];
  5332. dest[destPos++] = src[srcPos++];
  5333. dest[destPos++] = 255;
  5334. }
  5335. if (hasTransferMaps) {
  5336. for (let k = 0; k < destPos; k += 4) {
  5337. if (transferMapRed) {
  5338. dest[k + 0] = transferMapRed[dest[k + 0]];
  5339. }
  5340. if (transferMapGreen) {
  5341. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5342. }
  5343. if (transferMapBlue) {
  5344. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5345. }
  5346. }
  5347. }
  5348. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5349. }
  5350. } else {
  5351. throw new Error(`bad image kind: ${imgData.kind}`);
  5352. }
  5353. }
  5354. function putBinaryImageMask(ctx, imgData) {
  5355. if (imgData.bitmap) {
  5356. ctx.drawImage(imgData.bitmap, 0, 0);
  5357. return;
  5358. }
  5359. const height = imgData.height,
  5360. width = imgData.width;
  5361. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5362. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5363. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5364. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5365. let srcPos = 0;
  5366. const src = imgData.data;
  5367. const dest = chunkImgData.data;
  5368. for (let i = 0; i < totalChunks; i++) {
  5369. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5370. ({
  5371. srcPos
  5372. } = (0, _image_utils.applyMaskImageData)({
  5373. src,
  5374. srcPos,
  5375. dest,
  5376. width,
  5377. height: thisChunkHeight
  5378. }));
  5379. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5380. }
  5381. }
  5382. function copyCtxState(sourceCtx, destCtx) {
  5383. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  5384. for (const property of properties) {
  5385. if (sourceCtx[property] !== undefined) {
  5386. destCtx[property] = sourceCtx[property];
  5387. }
  5388. }
  5389. if (sourceCtx.setLineDash !== undefined) {
  5390. destCtx.setLineDash(sourceCtx.getLineDash());
  5391. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5392. }
  5393. }
  5394. function resetCtxToDefault(ctx, foregroundColor) {
  5395. ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  5396. ctx.fillRule = "nonzero";
  5397. ctx.globalAlpha = 1;
  5398. ctx.lineWidth = 1;
  5399. ctx.lineCap = "butt";
  5400. ctx.lineJoin = "miter";
  5401. ctx.miterLimit = 10;
  5402. ctx.globalCompositeOperation = "source-over";
  5403. ctx.font = "10px sans-serif";
  5404. if (ctx.setLineDash !== undefined) {
  5405. ctx.setLineDash([]);
  5406. ctx.lineDashOffset = 0;
  5407. }
  5408. }
  5409. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5410. const length = bytes.length;
  5411. for (let i = 3; i < length; i += 4) {
  5412. const alpha = bytes[i];
  5413. if (alpha === 0) {
  5414. bytes[i - 3] = r0;
  5415. bytes[i - 2] = g0;
  5416. bytes[i - 1] = b0;
  5417. } else if (alpha < 255) {
  5418. const alpha_ = 255 - alpha;
  5419. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  5420. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  5421. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  5422. }
  5423. }
  5424. }
  5425. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5426. const length = maskData.length;
  5427. const scale = 1 / 255;
  5428. for (let i = 3; i < length; i += 4) {
  5429. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5430. layerData[i] = layerData[i] * alpha * scale | 0;
  5431. }
  5432. }
  5433. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5434. const length = maskData.length;
  5435. for (let i = 3; i < length; i += 4) {
  5436. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  5437. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  5438. }
  5439. }
  5440. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  5441. const hasBackdrop = !!backdrop;
  5442. const r0 = hasBackdrop ? backdrop[0] : 0;
  5443. const g0 = hasBackdrop ? backdrop[1] : 0;
  5444. const b0 = hasBackdrop ? backdrop[2] : 0;
  5445. let composeFn;
  5446. if (subtype === "Luminosity") {
  5447. composeFn = composeSMaskLuminosity;
  5448. } else {
  5449. composeFn = composeSMaskAlpha;
  5450. }
  5451. const PIXELS_TO_PROCESS = 1048576;
  5452. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5453. for (let row = 0; row < height; row += chunkSize) {
  5454. const chunkHeight = Math.min(chunkSize, height - row);
  5455. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  5456. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  5457. if (hasBackdrop) {
  5458. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5459. }
  5460. composeFn(maskData.data, layerData.data, transferMap);
  5461. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  5462. }
  5463. }
  5464. function composeSMask(ctx, smask, layerCtx, layerBox) {
  5465. const layerOffsetX = layerBox[0];
  5466. const layerOffsetY = layerBox[1];
  5467. const layerWidth = layerBox[2] - layerOffsetX;
  5468. const layerHeight = layerBox[3] - layerOffsetY;
  5469. if (layerWidth === 0 || layerHeight === 0) {
  5470. return;
  5471. }
  5472. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  5473. ctx.save();
  5474. ctx.globalAlpha = 1;
  5475. ctx.globalCompositeOperation = "source-over";
  5476. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5477. ctx.drawImage(layerCtx.canvas, 0, 0);
  5478. ctx.restore();
  5479. }
  5480. function getImageSmoothingEnabled(transform, interpolate) {
  5481. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5482. scale[0] = Math.fround(scale[0]);
  5483. scale[1] = Math.fround(scale[1]);
  5484. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  5485. if (interpolate !== undefined) {
  5486. return interpolate;
  5487. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  5488. return true;
  5489. }
  5490. return false;
  5491. }
  5492. const LINE_CAP_STYLES = ["butt", "round", "square"];
  5493. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  5494. const NORMAL_CLIP = {};
  5495. const EO_CLIP = {};
  5496. class CanvasGraphics {
  5497. constructor(canvasCtx, commonObjs, objs, canvasFactory, optionalContentConfig, annotationCanvasMap, pageColors) {
  5498. this.ctx = canvasCtx;
  5499. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  5500. this.stateStack = [];
  5501. this.pendingClip = null;
  5502. this.pendingEOFill = false;
  5503. this.res = null;
  5504. this.xobjs = null;
  5505. this.commonObjs = commonObjs;
  5506. this.objs = objs;
  5507. this.canvasFactory = canvasFactory;
  5508. this.groupStack = [];
  5509. this.processingType3 = null;
  5510. this.baseTransform = null;
  5511. this.baseTransformStack = [];
  5512. this.groupLevel = 0;
  5513. this.smaskStack = [];
  5514. this.smaskCounter = 0;
  5515. this.tempSMask = null;
  5516. this.suspendedCtx = null;
  5517. this.contentVisible = true;
  5518. this.markedContentStack = [];
  5519. this.optionalContentConfig = optionalContentConfig;
  5520. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  5521. this.cachedPatterns = new Map();
  5522. this.annotationCanvasMap = annotationCanvasMap;
  5523. this.viewportScale = 1;
  5524. this.outputScaleX = 1;
  5525. this.outputScaleY = 1;
  5526. this.backgroundColor = pageColors?.background || null;
  5527. this.foregroundColor = pageColors?.foreground || null;
  5528. this._cachedScaleForStroking = null;
  5529. this._cachedGetSinglePixelWidth = null;
  5530. this._cachedBitmapsMap = new Map();
  5531. }
  5532. getObject(data, fallback = null) {
  5533. if (typeof data === "string") {
  5534. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  5535. }
  5536. return fallback;
  5537. }
  5538. beginDrawing({
  5539. transform,
  5540. viewport,
  5541. transparency = false,
  5542. background = null
  5543. }) {
  5544. const width = this.ctx.canvas.width;
  5545. const height = this.ctx.canvas.height;
  5546. const defaultBackgroundColor = background || "#ffffff";
  5547. this.ctx.save();
  5548. if (this.foregroundColor && this.backgroundColor) {
  5549. this.ctx.fillStyle = this.foregroundColor;
  5550. const fg = this.foregroundColor = this.ctx.fillStyle;
  5551. this.ctx.fillStyle = this.backgroundColor;
  5552. const bg = this.backgroundColor = this.ctx.fillStyle;
  5553. let isValidDefaultBg = true;
  5554. let defaultBg = defaultBackgroundColor;
  5555. this.ctx.fillStyle = defaultBackgroundColor;
  5556. defaultBg = this.ctx.fillStyle;
  5557. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  5558. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  5559. this.foregroundColor = this.backgroundColor = null;
  5560. } else {
  5561. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  5562. const newComp = x => {
  5563. x /= 255;
  5564. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  5565. };
  5566. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  5567. this.selectColor = (r, g, b) => {
  5568. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  5569. return Math.round(lumC) === lumB ? bg : fg;
  5570. };
  5571. }
  5572. }
  5573. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  5574. this.ctx.fillRect(0, 0, width, height);
  5575. this.ctx.restore();
  5576. if (transparency) {
  5577. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  5578. this.compositeCtx = this.ctx;
  5579. this.transparentCanvas = transparentCanvas.canvas;
  5580. this.ctx = transparentCanvas.context;
  5581. this.ctx.save();
  5582. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  5583. }
  5584. this.ctx.save();
  5585. resetCtxToDefault(this.ctx, this.foregroundColor);
  5586. if (transform) {
  5587. this.ctx.transform(...transform);
  5588. this.outputScaleX = transform[0];
  5589. this.outputScaleY = transform[0];
  5590. }
  5591. this.ctx.transform(...viewport.transform);
  5592. this.viewportScale = viewport.scale;
  5593. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  5594. }
  5595. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  5596. const argsArray = operatorList.argsArray;
  5597. const fnArray = operatorList.fnArray;
  5598. let i = executionStartIdx || 0;
  5599. const argsArrayLen = argsArray.length;
  5600. if (argsArrayLen === i) {
  5601. return i;
  5602. }
  5603. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  5604. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  5605. let steps = 0;
  5606. const commonObjs = this.commonObjs;
  5607. const objs = this.objs;
  5608. let fnId;
  5609. while (true) {
  5610. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  5611. stepper.breakIt(i, continueCallback);
  5612. return i;
  5613. }
  5614. fnId = fnArray[i];
  5615. if (fnId !== _util.OPS.dependency) {
  5616. this[fnId].apply(this, argsArray[i]);
  5617. } else {
  5618. for (const depObjId of argsArray[i]) {
  5619. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  5620. if (!objsPool.has(depObjId)) {
  5621. objsPool.get(depObjId, continueCallback);
  5622. return i;
  5623. }
  5624. }
  5625. }
  5626. i++;
  5627. if (i === argsArrayLen) {
  5628. return i;
  5629. }
  5630. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  5631. if (Date.now() > endTime) {
  5632. continueCallback();
  5633. return i;
  5634. }
  5635. steps = 0;
  5636. }
  5637. }
  5638. }
  5639. #restoreInitialState() {
  5640. while (this.stateStack.length || this.inSMaskMode) {
  5641. this.restore();
  5642. }
  5643. this.ctx.restore();
  5644. if (this.transparentCanvas) {
  5645. this.ctx = this.compositeCtx;
  5646. this.ctx.save();
  5647. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5648. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  5649. this.ctx.restore();
  5650. this.transparentCanvas = null;
  5651. }
  5652. }
  5653. endDrawing() {
  5654. this.#restoreInitialState();
  5655. this.cachedCanvases.clear();
  5656. this.cachedPatterns.clear();
  5657. for (const cache of this._cachedBitmapsMap.values()) {
  5658. for (const canvas of cache.values()) {
  5659. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  5660. canvas.width = canvas.height = 0;
  5661. }
  5662. }
  5663. cache.clear();
  5664. }
  5665. this._cachedBitmapsMap.clear();
  5666. }
  5667. _scaleImage(img, inverseTransform) {
  5668. const width = img.width;
  5669. const height = img.height;
  5670. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  5671. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  5672. let paintWidth = width,
  5673. paintHeight = height;
  5674. let tmpCanvasId = "prescale1";
  5675. let tmpCanvas, tmpCtx;
  5676. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5677. let newWidth = paintWidth,
  5678. newHeight = paintHeight;
  5679. if (widthScale > 2 && paintWidth > 1) {
  5680. newWidth = Math.ceil(paintWidth / 2);
  5681. widthScale /= paintWidth / newWidth;
  5682. }
  5683. if (heightScale > 2 && paintHeight > 1) {
  5684. newHeight = Math.ceil(paintHeight / 2);
  5685. heightScale /= paintHeight / newHeight;
  5686. }
  5687. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5688. tmpCtx = tmpCanvas.context;
  5689. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5690. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5691. img = tmpCanvas.canvas;
  5692. paintWidth = newWidth;
  5693. paintHeight = newHeight;
  5694. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5695. }
  5696. return {
  5697. img,
  5698. paintWidth,
  5699. paintHeight
  5700. };
  5701. }
  5702. _createMaskCanvas(img) {
  5703. const ctx = this.ctx;
  5704. const {
  5705. width,
  5706. height
  5707. } = img;
  5708. const fillColor = this.current.fillColor;
  5709. const isPatternFill = this.current.patternFill;
  5710. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5711. let cache, cacheKey, scaled, maskCanvas;
  5712. if ((img.bitmap || img.data) && img.count > 1) {
  5713. const mainKey = img.bitmap || img.data.buffer;
  5714. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  5715. cache = this._cachedBitmapsMap.get(mainKey);
  5716. if (!cache) {
  5717. cache = new Map();
  5718. this._cachedBitmapsMap.set(mainKey, cache);
  5719. }
  5720. const cachedImage = cache.get(cacheKey);
  5721. if (cachedImage && !isPatternFill) {
  5722. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  5723. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  5724. return {
  5725. canvas: cachedImage,
  5726. offsetX,
  5727. offsetY
  5728. };
  5729. }
  5730. scaled = cachedImage;
  5731. }
  5732. if (!scaled) {
  5733. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5734. putBinaryImageMask(maskCanvas.context, img);
  5735. }
  5736. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  5737. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  5738. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  5739. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  5740. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  5741. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  5742. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  5743. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  5744. const fillCtx = fillCanvas.context;
  5745. const offsetX = Math.min(cord1[0], cord2[0]);
  5746. const offsetY = Math.min(cord1[1], cord2[1]);
  5747. fillCtx.translate(-offsetX, -offsetY);
  5748. fillCtx.transform(...maskToCanvas);
  5749. if (!scaled) {
  5750. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  5751. scaled = scaled.img;
  5752. if (cache && isPatternFill) {
  5753. cache.set(cacheKey, scaled);
  5754. }
  5755. }
  5756. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  5757. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  5758. fillCtx.globalCompositeOperation = "source-in";
  5759. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  5760. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  5761. fillCtx.fillRect(0, 0, width, height);
  5762. if (cache && !isPatternFill) {
  5763. this.cachedCanvases.delete("fillCanvas");
  5764. cache.set(cacheKey, fillCanvas.canvas);
  5765. }
  5766. return {
  5767. canvas: fillCanvas.canvas,
  5768. offsetX: Math.round(offsetX),
  5769. offsetY: Math.round(offsetY)
  5770. };
  5771. }
  5772. setLineWidth(width) {
  5773. if (width !== this.current.lineWidth) {
  5774. this._cachedScaleForStroking = null;
  5775. }
  5776. this.current.lineWidth = width;
  5777. this.ctx.lineWidth = width;
  5778. }
  5779. setLineCap(style) {
  5780. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5781. }
  5782. setLineJoin(style) {
  5783. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5784. }
  5785. setMiterLimit(limit) {
  5786. this.ctx.miterLimit = limit;
  5787. }
  5788. setDash(dashArray, dashPhase) {
  5789. const ctx = this.ctx;
  5790. if (ctx.setLineDash !== undefined) {
  5791. ctx.setLineDash(dashArray);
  5792. ctx.lineDashOffset = dashPhase;
  5793. }
  5794. }
  5795. setRenderingIntent(intent) {}
  5796. setFlatness(flatness) {}
  5797. setGState(states) {
  5798. for (const [key, value] of states) {
  5799. switch (key) {
  5800. case "LW":
  5801. this.setLineWidth(value);
  5802. break;
  5803. case "LC":
  5804. this.setLineCap(value);
  5805. break;
  5806. case "LJ":
  5807. this.setLineJoin(value);
  5808. break;
  5809. case "ML":
  5810. this.setMiterLimit(value);
  5811. break;
  5812. case "D":
  5813. this.setDash(value[0], value[1]);
  5814. break;
  5815. case "RI":
  5816. this.setRenderingIntent(value);
  5817. break;
  5818. case "FL":
  5819. this.setFlatness(value);
  5820. break;
  5821. case "Font":
  5822. this.setFont(value[0], value[1]);
  5823. break;
  5824. case "CA":
  5825. this.current.strokeAlpha = value;
  5826. break;
  5827. case "ca":
  5828. this.current.fillAlpha = value;
  5829. this.ctx.globalAlpha = value;
  5830. break;
  5831. case "BM":
  5832. this.ctx.globalCompositeOperation = value;
  5833. break;
  5834. case "SMask":
  5835. this.current.activeSMask = value ? this.tempSMask : null;
  5836. this.tempSMask = null;
  5837. this.checkSMaskState();
  5838. break;
  5839. case "TR":
  5840. this.current.transferMaps = value;
  5841. }
  5842. }
  5843. }
  5844. get inSMaskMode() {
  5845. return !!this.suspendedCtx;
  5846. }
  5847. checkSMaskState() {
  5848. const inSMaskMode = this.inSMaskMode;
  5849. if (this.current.activeSMask && !inSMaskMode) {
  5850. this.beginSMaskMode();
  5851. } else if (!this.current.activeSMask && inSMaskMode) {
  5852. this.endSMaskMode();
  5853. }
  5854. }
  5855. beginSMaskMode() {
  5856. if (this.inSMaskMode) {
  5857. throw new Error("beginSMaskMode called while already in smask mode");
  5858. }
  5859. const drawnWidth = this.ctx.canvas.width;
  5860. const drawnHeight = this.ctx.canvas.height;
  5861. const cacheId = "smaskGroupAt" + this.groupLevel;
  5862. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  5863. this.suspendedCtx = this.ctx;
  5864. this.ctx = scratchCanvas.context;
  5865. const ctx = this.ctx;
  5866. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  5867. copyCtxState(this.suspendedCtx, ctx);
  5868. mirrorContextOperations(ctx, this.suspendedCtx);
  5869. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5870. }
  5871. endSMaskMode() {
  5872. if (!this.inSMaskMode) {
  5873. throw new Error("endSMaskMode called while not in smask mode");
  5874. }
  5875. this.ctx._removeMirroring();
  5876. copyCtxState(this.ctx, this.suspendedCtx);
  5877. this.ctx = this.suspendedCtx;
  5878. this.suspendedCtx = null;
  5879. }
  5880. compose(dirtyBox) {
  5881. if (!this.current.activeSMask) {
  5882. return;
  5883. }
  5884. if (!dirtyBox) {
  5885. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  5886. } else {
  5887. dirtyBox[0] = Math.floor(dirtyBox[0]);
  5888. dirtyBox[1] = Math.floor(dirtyBox[1]);
  5889. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  5890. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  5891. }
  5892. const smask = this.current.activeSMask;
  5893. const suspendedCtx = this.suspendedCtx;
  5894. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  5895. this.ctx.save();
  5896. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5897. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  5898. this.ctx.restore();
  5899. }
  5900. save() {
  5901. if (this.inSMaskMode) {
  5902. copyCtxState(this.ctx, this.suspendedCtx);
  5903. this.suspendedCtx.save();
  5904. } else {
  5905. this.ctx.save();
  5906. }
  5907. const old = this.current;
  5908. this.stateStack.push(old);
  5909. this.current = old.clone();
  5910. }
  5911. restore() {
  5912. if (this.stateStack.length === 0 && this.inSMaskMode) {
  5913. this.endSMaskMode();
  5914. }
  5915. if (this.stateStack.length !== 0) {
  5916. this.current = this.stateStack.pop();
  5917. if (this.inSMaskMode) {
  5918. this.suspendedCtx.restore();
  5919. copyCtxState(this.suspendedCtx, this.ctx);
  5920. } else {
  5921. this.ctx.restore();
  5922. }
  5923. this.checkSMaskState();
  5924. this.pendingClip = null;
  5925. this._cachedScaleForStroking = null;
  5926. this._cachedGetSinglePixelWidth = null;
  5927. }
  5928. }
  5929. transform(a, b, c, d, e, f) {
  5930. this.ctx.transform(a, b, c, d, e, f);
  5931. this._cachedScaleForStroking = null;
  5932. this._cachedGetSinglePixelWidth = null;
  5933. }
  5934. constructPath(ops, args, minMax) {
  5935. const ctx = this.ctx;
  5936. const current = this.current;
  5937. let x = current.x,
  5938. y = current.y;
  5939. let startX, startY;
  5940. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5941. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  5942. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  5943. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  5944. switch (ops[i] | 0) {
  5945. case _util.OPS.rectangle:
  5946. x = args[j++];
  5947. y = args[j++];
  5948. const width = args[j++];
  5949. const height = args[j++];
  5950. const xw = x + width;
  5951. const yh = y + height;
  5952. ctx.moveTo(x, y);
  5953. if (width === 0 || height === 0) {
  5954. ctx.lineTo(xw, yh);
  5955. } else {
  5956. ctx.lineTo(xw, y);
  5957. ctx.lineTo(xw, yh);
  5958. ctx.lineTo(x, yh);
  5959. }
  5960. if (!isScalingMatrix) {
  5961. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  5962. }
  5963. ctx.closePath();
  5964. break;
  5965. case _util.OPS.moveTo:
  5966. x = args[j++];
  5967. y = args[j++];
  5968. ctx.moveTo(x, y);
  5969. if (!isScalingMatrix) {
  5970. current.updatePathMinMax(currentTransform, x, y);
  5971. }
  5972. break;
  5973. case _util.OPS.lineTo:
  5974. x = args[j++];
  5975. y = args[j++];
  5976. ctx.lineTo(x, y);
  5977. if (!isScalingMatrix) {
  5978. current.updatePathMinMax(currentTransform, x, y);
  5979. }
  5980. break;
  5981. case _util.OPS.curveTo:
  5982. startX = x;
  5983. startY = y;
  5984. x = args[j + 4];
  5985. y = args[j + 5];
  5986. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  5987. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  5988. j += 6;
  5989. break;
  5990. case _util.OPS.curveTo2:
  5991. startX = x;
  5992. startY = y;
  5993. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  5994. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  5995. x = args[j + 2];
  5996. y = args[j + 3];
  5997. j += 4;
  5998. break;
  5999. case _util.OPS.curveTo3:
  6000. startX = x;
  6001. startY = y;
  6002. x = args[j + 2];
  6003. y = args[j + 3];
  6004. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6005. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  6006. j += 4;
  6007. break;
  6008. case _util.OPS.closePath:
  6009. ctx.closePath();
  6010. break;
  6011. }
  6012. }
  6013. if (isScalingMatrix) {
  6014. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  6015. }
  6016. current.setCurrentPoint(x, y);
  6017. }
  6018. closePath() {
  6019. this.ctx.closePath();
  6020. }
  6021. stroke(consumePath) {
  6022. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6023. const ctx = this.ctx;
  6024. const strokeColor = this.current.strokeColor;
  6025. ctx.globalAlpha = this.current.strokeAlpha;
  6026. if (this.contentVisible) {
  6027. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  6028. ctx.save();
  6029. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  6030. this.rescaleAndStroke(false);
  6031. ctx.restore();
  6032. } else {
  6033. this.rescaleAndStroke(true);
  6034. }
  6035. }
  6036. if (consumePath) {
  6037. this.consumePath(this.current.getClippedPathBoundingBox());
  6038. }
  6039. ctx.globalAlpha = this.current.fillAlpha;
  6040. }
  6041. closeStroke() {
  6042. this.closePath();
  6043. this.stroke();
  6044. }
  6045. fill(consumePath) {
  6046. consumePath = typeof consumePath !== "undefined" ? consumePath : true;
  6047. const ctx = this.ctx;
  6048. const fillColor = this.current.fillColor;
  6049. const isPatternFill = this.current.patternFill;
  6050. let needRestore = false;
  6051. if (isPatternFill) {
  6052. ctx.save();
  6053. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6054. needRestore = true;
  6055. }
  6056. const intersect = this.current.getClippedPathBoundingBox();
  6057. if (this.contentVisible && intersect !== null) {
  6058. if (this.pendingEOFill) {
  6059. ctx.fill("evenodd");
  6060. this.pendingEOFill = false;
  6061. } else {
  6062. ctx.fill();
  6063. }
  6064. }
  6065. if (needRestore) {
  6066. ctx.restore();
  6067. }
  6068. if (consumePath) {
  6069. this.consumePath(intersect);
  6070. }
  6071. }
  6072. eoFill() {
  6073. this.pendingEOFill = true;
  6074. this.fill();
  6075. }
  6076. fillStroke() {
  6077. this.fill(false);
  6078. this.stroke(false);
  6079. this.consumePath();
  6080. }
  6081. eoFillStroke() {
  6082. this.pendingEOFill = true;
  6083. this.fillStroke();
  6084. }
  6085. closeFillStroke() {
  6086. this.closePath();
  6087. this.fillStroke();
  6088. }
  6089. closeEOFillStroke() {
  6090. this.pendingEOFill = true;
  6091. this.closePath();
  6092. this.fillStroke();
  6093. }
  6094. endPath() {
  6095. this.consumePath();
  6096. }
  6097. clip() {
  6098. this.pendingClip = NORMAL_CLIP;
  6099. }
  6100. eoClip() {
  6101. this.pendingClip = EO_CLIP;
  6102. }
  6103. beginText() {
  6104. this.current.textMatrix = _util.IDENTITY_MATRIX;
  6105. this.current.textMatrixScale = 1;
  6106. this.current.x = this.current.lineX = 0;
  6107. this.current.y = this.current.lineY = 0;
  6108. }
  6109. endText() {
  6110. const paths = this.pendingTextPaths;
  6111. const ctx = this.ctx;
  6112. if (paths === undefined) {
  6113. ctx.beginPath();
  6114. return;
  6115. }
  6116. ctx.save();
  6117. ctx.beginPath();
  6118. for (const path of paths) {
  6119. ctx.setTransform(...path.transform);
  6120. ctx.translate(path.x, path.y);
  6121. path.addToPath(ctx, path.fontSize);
  6122. }
  6123. ctx.restore();
  6124. ctx.clip();
  6125. ctx.beginPath();
  6126. delete this.pendingTextPaths;
  6127. }
  6128. setCharSpacing(spacing) {
  6129. this.current.charSpacing = spacing;
  6130. }
  6131. setWordSpacing(spacing) {
  6132. this.current.wordSpacing = spacing;
  6133. }
  6134. setHScale(scale) {
  6135. this.current.textHScale = scale / 100;
  6136. }
  6137. setLeading(leading) {
  6138. this.current.leading = -leading;
  6139. }
  6140. setFont(fontRefName, size) {
  6141. const fontObj = this.commonObjs.get(fontRefName);
  6142. const current = this.current;
  6143. if (!fontObj) {
  6144. throw new Error(`Can't find font for ${fontRefName}`);
  6145. }
  6146. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6147. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6148. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  6149. }
  6150. if (size < 0) {
  6151. size = -size;
  6152. current.fontDirection = -1;
  6153. } else {
  6154. current.fontDirection = 1;
  6155. }
  6156. this.current.font = fontObj;
  6157. this.current.fontSize = size;
  6158. if (fontObj.isType3Font) {
  6159. return;
  6160. }
  6161. const name = fontObj.loadedName || "sans-serif";
  6162. let bold = "normal";
  6163. if (fontObj.black) {
  6164. bold = "900";
  6165. } else if (fontObj.bold) {
  6166. bold = "bold";
  6167. }
  6168. const italic = fontObj.italic ? "italic" : "normal";
  6169. const typeface = `"${name}", ${fontObj.fallbackName}`;
  6170. let browserFontSize = size;
  6171. if (size < MIN_FONT_SIZE) {
  6172. browserFontSize = MIN_FONT_SIZE;
  6173. } else if (size > MAX_FONT_SIZE) {
  6174. browserFontSize = MAX_FONT_SIZE;
  6175. }
  6176. this.current.fontSizeScale = size / browserFontSize;
  6177. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  6178. }
  6179. setTextRenderingMode(mode) {
  6180. this.current.textRenderingMode = mode;
  6181. }
  6182. setTextRise(rise) {
  6183. this.current.textRise = rise;
  6184. }
  6185. moveText(x, y) {
  6186. this.current.x = this.current.lineX += x;
  6187. this.current.y = this.current.lineY += y;
  6188. }
  6189. setLeadingMoveText(x, y) {
  6190. this.setLeading(-y);
  6191. this.moveText(x, y);
  6192. }
  6193. setTextMatrix(a, b, c, d, e, f) {
  6194. this.current.textMatrix = [a, b, c, d, e, f];
  6195. this.current.textMatrixScale = Math.hypot(a, b);
  6196. this.current.x = this.current.lineX = 0;
  6197. this.current.y = this.current.lineY = 0;
  6198. }
  6199. nextLine() {
  6200. this.moveText(0, this.current.leading);
  6201. }
  6202. paintChar(character, x, y, patternTransform) {
  6203. const ctx = this.ctx;
  6204. const current = this.current;
  6205. const font = current.font;
  6206. const textRenderingMode = current.textRenderingMode;
  6207. const fontSize = current.fontSize / current.fontSizeScale;
  6208. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6209. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  6210. const patternFill = current.patternFill && !font.missingFile;
  6211. let addToPath;
  6212. if (font.disableFontFace || isAddToPathSet || patternFill) {
  6213. addToPath = font.getPathGenerator(this.commonObjs, character);
  6214. }
  6215. if (font.disableFontFace || patternFill) {
  6216. ctx.save();
  6217. ctx.translate(x, y);
  6218. ctx.beginPath();
  6219. addToPath(ctx, fontSize);
  6220. if (patternTransform) {
  6221. ctx.setTransform(...patternTransform);
  6222. }
  6223. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6224. ctx.fill();
  6225. }
  6226. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6227. ctx.stroke();
  6228. }
  6229. ctx.restore();
  6230. } else {
  6231. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6232. ctx.fillText(character, x, y);
  6233. }
  6234. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6235. ctx.strokeText(character, x, y);
  6236. }
  6237. }
  6238. if (isAddToPathSet) {
  6239. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6240. paths.push({
  6241. transform: (0, _display_utils.getCurrentTransform)(ctx),
  6242. x,
  6243. y,
  6244. fontSize,
  6245. addToPath
  6246. });
  6247. }
  6248. }
  6249. get isFontSubpixelAAEnabled() {
  6250. const {
  6251. context: ctx
  6252. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  6253. ctx.scale(1.5, 1);
  6254. ctx.fillText("I", 0, 10);
  6255. const data = ctx.getImageData(0, 0, 10, 10).data;
  6256. let enabled = false;
  6257. for (let i = 3; i < data.length; i += 4) {
  6258. if (data[i] > 0 && data[i] < 255) {
  6259. enabled = true;
  6260. break;
  6261. }
  6262. }
  6263. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  6264. }
  6265. showText(glyphs) {
  6266. const current = this.current;
  6267. const font = current.font;
  6268. if (font.isType3Font) {
  6269. return this.showType3Text(glyphs);
  6270. }
  6271. const fontSize = current.fontSize;
  6272. if (fontSize === 0) {
  6273. return undefined;
  6274. }
  6275. const ctx = this.ctx;
  6276. const fontSizeScale = current.fontSizeScale;
  6277. const charSpacing = current.charSpacing;
  6278. const wordSpacing = current.wordSpacing;
  6279. const fontDirection = current.fontDirection;
  6280. const textHScale = current.textHScale * fontDirection;
  6281. const glyphsLength = glyphs.length;
  6282. const vertical = font.vertical;
  6283. const spacingDir = vertical ? 1 : -1;
  6284. const defaultVMetrics = font.defaultVMetrics;
  6285. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  6286. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  6287. ctx.save();
  6288. ctx.transform(...current.textMatrix);
  6289. ctx.translate(current.x, current.y + current.textRise);
  6290. if (fontDirection > 0) {
  6291. ctx.scale(textHScale, -1);
  6292. } else {
  6293. ctx.scale(textHScale, 1);
  6294. }
  6295. let patternTransform;
  6296. if (current.patternFill) {
  6297. ctx.save();
  6298. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6299. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6300. ctx.restore();
  6301. ctx.fillStyle = pattern;
  6302. }
  6303. let lineWidth = current.lineWidth;
  6304. const scale = current.textMatrixScale;
  6305. if (scale === 0 || lineWidth === 0) {
  6306. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6307. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6308. lineWidth = this.getSinglePixelWidth();
  6309. }
  6310. } else {
  6311. lineWidth /= scale;
  6312. }
  6313. if (fontSizeScale !== 1.0) {
  6314. ctx.scale(fontSizeScale, fontSizeScale);
  6315. lineWidth /= fontSizeScale;
  6316. }
  6317. ctx.lineWidth = lineWidth;
  6318. let x = 0,
  6319. i;
  6320. for (i = 0; i < glyphsLength; ++i) {
  6321. const glyph = glyphs[i];
  6322. if (typeof glyph === "number") {
  6323. x += spacingDir * glyph * fontSize / 1000;
  6324. continue;
  6325. }
  6326. let restoreNeeded = false;
  6327. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6328. const character = glyph.fontChar;
  6329. const accent = glyph.accent;
  6330. let scaledX, scaledY;
  6331. let width = glyph.width;
  6332. if (vertical) {
  6333. const vmetric = glyph.vmetric || defaultVMetrics;
  6334. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  6335. const vy = vmetric[2] * widthAdvanceScale;
  6336. width = vmetric ? -vmetric[0] : width;
  6337. scaledX = vx / fontSizeScale;
  6338. scaledY = (x + vy) / fontSizeScale;
  6339. } else {
  6340. scaledX = x / fontSizeScale;
  6341. scaledY = 0;
  6342. }
  6343. if (font.remeasure && width > 0) {
  6344. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6345. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6346. const characterScaleX = width / measuredWidth;
  6347. restoreNeeded = true;
  6348. ctx.save();
  6349. ctx.scale(characterScaleX, 1);
  6350. scaledX /= characterScaleX;
  6351. } else if (width !== measuredWidth) {
  6352. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6353. }
  6354. }
  6355. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  6356. if (simpleFillText && !accent) {
  6357. ctx.fillText(character, scaledX, scaledY);
  6358. } else {
  6359. this.paintChar(character, scaledX, scaledY, patternTransform);
  6360. if (accent) {
  6361. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  6362. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  6363. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  6364. }
  6365. }
  6366. }
  6367. let charWidth;
  6368. if (vertical) {
  6369. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  6370. } else {
  6371. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6372. }
  6373. x += charWidth;
  6374. if (restoreNeeded) {
  6375. ctx.restore();
  6376. }
  6377. }
  6378. if (vertical) {
  6379. current.y -= x;
  6380. } else {
  6381. current.x += x * textHScale;
  6382. }
  6383. ctx.restore();
  6384. this.compose();
  6385. return undefined;
  6386. }
  6387. showType3Text(glyphs) {
  6388. const ctx = this.ctx;
  6389. const current = this.current;
  6390. const font = current.font;
  6391. const fontSize = current.fontSize;
  6392. const fontDirection = current.fontDirection;
  6393. const spacingDir = font.vertical ? 1 : -1;
  6394. const charSpacing = current.charSpacing;
  6395. const wordSpacing = current.wordSpacing;
  6396. const textHScale = current.textHScale * fontDirection;
  6397. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6398. const glyphsLength = glyphs.length;
  6399. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  6400. let i, glyph, width, spacingLength;
  6401. if (isTextInvisible || fontSize === 0) {
  6402. return;
  6403. }
  6404. this._cachedScaleForStroking = null;
  6405. this._cachedGetSinglePixelWidth = null;
  6406. ctx.save();
  6407. ctx.transform(...current.textMatrix);
  6408. ctx.translate(current.x, current.y);
  6409. ctx.scale(textHScale, fontDirection);
  6410. for (i = 0; i < glyphsLength; ++i) {
  6411. glyph = glyphs[i];
  6412. if (typeof glyph === "number") {
  6413. spacingLength = spacingDir * glyph * fontSize / 1000;
  6414. this.ctx.translate(spacingLength, 0);
  6415. current.x += spacingLength * textHScale;
  6416. continue;
  6417. }
  6418. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6419. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  6420. if (!operatorList) {
  6421. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  6422. continue;
  6423. }
  6424. if (this.contentVisible) {
  6425. this.processingType3 = glyph;
  6426. this.save();
  6427. ctx.scale(fontSize, fontSize);
  6428. ctx.transform(...fontMatrix);
  6429. this.executeOperatorList(operatorList);
  6430. this.restore();
  6431. }
  6432. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  6433. width = transformed[0] * fontSize + spacing;
  6434. ctx.translate(width, 0);
  6435. current.x += width * textHScale;
  6436. }
  6437. ctx.restore();
  6438. this.processingType3 = null;
  6439. }
  6440. setCharWidth(xWidth, yWidth) {}
  6441. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  6442. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6443. this.ctx.clip();
  6444. this.endPath();
  6445. }
  6446. getColorN_Pattern(IR) {
  6447. let pattern;
  6448. if (IR[0] === "TilingPattern") {
  6449. const color = IR[1];
  6450. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  6451. const canvasGraphicsFactory = {
  6452. createCanvasGraphics: ctx => {
  6453. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
  6454. }
  6455. };
  6456. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  6457. } else {
  6458. pattern = this._getPattern(IR[1], IR[2]);
  6459. }
  6460. return pattern;
  6461. }
  6462. setStrokeColorN() {
  6463. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6464. }
  6465. setFillColorN() {
  6466. this.current.fillColor = this.getColorN_Pattern(arguments);
  6467. this.current.patternFill = true;
  6468. }
  6469. setStrokeRGBColor(r, g, b) {
  6470. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6471. this.ctx.strokeStyle = color;
  6472. this.current.strokeColor = color;
  6473. }
  6474. setFillRGBColor(r, g, b) {
  6475. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6476. this.ctx.fillStyle = color;
  6477. this.current.fillColor = color;
  6478. this.current.patternFill = false;
  6479. }
  6480. _getPattern(objId, matrix = null) {
  6481. let pattern;
  6482. if (this.cachedPatterns.has(objId)) {
  6483. pattern = this.cachedPatterns.get(objId);
  6484. } else {
  6485. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  6486. this.cachedPatterns.set(objId, pattern);
  6487. }
  6488. if (matrix) {
  6489. pattern.matrix = matrix;
  6490. }
  6491. return pattern;
  6492. }
  6493. shadingFill(objId) {
  6494. if (!this.contentVisible) {
  6495. return;
  6496. }
  6497. const ctx = this.ctx;
  6498. this.save();
  6499. const pattern = this._getPattern(objId);
  6500. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  6501. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  6502. if (inv) {
  6503. const canvas = ctx.canvas;
  6504. const width = canvas.width;
  6505. const height = canvas.height;
  6506. const bl = _util.Util.applyTransform([0, 0], inv);
  6507. const br = _util.Util.applyTransform([0, height], inv);
  6508. const ul = _util.Util.applyTransform([width, 0], inv);
  6509. const ur = _util.Util.applyTransform([width, height], inv);
  6510. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6511. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6512. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6513. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6514. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6515. } else {
  6516. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6517. }
  6518. this.compose(this.current.getClippedPathBoundingBox());
  6519. this.restore();
  6520. }
  6521. beginInlineImage() {
  6522. (0, _util.unreachable)("Should not call beginInlineImage");
  6523. }
  6524. beginImageData() {
  6525. (0, _util.unreachable)("Should not call beginImageData");
  6526. }
  6527. paintFormXObjectBegin(matrix, bbox) {
  6528. if (!this.contentVisible) {
  6529. return;
  6530. }
  6531. this.save();
  6532. this.baseTransformStack.push(this.baseTransform);
  6533. if (Array.isArray(matrix) && matrix.length === 6) {
  6534. this.transform(...matrix);
  6535. }
  6536. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  6537. if (bbox) {
  6538. const width = bbox[2] - bbox[0];
  6539. const height = bbox[3] - bbox[1];
  6540. this.ctx.rect(bbox[0], bbox[1], width, height);
  6541. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  6542. this.clip();
  6543. this.endPath();
  6544. }
  6545. }
  6546. paintFormXObjectEnd() {
  6547. if (!this.contentVisible) {
  6548. return;
  6549. }
  6550. this.restore();
  6551. this.baseTransform = this.baseTransformStack.pop();
  6552. }
  6553. beginGroup(group) {
  6554. if (!this.contentVisible) {
  6555. return;
  6556. }
  6557. this.save();
  6558. if (this.inSMaskMode) {
  6559. this.endSMaskMode();
  6560. this.current.activeSMask = null;
  6561. }
  6562. const currentCtx = this.ctx;
  6563. if (!group.isolated) {
  6564. (0, _util.info)("TODO: Support non-isolated groups.");
  6565. }
  6566. if (group.knockout) {
  6567. (0, _util.warn)("Knockout groups not supported.");
  6568. }
  6569. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  6570. if (group.matrix) {
  6571. currentCtx.transform(...group.matrix);
  6572. }
  6573. if (!group.bbox) {
  6574. throw new Error("Bounding box is required.");
  6575. }
  6576. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  6577. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  6578. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6579. const offsetX = Math.floor(bounds[0]);
  6580. const offsetY = Math.floor(bounds[1]);
  6581. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6582. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6583. let scaleX = 1,
  6584. scaleY = 1;
  6585. if (drawnWidth > MAX_GROUP_SIZE) {
  6586. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6587. drawnWidth = MAX_GROUP_SIZE;
  6588. }
  6589. if (drawnHeight > MAX_GROUP_SIZE) {
  6590. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6591. drawnHeight = MAX_GROUP_SIZE;
  6592. }
  6593. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  6594. let cacheId = "groupAt" + this.groupLevel;
  6595. if (group.smask) {
  6596. cacheId += "_smask_" + this.smaskCounter++ % 2;
  6597. }
  6598. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  6599. const groupCtx = scratchCanvas.context;
  6600. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6601. groupCtx.translate(-offsetX, -offsetY);
  6602. groupCtx.transform(...currentTransform);
  6603. if (group.smask) {
  6604. this.smaskStack.push({
  6605. canvas: scratchCanvas.canvas,
  6606. context: groupCtx,
  6607. offsetX,
  6608. offsetY,
  6609. scaleX,
  6610. scaleY,
  6611. subtype: group.smask.subtype,
  6612. backdrop: group.smask.backdrop,
  6613. transferMap: group.smask.transferMap || null,
  6614. startTransformInverse: null
  6615. });
  6616. } else {
  6617. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6618. currentCtx.translate(offsetX, offsetY);
  6619. currentCtx.scale(scaleX, scaleY);
  6620. currentCtx.save();
  6621. }
  6622. copyCtxState(currentCtx, groupCtx);
  6623. this.ctx = groupCtx;
  6624. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6625. this.groupStack.push(currentCtx);
  6626. this.groupLevel++;
  6627. }
  6628. endGroup(group) {
  6629. if (!this.contentVisible) {
  6630. return;
  6631. }
  6632. this.groupLevel--;
  6633. const groupCtx = this.ctx;
  6634. const ctx = this.groupStack.pop();
  6635. this.ctx = ctx;
  6636. this.ctx.imageSmoothingEnabled = false;
  6637. if (group.smask) {
  6638. this.tempSMask = this.smaskStack.pop();
  6639. this.restore();
  6640. } else {
  6641. this.ctx.restore();
  6642. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  6643. this.restore();
  6644. this.ctx.save();
  6645. this.ctx.setTransform(...currentMtx);
  6646. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  6647. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6648. this.ctx.restore();
  6649. this.compose(dirtyBox);
  6650. }
  6651. }
  6652. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  6653. this.#restoreInitialState();
  6654. resetCtxToDefault(this.ctx, this.foregroundColor);
  6655. this.ctx.save();
  6656. this.save();
  6657. if (this.baseTransform) {
  6658. this.ctx.setTransform(...this.baseTransform);
  6659. }
  6660. if (Array.isArray(rect) && rect.length === 4) {
  6661. const width = rect[2] - rect[0];
  6662. const height = rect[3] - rect[1];
  6663. if (hasOwnCanvas && this.annotationCanvasMap) {
  6664. transform = transform.slice();
  6665. transform[4] -= rect[0];
  6666. transform[5] -= rect[1];
  6667. rect = rect.slice();
  6668. rect[0] = rect[1] = 0;
  6669. rect[2] = width;
  6670. rect[3] = height;
  6671. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  6672. const {
  6673. viewportScale
  6674. } = this;
  6675. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  6676. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  6677. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  6678. const {
  6679. canvas,
  6680. context
  6681. } = this.annotationCanvas;
  6682. this.annotationCanvasMap.set(id, canvas);
  6683. this.annotationCanvas.savedCtx = this.ctx;
  6684. this.ctx = context;
  6685. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  6686. resetCtxToDefault(this.ctx, this.foregroundColor);
  6687. } else {
  6688. resetCtxToDefault(this.ctx, this.foregroundColor);
  6689. this.ctx.rect(rect[0], rect[1], width, height);
  6690. this.ctx.clip();
  6691. this.endPath();
  6692. }
  6693. }
  6694. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6695. this.transform(...transform);
  6696. this.transform(...matrix);
  6697. }
  6698. endAnnotation() {
  6699. if (this.annotationCanvas) {
  6700. this.ctx = this.annotationCanvas.savedCtx;
  6701. delete this.annotationCanvas.savedCtx;
  6702. delete this.annotationCanvas;
  6703. }
  6704. }
  6705. paintImageMaskXObject(img) {
  6706. if (!this.contentVisible) {
  6707. return;
  6708. }
  6709. const count = img.count;
  6710. img = this.getObject(img.data, img);
  6711. img.count = count;
  6712. const ctx = this.ctx;
  6713. const glyph = this.processingType3;
  6714. if (glyph) {
  6715. if (glyph.compiled === undefined) {
  6716. glyph.compiled = compileType3Glyph(img);
  6717. }
  6718. if (glyph.compiled) {
  6719. glyph.compiled(ctx);
  6720. return;
  6721. }
  6722. }
  6723. const mask = this._createMaskCanvas(img);
  6724. const maskCanvas = mask.canvas;
  6725. ctx.save();
  6726. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6727. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  6728. ctx.restore();
  6729. this.compose();
  6730. }
  6731. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  6732. if (!this.contentVisible) {
  6733. return;
  6734. }
  6735. img = this.getObject(img.data, img);
  6736. const ctx = this.ctx;
  6737. ctx.save();
  6738. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6739. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  6740. const mask = this._createMaskCanvas(img);
  6741. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6742. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6743. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  6744. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  6745. ctx.drawImage(mask.canvas, x, y);
  6746. }
  6747. ctx.restore();
  6748. this.compose();
  6749. }
  6750. paintImageMaskXObjectGroup(images) {
  6751. if (!this.contentVisible) {
  6752. return;
  6753. }
  6754. const ctx = this.ctx;
  6755. const fillColor = this.current.fillColor;
  6756. const isPatternFill = this.current.patternFill;
  6757. for (const image of images) {
  6758. const {
  6759. data,
  6760. width,
  6761. height,
  6762. transform
  6763. } = image;
  6764. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  6765. const maskCtx = maskCanvas.context;
  6766. maskCtx.save();
  6767. const img = this.getObject(data, image);
  6768. putBinaryImageMask(maskCtx, img);
  6769. maskCtx.globalCompositeOperation = "source-in";
  6770. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  6771. maskCtx.fillRect(0, 0, width, height);
  6772. maskCtx.restore();
  6773. ctx.save();
  6774. ctx.transform(...transform);
  6775. ctx.scale(1, -1);
  6776. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  6777. ctx.restore();
  6778. }
  6779. this.compose();
  6780. }
  6781. paintImageXObject(objId) {
  6782. if (!this.contentVisible) {
  6783. return;
  6784. }
  6785. const imgData = this.getObject(objId);
  6786. if (!imgData) {
  6787. (0, _util.warn)("Dependent image isn't ready yet");
  6788. return;
  6789. }
  6790. this.paintInlineImageXObject(imgData);
  6791. }
  6792. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  6793. if (!this.contentVisible) {
  6794. return;
  6795. }
  6796. const imgData = this.getObject(objId);
  6797. if (!imgData) {
  6798. (0, _util.warn)("Dependent image isn't ready yet");
  6799. return;
  6800. }
  6801. const width = imgData.width;
  6802. const height = imgData.height;
  6803. const map = [];
  6804. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6805. map.push({
  6806. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  6807. x: 0,
  6808. y: 0,
  6809. w: width,
  6810. h: height
  6811. });
  6812. }
  6813. this.paintInlineImageXObjectGroup(imgData, map);
  6814. }
  6815. paintInlineImageXObject(imgData) {
  6816. if (!this.contentVisible) {
  6817. return;
  6818. }
  6819. const width = imgData.width;
  6820. const height = imgData.height;
  6821. const ctx = this.ctx;
  6822. this.save();
  6823. ctx.scale(1 / width, -1 / height);
  6824. let imgToPaint;
  6825. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  6826. imgToPaint = imgData;
  6827. } else {
  6828. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  6829. const tmpCtx = tmpCanvas.context;
  6830. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6831. imgToPaint = tmpCanvas.canvas;
  6832. }
  6833. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  6834. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  6835. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  6836. this.compose();
  6837. this.restore();
  6838. }
  6839. paintInlineImageXObjectGroup(imgData, map) {
  6840. if (!this.contentVisible) {
  6841. return;
  6842. }
  6843. const ctx = this.ctx;
  6844. const w = imgData.width;
  6845. const h = imgData.height;
  6846. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  6847. const tmpCtx = tmpCanvas.context;
  6848. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6849. for (const entry of map) {
  6850. ctx.save();
  6851. ctx.transform(...entry.transform);
  6852. ctx.scale(1, -1);
  6853. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  6854. ctx.restore();
  6855. }
  6856. this.compose();
  6857. }
  6858. paintSolidColorImageMask() {
  6859. if (!this.contentVisible) {
  6860. return;
  6861. }
  6862. this.ctx.fillRect(0, 0, 1, 1);
  6863. this.compose();
  6864. }
  6865. markPoint(tag) {}
  6866. markPointProps(tag, properties) {}
  6867. beginMarkedContent(tag) {
  6868. this.markedContentStack.push({
  6869. visible: true
  6870. });
  6871. }
  6872. beginMarkedContentProps(tag, properties) {
  6873. if (tag === "OC") {
  6874. this.markedContentStack.push({
  6875. visible: this.optionalContentConfig.isVisible(properties)
  6876. });
  6877. } else {
  6878. this.markedContentStack.push({
  6879. visible: true
  6880. });
  6881. }
  6882. this.contentVisible = this.isContentVisible();
  6883. }
  6884. endMarkedContent() {
  6885. this.markedContentStack.pop();
  6886. this.contentVisible = this.isContentVisible();
  6887. }
  6888. beginCompat() {}
  6889. endCompat() {}
  6890. consumePath(clipBox) {
  6891. const isEmpty = this.current.isEmptyClip();
  6892. if (this.pendingClip) {
  6893. this.current.updateClipFromPath();
  6894. }
  6895. if (!this.pendingClip) {
  6896. this.compose(clipBox);
  6897. }
  6898. const ctx = this.ctx;
  6899. if (this.pendingClip) {
  6900. if (!isEmpty) {
  6901. if (this.pendingClip === EO_CLIP) {
  6902. ctx.clip("evenodd");
  6903. } else {
  6904. ctx.clip();
  6905. }
  6906. }
  6907. this.pendingClip = null;
  6908. }
  6909. this.current.startNewPathAndClipBox(this.current.clipBox);
  6910. ctx.beginPath();
  6911. }
  6912. getSinglePixelWidth() {
  6913. if (!this._cachedGetSinglePixelWidth) {
  6914. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  6915. if (m[1] === 0 && m[2] === 0) {
  6916. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  6917. } else {
  6918. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  6919. const normX = Math.hypot(m[0], m[2]);
  6920. const normY = Math.hypot(m[1], m[3]);
  6921. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  6922. }
  6923. }
  6924. return this._cachedGetSinglePixelWidth;
  6925. }
  6926. getScaleForStroking() {
  6927. if (!this._cachedScaleForStroking) {
  6928. const {
  6929. lineWidth
  6930. } = this.current;
  6931. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  6932. let scaleX, scaleY;
  6933. if (m[1] === 0 && m[2] === 0) {
  6934. const normX = Math.abs(m[0]);
  6935. const normY = Math.abs(m[3]);
  6936. if (lineWidth === 0) {
  6937. scaleX = 1 / normX;
  6938. scaleY = 1 / normY;
  6939. } else {
  6940. const scaledXLineWidth = normX * lineWidth;
  6941. const scaledYLineWidth = normY * lineWidth;
  6942. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  6943. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  6944. }
  6945. } else {
  6946. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  6947. const normX = Math.hypot(m[0], m[1]);
  6948. const normY = Math.hypot(m[2], m[3]);
  6949. if (lineWidth === 0) {
  6950. scaleX = normY / absDet;
  6951. scaleY = normX / absDet;
  6952. } else {
  6953. const baseArea = lineWidth * absDet;
  6954. scaleX = normY > baseArea ? normY / baseArea : 1;
  6955. scaleY = normX > baseArea ? normX / baseArea : 1;
  6956. }
  6957. }
  6958. this._cachedScaleForStroking = [scaleX, scaleY];
  6959. }
  6960. return this._cachedScaleForStroking;
  6961. }
  6962. rescaleAndStroke(saveRestore) {
  6963. const {
  6964. ctx
  6965. } = this;
  6966. const {
  6967. lineWidth
  6968. } = this.current;
  6969. const [scaleX, scaleY] = this.getScaleForStroking();
  6970. ctx.lineWidth = lineWidth || 1;
  6971. if (scaleX === 1 && scaleY === 1) {
  6972. ctx.stroke();
  6973. return;
  6974. }
  6975. let savedMatrix, savedDashes, savedDashOffset;
  6976. if (saveRestore) {
  6977. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  6978. savedDashes = ctx.getLineDash().slice();
  6979. savedDashOffset = ctx.lineDashOffset;
  6980. }
  6981. ctx.scale(scaleX, scaleY);
  6982. const scale = Math.max(scaleX, scaleY);
  6983. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  6984. ctx.lineDashOffset /= scale;
  6985. ctx.stroke();
  6986. if (saveRestore) {
  6987. ctx.setTransform(...savedMatrix);
  6988. ctx.setLineDash(savedDashes);
  6989. ctx.lineDashOffset = savedDashOffset;
  6990. }
  6991. }
  6992. isContentVisible() {
  6993. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  6994. if (!this.markedContentStack[i].visible) {
  6995. return false;
  6996. }
  6997. }
  6998. return true;
  6999. }
  7000. }
  7001. exports.CanvasGraphics = CanvasGraphics;
  7002. for (const op in _util.OPS) {
  7003. if (CanvasGraphics.prototype[op] !== undefined) {
  7004. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  7005. }
  7006. }
  7007. /***/ }),
  7008. /* 11 */
  7009. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7010. Object.defineProperty(exports, "__esModule", ({
  7011. value: true
  7012. }));
  7013. exports.TilingPattern = exports.PathType = void 0;
  7014. exports.getShadingPattern = getShadingPattern;
  7015. var _util = __w_pdfjs_require__(1);
  7016. var _display_utils = __w_pdfjs_require__(6);
  7017. var _is_node = __w_pdfjs_require__(12);
  7018. const PathType = {
  7019. FILL: "Fill",
  7020. STROKE: "Stroke",
  7021. SHADING: "Shading"
  7022. };
  7023. exports.PathType = PathType;
  7024. function applyBoundingBox(ctx, bbox) {
  7025. if (!bbox || _is_node.isNodeJS) {
  7026. return;
  7027. }
  7028. const width = bbox[2] - bbox[0];
  7029. const height = bbox[3] - bbox[1];
  7030. const region = new Path2D();
  7031. region.rect(bbox[0], bbox[1], width, height);
  7032. ctx.clip(region);
  7033. }
  7034. class BaseShadingPattern {
  7035. constructor() {
  7036. if (this.constructor === BaseShadingPattern) {
  7037. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  7038. }
  7039. }
  7040. getPattern() {
  7041. (0, _util.unreachable)("Abstract method `getPattern` called.");
  7042. }
  7043. }
  7044. class RadialAxialShadingPattern extends BaseShadingPattern {
  7045. constructor(IR) {
  7046. super();
  7047. this._type = IR[1];
  7048. this._bbox = IR[2];
  7049. this._colorStops = IR[3];
  7050. this._p0 = IR[4];
  7051. this._p1 = IR[5];
  7052. this._r0 = IR[6];
  7053. this._r1 = IR[7];
  7054. this.matrix = null;
  7055. }
  7056. _createGradient(ctx) {
  7057. let grad;
  7058. if (this._type === "axial") {
  7059. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  7060. } else if (this._type === "radial") {
  7061. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  7062. }
  7063. for (const colorStop of this._colorStops) {
  7064. grad.addColorStop(colorStop[0], colorStop[1]);
  7065. }
  7066. return grad;
  7067. }
  7068. getPattern(ctx, owner, inverse, pathType) {
  7069. let pattern;
  7070. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  7071. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  7072. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  7073. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  7074. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  7075. const tmpCtx = tmpCanvas.context;
  7076. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7077. tmpCtx.beginPath();
  7078. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7079. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  7080. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  7081. tmpCtx.transform(...owner.baseTransform);
  7082. if (this.matrix) {
  7083. tmpCtx.transform(...this.matrix);
  7084. }
  7085. applyBoundingBox(tmpCtx, this._bbox);
  7086. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  7087. tmpCtx.fill();
  7088. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  7089. const domMatrix = new DOMMatrix(inverse);
  7090. pattern.setTransform(domMatrix);
  7091. } else {
  7092. applyBoundingBox(ctx, this._bbox);
  7093. pattern = this._createGradient(ctx);
  7094. }
  7095. return pattern;
  7096. }
  7097. }
  7098. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7099. const coords = context.coords,
  7100. colors = context.colors;
  7101. const bytes = data.data,
  7102. rowSize = data.width * 4;
  7103. let tmp;
  7104. if (coords[p1 + 1] > coords[p2 + 1]) {
  7105. tmp = p1;
  7106. p1 = p2;
  7107. p2 = tmp;
  7108. tmp = c1;
  7109. c1 = c2;
  7110. c2 = tmp;
  7111. }
  7112. if (coords[p2 + 1] > coords[p3 + 1]) {
  7113. tmp = p2;
  7114. p2 = p3;
  7115. p3 = tmp;
  7116. tmp = c2;
  7117. c2 = c3;
  7118. c3 = tmp;
  7119. }
  7120. if (coords[p1 + 1] > coords[p2 + 1]) {
  7121. tmp = p1;
  7122. p1 = p2;
  7123. p2 = tmp;
  7124. tmp = c1;
  7125. c1 = c2;
  7126. c2 = tmp;
  7127. }
  7128. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7129. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7130. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7131. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7132. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7133. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7134. if (y1 >= y3) {
  7135. return;
  7136. }
  7137. const c1r = colors[c1],
  7138. c1g = colors[c1 + 1],
  7139. c1b = colors[c1 + 2];
  7140. const c2r = colors[c2],
  7141. c2g = colors[c2 + 1],
  7142. c2b = colors[c2 + 2];
  7143. const c3r = colors[c3],
  7144. c3g = colors[c3 + 1],
  7145. c3b = colors[c3 + 2];
  7146. const minY = Math.round(y1),
  7147. maxY = Math.round(y3);
  7148. let xa, car, cag, cab;
  7149. let xb, cbr, cbg, cbb;
  7150. for (let y = minY; y <= maxY; y++) {
  7151. if (y < y2) {
  7152. let k;
  7153. if (y < y1) {
  7154. k = 0;
  7155. } else {
  7156. k = (y1 - y) / (y1 - y2);
  7157. }
  7158. xa = x1 - (x1 - x2) * k;
  7159. car = c1r - (c1r - c2r) * k;
  7160. cag = c1g - (c1g - c2g) * k;
  7161. cab = c1b - (c1b - c2b) * k;
  7162. } else {
  7163. let k;
  7164. if (y > y3) {
  7165. k = 1;
  7166. } else if (y2 === y3) {
  7167. k = 0;
  7168. } else {
  7169. k = (y2 - y) / (y2 - y3);
  7170. }
  7171. xa = x2 - (x2 - x3) * k;
  7172. car = c2r - (c2r - c3r) * k;
  7173. cag = c2g - (c2g - c3g) * k;
  7174. cab = c2b - (c2b - c3b) * k;
  7175. }
  7176. let k;
  7177. if (y < y1) {
  7178. k = 0;
  7179. } else if (y > y3) {
  7180. k = 1;
  7181. } else {
  7182. k = (y1 - y) / (y1 - y3);
  7183. }
  7184. xb = x1 - (x1 - x3) * k;
  7185. cbr = c1r - (c1r - c3r) * k;
  7186. cbg = c1g - (c1g - c3g) * k;
  7187. cbb = c1b - (c1b - c3b) * k;
  7188. const x1_ = Math.round(Math.min(xa, xb));
  7189. const x2_ = Math.round(Math.max(xa, xb));
  7190. let j = rowSize * y + x1_ * 4;
  7191. for (let x = x1_; x <= x2_; x++) {
  7192. k = (xa - x) / (xa - xb);
  7193. if (k < 0) {
  7194. k = 0;
  7195. } else if (k > 1) {
  7196. k = 1;
  7197. }
  7198. bytes[j++] = car - (car - cbr) * k | 0;
  7199. bytes[j++] = cag - (cag - cbg) * k | 0;
  7200. bytes[j++] = cab - (cab - cbb) * k | 0;
  7201. bytes[j++] = 255;
  7202. }
  7203. }
  7204. }
  7205. function drawFigure(data, figure, context) {
  7206. const ps = figure.coords;
  7207. const cs = figure.colors;
  7208. let i, ii;
  7209. switch (figure.type) {
  7210. case "lattice":
  7211. const verticesPerRow = figure.verticesPerRow;
  7212. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  7213. const cols = verticesPerRow - 1;
  7214. for (i = 0; i < rows; i++) {
  7215. let q = i * verticesPerRow;
  7216. for (let j = 0; j < cols; j++, q++) {
  7217. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7218. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7219. }
  7220. }
  7221. break;
  7222. case "triangles":
  7223. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7224. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  7225. }
  7226. break;
  7227. default:
  7228. throw new Error("illegal figure");
  7229. }
  7230. }
  7231. class MeshShadingPattern extends BaseShadingPattern {
  7232. constructor(IR) {
  7233. super();
  7234. this._coords = IR[2];
  7235. this._colors = IR[3];
  7236. this._figures = IR[4];
  7237. this._bounds = IR[5];
  7238. this._bbox = IR[7];
  7239. this._background = IR[8];
  7240. this.matrix = null;
  7241. }
  7242. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  7243. const EXPECTED_SCALE = 1.1;
  7244. const MAX_PATTERN_SIZE = 3000;
  7245. const BORDER_SIZE = 2;
  7246. const offsetX = Math.floor(this._bounds[0]);
  7247. const offsetY = Math.floor(this._bounds[1]);
  7248. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  7249. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  7250. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7251. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7252. const scaleX = boundsWidth / width;
  7253. const scaleY = boundsHeight / height;
  7254. const context = {
  7255. coords: this._coords,
  7256. colors: this._colors,
  7257. offsetX: -offsetX,
  7258. offsetY: -offsetY,
  7259. scaleX: 1 / scaleX,
  7260. scaleY: 1 / scaleY
  7261. };
  7262. const paddedWidth = width + BORDER_SIZE * 2;
  7263. const paddedHeight = height + BORDER_SIZE * 2;
  7264. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  7265. const tmpCtx = tmpCanvas.context;
  7266. const data = tmpCtx.createImageData(width, height);
  7267. if (backgroundColor) {
  7268. const bytes = data.data;
  7269. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  7270. bytes[i] = backgroundColor[0];
  7271. bytes[i + 1] = backgroundColor[1];
  7272. bytes[i + 2] = backgroundColor[2];
  7273. bytes[i + 3] = 255;
  7274. }
  7275. }
  7276. for (const figure of this._figures) {
  7277. drawFigure(data, figure, context);
  7278. }
  7279. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  7280. const canvas = tmpCanvas.canvas;
  7281. return {
  7282. canvas,
  7283. offsetX: offsetX - BORDER_SIZE * scaleX,
  7284. offsetY: offsetY - BORDER_SIZE * scaleY,
  7285. scaleX,
  7286. scaleY
  7287. };
  7288. }
  7289. getPattern(ctx, owner, inverse, pathType) {
  7290. applyBoundingBox(ctx, this._bbox);
  7291. let scale;
  7292. if (pathType === PathType.SHADING) {
  7293. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  7294. } else {
  7295. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  7296. if (this.matrix) {
  7297. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7298. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  7299. }
  7300. }
  7301. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  7302. if (pathType !== PathType.SHADING) {
  7303. ctx.setTransform(...owner.baseTransform);
  7304. if (this.matrix) {
  7305. ctx.transform(...this.matrix);
  7306. }
  7307. }
  7308. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7309. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  7310. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  7311. }
  7312. }
  7313. class DummyShadingPattern extends BaseShadingPattern {
  7314. getPattern() {
  7315. return "hotpink";
  7316. }
  7317. }
  7318. function getShadingPattern(IR) {
  7319. switch (IR[0]) {
  7320. case "RadialAxial":
  7321. return new RadialAxialShadingPattern(IR);
  7322. case "Mesh":
  7323. return new MeshShadingPattern(IR);
  7324. case "Dummy":
  7325. return new DummyShadingPattern();
  7326. }
  7327. throw new Error(`Unknown IR type: ${IR[0]}`);
  7328. }
  7329. const PaintType = {
  7330. COLORED: 1,
  7331. UNCOLORED: 2
  7332. };
  7333. class TilingPattern {
  7334. static get MAX_PATTERN_SIZE() {
  7335. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  7336. }
  7337. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  7338. this.operatorList = IR[2];
  7339. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7340. this.bbox = IR[4];
  7341. this.xstep = IR[5];
  7342. this.ystep = IR[6];
  7343. this.paintType = IR[7];
  7344. this.tilingType = IR[8];
  7345. this.color = color;
  7346. this.ctx = ctx;
  7347. this.canvasGraphicsFactory = canvasGraphicsFactory;
  7348. this.baseTransform = baseTransform;
  7349. }
  7350. createPatternCanvas(owner) {
  7351. const operatorList = this.operatorList;
  7352. const bbox = this.bbox;
  7353. const xstep = this.xstep;
  7354. const ystep = this.ystep;
  7355. const paintType = this.paintType;
  7356. const tilingType = this.tilingType;
  7357. const color = this.color;
  7358. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  7359. (0, _util.info)("TilingType: " + tilingType);
  7360. const x0 = bbox[0],
  7361. y0 = bbox[1],
  7362. x1 = bbox[2],
  7363. y1 = bbox[3];
  7364. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7365. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  7366. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  7367. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  7368. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  7369. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  7370. const tmpCtx = tmpCanvas.context;
  7371. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  7372. graphics.groupLevel = owner.groupLevel;
  7373. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  7374. let adjustedX0 = x0;
  7375. let adjustedY0 = y0;
  7376. let adjustedX1 = x1;
  7377. let adjustedY1 = y1;
  7378. if (x0 < 0) {
  7379. adjustedX0 = 0;
  7380. adjustedX1 += Math.abs(x0);
  7381. }
  7382. if (y0 < 0) {
  7383. adjustedY0 = 0;
  7384. adjustedY1 += Math.abs(y0);
  7385. }
  7386. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  7387. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  7388. tmpCtx.save();
  7389. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  7390. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  7391. graphics.executeOperatorList(operatorList);
  7392. graphics.endDrawing();
  7393. return {
  7394. canvas: tmpCanvas.canvas,
  7395. scaleX: dimx.scale,
  7396. scaleY: dimy.scale,
  7397. offsetX: adjustedX0,
  7398. offsetY: adjustedY0
  7399. };
  7400. }
  7401. getSizeAndScale(step, realOutputSize, scale) {
  7402. step = Math.abs(step);
  7403. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  7404. let size = Math.ceil(step * scale);
  7405. if (size >= maxSize) {
  7406. size = maxSize;
  7407. } else {
  7408. scale = size / step;
  7409. }
  7410. return {
  7411. scale,
  7412. size
  7413. };
  7414. }
  7415. clipBbox(graphics, x0, y0, x1, y1) {
  7416. const bboxWidth = x1 - x0;
  7417. const bboxHeight = y1 - y0;
  7418. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  7419. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  7420. graphics.clip();
  7421. graphics.endPath();
  7422. }
  7423. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  7424. const context = graphics.ctx,
  7425. current = graphics.current;
  7426. switch (paintType) {
  7427. case PaintType.COLORED:
  7428. const ctx = this.ctx;
  7429. context.fillStyle = ctx.fillStyle;
  7430. context.strokeStyle = ctx.strokeStyle;
  7431. current.fillColor = ctx.fillStyle;
  7432. current.strokeColor = ctx.strokeStyle;
  7433. break;
  7434. case PaintType.UNCOLORED:
  7435. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  7436. context.fillStyle = cssColor;
  7437. context.strokeStyle = cssColor;
  7438. current.fillColor = cssColor;
  7439. current.strokeColor = cssColor;
  7440. break;
  7441. default:
  7442. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  7443. }
  7444. }
  7445. getPattern(ctx, owner, inverse, pathType) {
  7446. let matrix = inverse;
  7447. if (pathType !== PathType.SHADING) {
  7448. matrix = _util.Util.transform(matrix, owner.baseTransform);
  7449. if (this.matrix) {
  7450. matrix = _util.Util.transform(matrix, this.matrix);
  7451. }
  7452. }
  7453. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  7454. let domMatrix = new DOMMatrix(matrix);
  7455. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7456. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  7457. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  7458. pattern.setTransform(domMatrix);
  7459. return pattern;
  7460. }
  7461. }
  7462. exports.TilingPattern = TilingPattern;
  7463. /***/ }),
  7464. /* 12 */
  7465. /***/ ((__unused_webpack_module, exports) => {
  7466. Object.defineProperty(exports, "__esModule", ({
  7467. value: true
  7468. }));
  7469. exports.isNodeJS = void 0;
  7470. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  7471. exports.isNodeJS = isNodeJS;
  7472. /***/ }),
  7473. /* 13 */
  7474. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7475. Object.defineProperty(exports, "__esModule", ({
  7476. value: true
  7477. }));
  7478. exports.applyMaskImageData = applyMaskImageData;
  7479. var _util = __w_pdfjs_require__(1);
  7480. function applyMaskImageData({
  7481. src,
  7482. srcPos = 0,
  7483. dest,
  7484. destPos = 0,
  7485. width,
  7486. height,
  7487. inverseDecode = false
  7488. }) {
  7489. const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7490. const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  7491. const widthInSource = width >> 3;
  7492. const widthRemainder = width & 7;
  7493. const srcLength = src.length;
  7494. dest = new Uint32Array(dest.buffer);
  7495. for (let i = 0; i < height; i++) {
  7496. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  7497. const elem = srcPos < srcLength ? src[srcPos] : 255;
  7498. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  7499. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  7500. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  7501. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  7502. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  7503. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  7504. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  7505. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  7506. }
  7507. if (widthRemainder === 0) {
  7508. continue;
  7509. }
  7510. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  7511. for (let j = 0; j < widthRemainder; j++) {
  7512. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  7513. }
  7514. }
  7515. return {
  7516. srcPos,
  7517. destPos
  7518. };
  7519. }
  7520. /***/ }),
  7521. /* 14 */
  7522. /***/ ((__unused_webpack_module, exports) => {
  7523. Object.defineProperty(exports, "__esModule", ({
  7524. value: true
  7525. }));
  7526. exports.GlobalWorkerOptions = void 0;
  7527. const GlobalWorkerOptions = Object.create(null);
  7528. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  7529. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  7530. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  7531. /***/ }),
  7532. /* 15 */
  7533. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7534. Object.defineProperty(exports, "__esModule", ({
  7535. value: true
  7536. }));
  7537. exports.MessageHandler = void 0;
  7538. var _util = __w_pdfjs_require__(1);
  7539. const CallbackKind = {
  7540. UNKNOWN: 0,
  7541. DATA: 1,
  7542. ERROR: 2
  7543. };
  7544. const StreamKind = {
  7545. UNKNOWN: 0,
  7546. CANCEL: 1,
  7547. CANCEL_COMPLETE: 2,
  7548. CLOSE: 3,
  7549. ENQUEUE: 4,
  7550. ERROR: 5,
  7551. PULL: 6,
  7552. PULL_COMPLETE: 7,
  7553. START_COMPLETE: 8
  7554. };
  7555. function wrapReason(reason) {
  7556. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  7557. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  7558. }
  7559. switch (reason.name) {
  7560. case "AbortException":
  7561. return new _util.AbortException(reason.message);
  7562. case "MissingPDFException":
  7563. return new _util.MissingPDFException(reason.message);
  7564. case "PasswordException":
  7565. return new _util.PasswordException(reason.message, reason.code);
  7566. case "UnexpectedResponseException":
  7567. return new _util.UnexpectedResponseException(reason.message, reason.status);
  7568. case "UnknownErrorException":
  7569. return new _util.UnknownErrorException(reason.message, reason.details);
  7570. default:
  7571. return new _util.UnknownErrorException(reason.message, reason.toString());
  7572. }
  7573. }
  7574. class MessageHandler {
  7575. constructor(sourceName, targetName, comObj) {
  7576. this.sourceName = sourceName;
  7577. this.targetName = targetName;
  7578. this.comObj = comObj;
  7579. this.callbackId = 1;
  7580. this.streamId = 1;
  7581. this.streamSinks = Object.create(null);
  7582. this.streamControllers = Object.create(null);
  7583. this.callbackCapabilities = Object.create(null);
  7584. this.actionHandler = Object.create(null);
  7585. this._onComObjOnMessage = event => {
  7586. const data = event.data;
  7587. if (data.targetName !== this.sourceName) {
  7588. return;
  7589. }
  7590. if (data.stream) {
  7591. this._processStreamMessage(data);
  7592. return;
  7593. }
  7594. if (data.callback) {
  7595. const callbackId = data.callbackId;
  7596. const capability = this.callbackCapabilities[callbackId];
  7597. if (!capability) {
  7598. throw new Error(`Cannot resolve callback ${callbackId}`);
  7599. }
  7600. delete this.callbackCapabilities[callbackId];
  7601. if (data.callback === CallbackKind.DATA) {
  7602. capability.resolve(data.data);
  7603. } else if (data.callback === CallbackKind.ERROR) {
  7604. capability.reject(wrapReason(data.reason));
  7605. } else {
  7606. throw new Error("Unexpected callback case");
  7607. }
  7608. return;
  7609. }
  7610. const action = this.actionHandler[data.action];
  7611. if (!action) {
  7612. throw new Error(`Unknown action from worker: ${data.action}`);
  7613. }
  7614. if (data.callbackId) {
  7615. const cbSourceName = this.sourceName;
  7616. const cbTargetName = data.sourceName;
  7617. new Promise(function (resolve) {
  7618. resolve(action(data.data));
  7619. }).then(function (result) {
  7620. comObj.postMessage({
  7621. sourceName: cbSourceName,
  7622. targetName: cbTargetName,
  7623. callback: CallbackKind.DATA,
  7624. callbackId: data.callbackId,
  7625. data: result
  7626. });
  7627. }, function (reason) {
  7628. comObj.postMessage({
  7629. sourceName: cbSourceName,
  7630. targetName: cbTargetName,
  7631. callback: CallbackKind.ERROR,
  7632. callbackId: data.callbackId,
  7633. reason: wrapReason(reason)
  7634. });
  7635. });
  7636. return;
  7637. }
  7638. if (data.streamId) {
  7639. this._createStreamSink(data);
  7640. return;
  7641. }
  7642. action(data.data);
  7643. };
  7644. comObj.addEventListener("message", this._onComObjOnMessage);
  7645. }
  7646. on(actionName, handler) {
  7647. const ah = this.actionHandler;
  7648. if (ah[actionName]) {
  7649. throw new Error(`There is already an actionName called "${actionName}"`);
  7650. }
  7651. ah[actionName] = handler;
  7652. }
  7653. send(actionName, data, transfers) {
  7654. this.comObj.postMessage({
  7655. sourceName: this.sourceName,
  7656. targetName: this.targetName,
  7657. action: actionName,
  7658. data
  7659. }, transfers);
  7660. }
  7661. sendWithPromise(actionName, data, transfers) {
  7662. const callbackId = this.callbackId++;
  7663. const capability = (0, _util.createPromiseCapability)();
  7664. this.callbackCapabilities[callbackId] = capability;
  7665. try {
  7666. this.comObj.postMessage({
  7667. sourceName: this.sourceName,
  7668. targetName: this.targetName,
  7669. action: actionName,
  7670. callbackId,
  7671. data
  7672. }, transfers);
  7673. } catch (ex) {
  7674. capability.reject(ex);
  7675. }
  7676. return capability.promise;
  7677. }
  7678. sendWithStream(actionName, data, queueingStrategy, transfers) {
  7679. const streamId = this.streamId++,
  7680. sourceName = this.sourceName,
  7681. targetName = this.targetName,
  7682. comObj = this.comObj;
  7683. return new ReadableStream({
  7684. start: controller => {
  7685. const startCapability = (0, _util.createPromiseCapability)();
  7686. this.streamControllers[streamId] = {
  7687. controller,
  7688. startCall: startCapability,
  7689. pullCall: null,
  7690. cancelCall: null,
  7691. isClosed: false
  7692. };
  7693. comObj.postMessage({
  7694. sourceName,
  7695. targetName,
  7696. action: actionName,
  7697. streamId,
  7698. data,
  7699. desiredSize: controller.desiredSize
  7700. }, transfers);
  7701. return startCapability.promise;
  7702. },
  7703. pull: controller => {
  7704. const pullCapability = (0, _util.createPromiseCapability)();
  7705. this.streamControllers[streamId].pullCall = pullCapability;
  7706. comObj.postMessage({
  7707. sourceName,
  7708. targetName,
  7709. stream: StreamKind.PULL,
  7710. streamId,
  7711. desiredSize: controller.desiredSize
  7712. });
  7713. return pullCapability.promise;
  7714. },
  7715. cancel: reason => {
  7716. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  7717. const cancelCapability = (0, _util.createPromiseCapability)();
  7718. this.streamControllers[streamId].cancelCall = cancelCapability;
  7719. this.streamControllers[streamId].isClosed = true;
  7720. comObj.postMessage({
  7721. sourceName,
  7722. targetName,
  7723. stream: StreamKind.CANCEL,
  7724. streamId,
  7725. reason: wrapReason(reason)
  7726. });
  7727. return cancelCapability.promise;
  7728. }
  7729. }, queueingStrategy);
  7730. }
  7731. _createStreamSink(data) {
  7732. const streamId = data.streamId,
  7733. sourceName = this.sourceName,
  7734. targetName = data.sourceName,
  7735. comObj = this.comObj;
  7736. const self = this,
  7737. action = this.actionHandler[data.action];
  7738. const streamSink = {
  7739. enqueue(chunk, size = 1, transfers) {
  7740. if (this.isCancelled) {
  7741. return;
  7742. }
  7743. const lastDesiredSize = this.desiredSize;
  7744. this.desiredSize -= size;
  7745. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  7746. this.sinkCapability = (0, _util.createPromiseCapability)();
  7747. this.ready = this.sinkCapability.promise;
  7748. }
  7749. comObj.postMessage({
  7750. sourceName,
  7751. targetName,
  7752. stream: StreamKind.ENQUEUE,
  7753. streamId,
  7754. chunk
  7755. }, transfers);
  7756. },
  7757. close() {
  7758. if (this.isCancelled) {
  7759. return;
  7760. }
  7761. this.isCancelled = true;
  7762. comObj.postMessage({
  7763. sourceName,
  7764. targetName,
  7765. stream: StreamKind.CLOSE,
  7766. streamId
  7767. });
  7768. delete self.streamSinks[streamId];
  7769. },
  7770. error(reason) {
  7771. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  7772. if (this.isCancelled) {
  7773. return;
  7774. }
  7775. this.isCancelled = true;
  7776. comObj.postMessage({
  7777. sourceName,
  7778. targetName,
  7779. stream: StreamKind.ERROR,
  7780. streamId,
  7781. reason: wrapReason(reason)
  7782. });
  7783. },
  7784. sinkCapability: (0, _util.createPromiseCapability)(),
  7785. onPull: null,
  7786. onCancel: null,
  7787. isCancelled: false,
  7788. desiredSize: data.desiredSize,
  7789. ready: null
  7790. };
  7791. streamSink.sinkCapability.resolve();
  7792. streamSink.ready = streamSink.sinkCapability.promise;
  7793. this.streamSinks[streamId] = streamSink;
  7794. new Promise(function (resolve) {
  7795. resolve(action(data.data, streamSink));
  7796. }).then(function () {
  7797. comObj.postMessage({
  7798. sourceName,
  7799. targetName,
  7800. stream: StreamKind.START_COMPLETE,
  7801. streamId,
  7802. success: true
  7803. });
  7804. }, function (reason) {
  7805. comObj.postMessage({
  7806. sourceName,
  7807. targetName,
  7808. stream: StreamKind.START_COMPLETE,
  7809. streamId,
  7810. reason: wrapReason(reason)
  7811. });
  7812. });
  7813. }
  7814. _processStreamMessage(data) {
  7815. const streamId = data.streamId,
  7816. sourceName = this.sourceName,
  7817. targetName = data.sourceName,
  7818. comObj = this.comObj;
  7819. const streamController = this.streamControllers[streamId],
  7820. streamSink = this.streamSinks[streamId];
  7821. switch (data.stream) {
  7822. case StreamKind.START_COMPLETE:
  7823. if (data.success) {
  7824. streamController.startCall.resolve();
  7825. } else {
  7826. streamController.startCall.reject(wrapReason(data.reason));
  7827. }
  7828. break;
  7829. case StreamKind.PULL_COMPLETE:
  7830. if (data.success) {
  7831. streamController.pullCall.resolve();
  7832. } else {
  7833. streamController.pullCall.reject(wrapReason(data.reason));
  7834. }
  7835. break;
  7836. case StreamKind.PULL:
  7837. if (!streamSink) {
  7838. comObj.postMessage({
  7839. sourceName,
  7840. targetName,
  7841. stream: StreamKind.PULL_COMPLETE,
  7842. streamId,
  7843. success: true
  7844. });
  7845. break;
  7846. }
  7847. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  7848. streamSink.sinkCapability.resolve();
  7849. }
  7850. streamSink.desiredSize = data.desiredSize;
  7851. new Promise(function (resolve) {
  7852. resolve(streamSink.onPull && streamSink.onPull());
  7853. }).then(function () {
  7854. comObj.postMessage({
  7855. sourceName,
  7856. targetName,
  7857. stream: StreamKind.PULL_COMPLETE,
  7858. streamId,
  7859. success: true
  7860. });
  7861. }, function (reason) {
  7862. comObj.postMessage({
  7863. sourceName,
  7864. targetName,
  7865. stream: StreamKind.PULL_COMPLETE,
  7866. streamId,
  7867. reason: wrapReason(reason)
  7868. });
  7869. });
  7870. break;
  7871. case StreamKind.ENQUEUE:
  7872. (0, _util.assert)(streamController, "enqueue should have stream controller");
  7873. if (streamController.isClosed) {
  7874. break;
  7875. }
  7876. streamController.controller.enqueue(data.chunk);
  7877. break;
  7878. case StreamKind.CLOSE:
  7879. (0, _util.assert)(streamController, "close should have stream controller");
  7880. if (streamController.isClosed) {
  7881. break;
  7882. }
  7883. streamController.isClosed = true;
  7884. streamController.controller.close();
  7885. this._deleteStreamController(streamController, streamId);
  7886. break;
  7887. case StreamKind.ERROR:
  7888. (0, _util.assert)(streamController, "error should have stream controller");
  7889. streamController.controller.error(wrapReason(data.reason));
  7890. this._deleteStreamController(streamController, streamId);
  7891. break;
  7892. case StreamKind.CANCEL_COMPLETE:
  7893. if (data.success) {
  7894. streamController.cancelCall.resolve();
  7895. } else {
  7896. streamController.cancelCall.reject(wrapReason(data.reason));
  7897. }
  7898. this._deleteStreamController(streamController, streamId);
  7899. break;
  7900. case StreamKind.CANCEL:
  7901. if (!streamSink) {
  7902. break;
  7903. }
  7904. new Promise(function (resolve) {
  7905. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  7906. }).then(function () {
  7907. comObj.postMessage({
  7908. sourceName,
  7909. targetName,
  7910. stream: StreamKind.CANCEL_COMPLETE,
  7911. streamId,
  7912. success: true
  7913. });
  7914. }, function (reason) {
  7915. comObj.postMessage({
  7916. sourceName,
  7917. targetName,
  7918. stream: StreamKind.CANCEL_COMPLETE,
  7919. streamId,
  7920. reason: wrapReason(reason)
  7921. });
  7922. });
  7923. streamSink.sinkCapability.reject(wrapReason(data.reason));
  7924. streamSink.isCancelled = true;
  7925. delete this.streamSinks[streamId];
  7926. break;
  7927. default:
  7928. throw new Error("Unexpected stream case");
  7929. }
  7930. }
  7931. async _deleteStreamController(streamController, streamId) {
  7932. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  7933. delete this.streamControllers[streamId];
  7934. }
  7935. destroy() {
  7936. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  7937. }
  7938. }
  7939. exports.MessageHandler = MessageHandler;
  7940. /***/ }),
  7941. /* 16 */
  7942. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7943. Object.defineProperty(exports, "__esModule", ({
  7944. value: true
  7945. }));
  7946. exports.Metadata = void 0;
  7947. var _util = __w_pdfjs_require__(1);
  7948. class Metadata {
  7949. #metadataMap;
  7950. #data;
  7951. constructor({
  7952. parsedData,
  7953. rawData
  7954. }) {
  7955. this.#metadataMap = parsedData;
  7956. this.#data = rawData;
  7957. }
  7958. getRaw() {
  7959. return this.#data;
  7960. }
  7961. get(name) {
  7962. return this.#metadataMap.get(name) ?? null;
  7963. }
  7964. getAll() {
  7965. return (0, _util.objectFromMap)(this.#metadataMap);
  7966. }
  7967. has(name) {
  7968. return this.#metadataMap.has(name);
  7969. }
  7970. }
  7971. exports.Metadata = Metadata;
  7972. /***/ }),
  7973. /* 17 */
  7974. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7975. Object.defineProperty(exports, "__esModule", ({
  7976. value: true
  7977. }));
  7978. exports.OptionalContentConfig = void 0;
  7979. var _util = __w_pdfjs_require__(1);
  7980. var _murmurhash = __w_pdfjs_require__(8);
  7981. const INTERNAL = Symbol("INTERNAL");
  7982. class OptionalContentGroup {
  7983. #visible = true;
  7984. constructor(name, intent) {
  7985. this.name = name;
  7986. this.intent = intent;
  7987. }
  7988. get visible() {
  7989. return this.#visible;
  7990. }
  7991. _setVisible(internal, visible) {
  7992. if (internal !== INTERNAL) {
  7993. (0, _util.unreachable)("Internal method `_setVisible` called.");
  7994. }
  7995. this.#visible = visible;
  7996. }
  7997. }
  7998. class OptionalContentConfig {
  7999. #cachedGetHash = null;
  8000. #groups = new Map();
  8001. #initialHash = null;
  8002. #order = null;
  8003. constructor(data) {
  8004. this.name = null;
  8005. this.creator = null;
  8006. if (data === null) {
  8007. return;
  8008. }
  8009. this.name = data.name;
  8010. this.creator = data.creator;
  8011. this.#order = data.order;
  8012. for (const group of data.groups) {
  8013. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  8014. }
  8015. if (data.baseState === "OFF") {
  8016. for (const group of this.#groups.values()) {
  8017. group._setVisible(INTERNAL, false);
  8018. }
  8019. }
  8020. for (const on of data.on) {
  8021. this.#groups.get(on)._setVisible(INTERNAL, true);
  8022. }
  8023. for (const off of data.off) {
  8024. this.#groups.get(off)._setVisible(INTERNAL, false);
  8025. }
  8026. this.#initialHash = this.getHash();
  8027. }
  8028. #evaluateVisibilityExpression(array) {
  8029. const length = array.length;
  8030. if (length < 2) {
  8031. return true;
  8032. }
  8033. const operator = array[0];
  8034. for (let i = 1; i < length; i++) {
  8035. const element = array[i];
  8036. let state;
  8037. if (Array.isArray(element)) {
  8038. state = this.#evaluateVisibilityExpression(element);
  8039. } else if (this.#groups.has(element)) {
  8040. state = this.#groups.get(element).visible;
  8041. } else {
  8042. (0, _util.warn)(`Optional content group not found: ${element}`);
  8043. return true;
  8044. }
  8045. switch (operator) {
  8046. case "And":
  8047. if (!state) {
  8048. return false;
  8049. }
  8050. break;
  8051. case "Or":
  8052. if (state) {
  8053. return true;
  8054. }
  8055. break;
  8056. case "Not":
  8057. return !state;
  8058. default:
  8059. return true;
  8060. }
  8061. }
  8062. return operator === "And";
  8063. }
  8064. isVisible(group) {
  8065. if (this.#groups.size === 0) {
  8066. return true;
  8067. }
  8068. if (!group) {
  8069. (0, _util.warn)("Optional content group not defined.");
  8070. return true;
  8071. }
  8072. if (group.type === "OCG") {
  8073. if (!this.#groups.has(group.id)) {
  8074. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  8075. return true;
  8076. }
  8077. return this.#groups.get(group.id).visible;
  8078. } else if (group.type === "OCMD") {
  8079. if (group.expression) {
  8080. return this.#evaluateVisibilityExpression(group.expression);
  8081. }
  8082. if (!group.policy || group.policy === "AnyOn") {
  8083. for (const id of group.ids) {
  8084. if (!this.#groups.has(id)) {
  8085. (0, _util.warn)(`Optional content group not found: ${id}`);
  8086. return true;
  8087. }
  8088. if (this.#groups.get(id).visible) {
  8089. return true;
  8090. }
  8091. }
  8092. return false;
  8093. } else if (group.policy === "AllOn") {
  8094. for (const id of group.ids) {
  8095. if (!this.#groups.has(id)) {
  8096. (0, _util.warn)(`Optional content group not found: ${id}`);
  8097. return true;
  8098. }
  8099. if (!this.#groups.get(id).visible) {
  8100. return false;
  8101. }
  8102. }
  8103. return true;
  8104. } else if (group.policy === "AnyOff") {
  8105. for (const id of group.ids) {
  8106. if (!this.#groups.has(id)) {
  8107. (0, _util.warn)(`Optional content group not found: ${id}`);
  8108. return true;
  8109. }
  8110. if (!this.#groups.get(id).visible) {
  8111. return true;
  8112. }
  8113. }
  8114. return false;
  8115. } else if (group.policy === "AllOff") {
  8116. for (const id of group.ids) {
  8117. if (!this.#groups.has(id)) {
  8118. (0, _util.warn)(`Optional content group not found: ${id}`);
  8119. return true;
  8120. }
  8121. if (this.#groups.get(id).visible) {
  8122. return false;
  8123. }
  8124. }
  8125. return true;
  8126. }
  8127. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  8128. return true;
  8129. }
  8130. (0, _util.warn)(`Unknown group type ${group.type}.`);
  8131. return true;
  8132. }
  8133. setVisibility(id, visible = true) {
  8134. if (!this.#groups.has(id)) {
  8135. (0, _util.warn)(`Optional content group not found: ${id}`);
  8136. return;
  8137. }
  8138. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  8139. this.#cachedGetHash = null;
  8140. }
  8141. get hasInitialVisibility() {
  8142. return this.getHash() === this.#initialHash;
  8143. }
  8144. getOrder() {
  8145. if (!this.#groups.size) {
  8146. return null;
  8147. }
  8148. if (this.#order) {
  8149. return this.#order.slice();
  8150. }
  8151. return [...this.#groups.keys()];
  8152. }
  8153. getGroups() {
  8154. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  8155. }
  8156. getGroup(id) {
  8157. return this.#groups.get(id) || null;
  8158. }
  8159. getHash() {
  8160. if (this.#cachedGetHash !== null) {
  8161. return this.#cachedGetHash;
  8162. }
  8163. const hash = new _murmurhash.MurmurHash3_64();
  8164. for (const [id, group] of this.#groups) {
  8165. hash.update(`${id}:${group.visible}`);
  8166. }
  8167. return this.#cachedGetHash = hash.hexdigest();
  8168. }
  8169. }
  8170. exports.OptionalContentConfig = OptionalContentConfig;
  8171. /***/ }),
  8172. /* 18 */
  8173. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8174. Object.defineProperty(exports, "__esModule", ({
  8175. value: true
  8176. }));
  8177. exports.PDFDataTransportStream = void 0;
  8178. var _util = __w_pdfjs_require__(1);
  8179. var _display_utils = __w_pdfjs_require__(6);
  8180. class PDFDataTransportStream {
  8181. constructor(params, pdfDataRangeTransport) {
  8182. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  8183. this._queuedChunks = [];
  8184. this._progressiveDone = params.progressiveDone || false;
  8185. this._contentDispositionFilename = params.contentDispositionFilename || null;
  8186. const initialData = params.initialData;
  8187. if (initialData?.length > 0) {
  8188. const buffer = new Uint8Array(initialData).buffer;
  8189. this._queuedChunks.push(buffer);
  8190. }
  8191. this._pdfDataRangeTransport = pdfDataRangeTransport;
  8192. this._isStreamingSupported = !params.disableStream;
  8193. this._isRangeSupported = !params.disableRange;
  8194. this._contentLength = params.length;
  8195. this._fullRequestReader = null;
  8196. this._rangeReaders = [];
  8197. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  8198. this._onReceiveData({
  8199. begin,
  8200. chunk
  8201. });
  8202. });
  8203. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  8204. this._onProgress({
  8205. loaded,
  8206. total
  8207. });
  8208. });
  8209. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  8210. this._onReceiveData({
  8211. chunk
  8212. });
  8213. });
  8214. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  8215. this._onProgressiveDone();
  8216. });
  8217. this._pdfDataRangeTransport.transportReady();
  8218. }
  8219. _onReceiveData(args) {
  8220. const buffer = new Uint8Array(args.chunk).buffer;
  8221. if (args.begin === undefined) {
  8222. if (this._fullRequestReader) {
  8223. this._fullRequestReader._enqueue(buffer);
  8224. } else {
  8225. this._queuedChunks.push(buffer);
  8226. }
  8227. } else {
  8228. const found = this._rangeReaders.some(function (rangeReader) {
  8229. if (rangeReader._begin !== args.begin) {
  8230. return false;
  8231. }
  8232. rangeReader._enqueue(buffer);
  8233. return true;
  8234. });
  8235. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  8236. }
  8237. }
  8238. get _progressiveDataLength() {
  8239. return this._fullRequestReader?._loaded ?? 0;
  8240. }
  8241. _onProgress(evt) {
  8242. if (evt.total === undefined) {
  8243. this._rangeReaders[0]?.onProgress?.({
  8244. loaded: evt.loaded
  8245. });
  8246. } else {
  8247. this._fullRequestReader?.onProgress?.({
  8248. loaded: evt.loaded,
  8249. total: evt.total
  8250. });
  8251. }
  8252. }
  8253. _onProgressiveDone() {
  8254. this._fullRequestReader?.progressiveDone();
  8255. this._progressiveDone = true;
  8256. }
  8257. _removeRangeReader(reader) {
  8258. const i = this._rangeReaders.indexOf(reader);
  8259. if (i >= 0) {
  8260. this._rangeReaders.splice(i, 1);
  8261. }
  8262. }
  8263. getFullReader() {
  8264. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  8265. const queuedChunks = this._queuedChunks;
  8266. this._queuedChunks = null;
  8267. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  8268. }
  8269. getRangeReader(begin, end) {
  8270. if (end <= this._progressiveDataLength) {
  8271. return null;
  8272. }
  8273. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  8274. this._pdfDataRangeTransport.requestDataRange(begin, end);
  8275. this._rangeReaders.push(reader);
  8276. return reader;
  8277. }
  8278. cancelAllRequests(reason) {
  8279. this._fullRequestReader?.cancel(reason);
  8280. for (const reader of this._rangeReaders.slice(0)) {
  8281. reader.cancel(reason);
  8282. }
  8283. this._pdfDataRangeTransport.abort();
  8284. }
  8285. }
  8286. exports.PDFDataTransportStream = PDFDataTransportStream;
  8287. class PDFDataTransportStreamReader {
  8288. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  8289. this._stream = stream;
  8290. this._done = progressiveDone || false;
  8291. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  8292. this._queuedChunks = queuedChunks || [];
  8293. this._loaded = 0;
  8294. for (const chunk of this._queuedChunks) {
  8295. this._loaded += chunk.byteLength;
  8296. }
  8297. this._requests = [];
  8298. this._headersReady = Promise.resolve();
  8299. stream._fullRequestReader = this;
  8300. this.onProgress = null;
  8301. }
  8302. _enqueue(chunk) {
  8303. if (this._done) {
  8304. return;
  8305. }
  8306. if (this._requests.length > 0) {
  8307. const requestCapability = this._requests.shift();
  8308. requestCapability.resolve({
  8309. value: chunk,
  8310. done: false
  8311. });
  8312. } else {
  8313. this._queuedChunks.push(chunk);
  8314. }
  8315. this._loaded += chunk.byteLength;
  8316. }
  8317. get headersReady() {
  8318. return this._headersReady;
  8319. }
  8320. get filename() {
  8321. return this._filename;
  8322. }
  8323. get isRangeSupported() {
  8324. return this._stream._isRangeSupported;
  8325. }
  8326. get isStreamingSupported() {
  8327. return this._stream._isStreamingSupported;
  8328. }
  8329. get contentLength() {
  8330. return this._stream._contentLength;
  8331. }
  8332. async read() {
  8333. if (this._queuedChunks.length > 0) {
  8334. const chunk = this._queuedChunks.shift();
  8335. return {
  8336. value: chunk,
  8337. done: false
  8338. };
  8339. }
  8340. if (this._done) {
  8341. return {
  8342. value: undefined,
  8343. done: true
  8344. };
  8345. }
  8346. const requestCapability = (0, _util.createPromiseCapability)();
  8347. this._requests.push(requestCapability);
  8348. return requestCapability.promise;
  8349. }
  8350. cancel(reason) {
  8351. this._done = true;
  8352. for (const requestCapability of this._requests) {
  8353. requestCapability.resolve({
  8354. value: undefined,
  8355. done: true
  8356. });
  8357. }
  8358. this._requests.length = 0;
  8359. }
  8360. progressiveDone() {
  8361. if (this._done) {
  8362. return;
  8363. }
  8364. this._done = true;
  8365. }
  8366. }
  8367. class PDFDataTransportStreamRangeReader {
  8368. constructor(stream, begin, end) {
  8369. this._stream = stream;
  8370. this._begin = begin;
  8371. this._end = end;
  8372. this._queuedChunk = null;
  8373. this._requests = [];
  8374. this._done = false;
  8375. this.onProgress = null;
  8376. }
  8377. _enqueue(chunk) {
  8378. if (this._done) {
  8379. return;
  8380. }
  8381. if (this._requests.length === 0) {
  8382. this._queuedChunk = chunk;
  8383. } else {
  8384. const requestsCapability = this._requests.shift();
  8385. requestsCapability.resolve({
  8386. value: chunk,
  8387. done: false
  8388. });
  8389. for (const requestCapability of this._requests) {
  8390. requestCapability.resolve({
  8391. value: undefined,
  8392. done: true
  8393. });
  8394. }
  8395. this._requests.length = 0;
  8396. }
  8397. this._done = true;
  8398. this._stream._removeRangeReader(this);
  8399. }
  8400. get isStreamingSupported() {
  8401. return false;
  8402. }
  8403. async read() {
  8404. if (this._queuedChunk) {
  8405. const chunk = this._queuedChunk;
  8406. this._queuedChunk = null;
  8407. return {
  8408. value: chunk,
  8409. done: false
  8410. };
  8411. }
  8412. if (this._done) {
  8413. return {
  8414. value: undefined,
  8415. done: true
  8416. };
  8417. }
  8418. const requestCapability = (0, _util.createPromiseCapability)();
  8419. this._requests.push(requestCapability);
  8420. return requestCapability.promise;
  8421. }
  8422. cancel(reason) {
  8423. this._done = true;
  8424. for (const requestCapability of this._requests) {
  8425. requestCapability.resolve({
  8426. value: undefined,
  8427. done: true
  8428. });
  8429. }
  8430. this._requests.length = 0;
  8431. this._stream._removeRangeReader(this);
  8432. }
  8433. }
  8434. /***/ }),
  8435. /* 19 */
  8436. /***/ ((__unused_webpack_module, exports) => {
  8437. Object.defineProperty(exports, "__esModule", ({
  8438. value: true
  8439. }));
  8440. exports.XfaText = void 0;
  8441. class XfaText {
  8442. static textContent(xfa) {
  8443. const items = [];
  8444. const output = {
  8445. items,
  8446. styles: Object.create(null)
  8447. };
  8448. function walk(node) {
  8449. if (!node) {
  8450. return;
  8451. }
  8452. let str = null;
  8453. const name = node.name;
  8454. if (name === "#text") {
  8455. str = node.value;
  8456. } else if (!XfaText.shouldBuildText(name)) {
  8457. return;
  8458. } else if (node?.attributes?.textContent) {
  8459. str = node.attributes.textContent;
  8460. } else if (node.value) {
  8461. str = node.value;
  8462. }
  8463. if (str !== null) {
  8464. items.push({
  8465. str
  8466. });
  8467. }
  8468. if (!node.children) {
  8469. return;
  8470. }
  8471. for (const child of node.children) {
  8472. walk(child);
  8473. }
  8474. }
  8475. walk(xfa);
  8476. return output;
  8477. }
  8478. static shouldBuildText(name) {
  8479. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  8480. }
  8481. }
  8482. exports.XfaText = XfaText;
  8483. /***/ }),
  8484. /* 20 */
  8485. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8486. Object.defineProperty(exports, "__esModule", ({
  8487. value: true
  8488. }));
  8489. exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  8490. var _base_factory = __w_pdfjs_require__(7);
  8491. ;
  8492. const fetchData = function (url) {
  8493. return new Promise((resolve, reject) => {
  8494. const fs = require("fs");
  8495. fs.readFile(url, (error, data) => {
  8496. if (error || !data) {
  8497. reject(new Error(error));
  8498. return;
  8499. }
  8500. resolve(new Uint8Array(data));
  8501. });
  8502. });
  8503. };
  8504. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  8505. _createCanvas(width, height) {
  8506. const Canvas = require("canvas");
  8507. return Canvas.createCanvas(width, height);
  8508. }
  8509. }
  8510. exports.NodeCanvasFactory = NodeCanvasFactory;
  8511. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  8512. _fetchData(url, compressionType) {
  8513. return fetchData(url).then(data => {
  8514. return {
  8515. cMapData: data,
  8516. compressionType
  8517. };
  8518. });
  8519. }
  8520. }
  8521. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  8522. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  8523. _fetchData(url) {
  8524. return fetchData(url);
  8525. }
  8526. }
  8527. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  8528. /***/ }),
  8529. /* 21 */
  8530. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8531. Object.defineProperty(exports, "__esModule", ({
  8532. value: true
  8533. }));
  8534. exports.AnnotationEditorLayer = void 0;
  8535. var _tools = __w_pdfjs_require__(5);
  8536. var _util = __w_pdfjs_require__(1);
  8537. var _freetext = __w_pdfjs_require__(22);
  8538. var _ink = __w_pdfjs_require__(23);
  8539. class AnnotationEditorLayer {
  8540. #accessibilityManager;
  8541. #allowClick = false;
  8542. #boundPointerup = this.pointerup.bind(this);
  8543. #boundPointerdown = this.pointerdown.bind(this);
  8544. #editors = new Map();
  8545. #hadPointerDown = false;
  8546. #isCleaningUp = false;
  8547. #uiManager;
  8548. static _initialized = false;
  8549. constructor(options) {
  8550. if (!AnnotationEditorLayer._initialized) {
  8551. AnnotationEditorLayer._initialized = true;
  8552. _freetext.FreeTextEditor.initialize(options.l10n);
  8553. _ink.InkEditor.initialize(options.l10n);
  8554. }
  8555. options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
  8556. this.#uiManager = options.uiManager;
  8557. this.annotationStorage = options.annotationStorage;
  8558. this.pageIndex = options.pageIndex;
  8559. this.div = options.div;
  8560. this.#accessibilityManager = options.accessibilityManager;
  8561. this.#uiManager.addLayer(this);
  8562. }
  8563. updateToolbar(mode) {
  8564. this.#uiManager.updateToolbar(mode);
  8565. }
  8566. updateMode(mode = this.#uiManager.getMode()) {
  8567. this.#cleanup();
  8568. if (mode === _util.AnnotationEditorType.INK) {
  8569. this.addInkEditorIfNeeded(false);
  8570. this.disableClick();
  8571. } else {
  8572. this.enableClick();
  8573. }
  8574. this.#uiManager.unselectAll();
  8575. this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
  8576. this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
  8577. }
  8578. addInkEditorIfNeeded(isCommitting) {
  8579. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  8580. return;
  8581. }
  8582. if (!isCommitting) {
  8583. for (const editor of this.#editors.values()) {
  8584. if (editor.isEmpty()) {
  8585. editor.setInBackground();
  8586. return;
  8587. }
  8588. }
  8589. }
  8590. const editor = this.#createAndAddNewEditor({
  8591. offsetX: 0,
  8592. offsetY: 0
  8593. });
  8594. editor.setInBackground();
  8595. }
  8596. setEditingState(isEditing) {
  8597. this.#uiManager.setEditingState(isEditing);
  8598. }
  8599. addCommands(params) {
  8600. this.#uiManager.addCommands(params);
  8601. }
  8602. enable() {
  8603. this.div.style.pointerEvents = "auto";
  8604. for (const editor of this.#editors.values()) {
  8605. editor.enableEditing();
  8606. }
  8607. }
  8608. disable() {
  8609. this.div.style.pointerEvents = "none";
  8610. for (const editor of this.#editors.values()) {
  8611. editor.disableEditing();
  8612. }
  8613. }
  8614. setActiveEditor(editor) {
  8615. const currentActive = this.#uiManager.getActive();
  8616. if (currentActive === editor) {
  8617. return;
  8618. }
  8619. this.#uiManager.setActiveEditor(editor);
  8620. }
  8621. enableClick() {
  8622. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  8623. this.div.addEventListener("pointerup", this.#boundPointerup);
  8624. }
  8625. disableClick() {
  8626. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  8627. this.div.removeEventListener("pointerup", this.#boundPointerup);
  8628. }
  8629. attach(editor) {
  8630. this.#editors.set(editor.id, editor);
  8631. }
  8632. detach(editor) {
  8633. this.#editors.delete(editor.id);
  8634. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  8635. }
  8636. remove(editor) {
  8637. this.#uiManager.removeEditor(editor);
  8638. this.detach(editor);
  8639. this.annotationStorage.remove(editor.id);
  8640. editor.div.style.display = "none";
  8641. setTimeout(() => {
  8642. editor.div.style.display = "";
  8643. editor.div.remove();
  8644. editor.isAttachedToDOM = false;
  8645. if (document.activeElement === document.body) {
  8646. this.#uiManager.focusMainContainer();
  8647. }
  8648. }, 0);
  8649. if (!this.#isCleaningUp) {
  8650. this.addInkEditorIfNeeded(false);
  8651. }
  8652. }
  8653. #changeParent(editor) {
  8654. if (editor.parent === this) {
  8655. return;
  8656. }
  8657. this.attach(editor);
  8658. editor.pageIndex = this.pageIndex;
  8659. editor.parent?.detach(editor);
  8660. editor.parent = this;
  8661. if (editor.div && editor.isAttachedToDOM) {
  8662. editor.div.remove();
  8663. this.div.append(editor.div);
  8664. }
  8665. }
  8666. add(editor) {
  8667. this.#changeParent(editor);
  8668. this.#uiManager.addEditor(editor);
  8669. this.attach(editor);
  8670. if (!editor.isAttachedToDOM) {
  8671. const div = editor.render();
  8672. this.div.append(div);
  8673. editor.isAttachedToDOM = true;
  8674. }
  8675. this.moveEditorInDOM(editor);
  8676. editor.onceAdded();
  8677. this.addToAnnotationStorage(editor);
  8678. }
  8679. moveEditorInDOM(editor) {
  8680. this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  8681. }
  8682. addToAnnotationStorage(editor) {
  8683. if (!editor.isEmpty() && !this.annotationStorage.has(editor.id)) {
  8684. this.annotationStorage.setValue(editor.id, editor);
  8685. }
  8686. }
  8687. addOrRebuild(editor) {
  8688. if (editor.needsToBeRebuilt()) {
  8689. editor.rebuild();
  8690. } else {
  8691. this.add(editor);
  8692. }
  8693. }
  8694. addANewEditor(editor) {
  8695. const cmd = () => {
  8696. this.addOrRebuild(editor);
  8697. };
  8698. const undo = () => {
  8699. editor.remove();
  8700. };
  8701. this.addCommands({
  8702. cmd,
  8703. undo,
  8704. mustExec: true
  8705. });
  8706. }
  8707. addUndoableEditor(editor) {
  8708. const cmd = () => {
  8709. this.addOrRebuild(editor);
  8710. };
  8711. const undo = () => {
  8712. editor.remove();
  8713. };
  8714. this.addCommands({
  8715. cmd,
  8716. undo,
  8717. mustExec: false
  8718. });
  8719. }
  8720. getNextId() {
  8721. return this.#uiManager.getId();
  8722. }
  8723. #createNewEditor(params) {
  8724. switch (this.#uiManager.getMode()) {
  8725. case _util.AnnotationEditorType.FREETEXT:
  8726. return new _freetext.FreeTextEditor(params);
  8727. case _util.AnnotationEditorType.INK:
  8728. return new _ink.InkEditor(params);
  8729. }
  8730. return null;
  8731. }
  8732. deserialize(data) {
  8733. switch (data.annotationType) {
  8734. case _util.AnnotationEditorType.FREETEXT:
  8735. return _freetext.FreeTextEditor.deserialize(data, this);
  8736. case _util.AnnotationEditorType.INK:
  8737. return _ink.InkEditor.deserialize(data, this);
  8738. }
  8739. return null;
  8740. }
  8741. #createAndAddNewEditor(event) {
  8742. const id = this.getNextId();
  8743. const editor = this.#createNewEditor({
  8744. parent: this,
  8745. id,
  8746. x: event.offsetX,
  8747. y: event.offsetY
  8748. });
  8749. if (editor) {
  8750. this.add(editor);
  8751. }
  8752. return editor;
  8753. }
  8754. setSelected(editor) {
  8755. this.#uiManager.setSelected(editor);
  8756. }
  8757. toggleSelected(editor) {
  8758. this.#uiManager.toggleSelected(editor);
  8759. }
  8760. isSelected(editor) {
  8761. return this.#uiManager.isSelected(editor);
  8762. }
  8763. unselect(editor) {
  8764. this.#uiManager.unselect(editor);
  8765. }
  8766. pointerup(event) {
  8767. const isMac = _tools.KeyboardManager.platform.isMac;
  8768. if (event.button !== 0 || event.ctrlKey && isMac) {
  8769. return;
  8770. }
  8771. if (event.target !== this.div) {
  8772. return;
  8773. }
  8774. if (!this.#hadPointerDown) {
  8775. return;
  8776. }
  8777. this.#hadPointerDown = false;
  8778. if (!this.#allowClick) {
  8779. this.#allowClick = true;
  8780. return;
  8781. }
  8782. this.#createAndAddNewEditor(event);
  8783. }
  8784. pointerdown(event) {
  8785. const isMac = _tools.KeyboardManager.platform.isMac;
  8786. if (event.button !== 0 || event.ctrlKey && isMac) {
  8787. return;
  8788. }
  8789. if (event.target !== this.div) {
  8790. return;
  8791. }
  8792. this.#hadPointerDown = true;
  8793. const editor = this.#uiManager.getActive();
  8794. this.#allowClick = !editor || editor.isEmpty();
  8795. }
  8796. drop(event) {
  8797. const id = event.dataTransfer.getData("text/plain");
  8798. const editor = this.#uiManager.getEditor(id);
  8799. if (!editor) {
  8800. return;
  8801. }
  8802. event.preventDefault();
  8803. event.dataTransfer.dropEffect = "move";
  8804. this.#changeParent(editor);
  8805. const rect = this.div.getBoundingClientRect();
  8806. const endX = event.clientX - rect.x;
  8807. const endY = event.clientY - rect.y;
  8808. editor.translate(endX - editor.startX, endY - editor.startY);
  8809. this.moveEditorInDOM(editor);
  8810. editor.div.focus();
  8811. }
  8812. dragover(event) {
  8813. event.preventDefault();
  8814. }
  8815. destroy() {
  8816. if (this.#uiManager.getActive()?.parent === this) {
  8817. this.#uiManager.setActiveEditor(null);
  8818. }
  8819. for (const editor of this.#editors.values()) {
  8820. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  8821. editor.isAttachedToDOM = false;
  8822. editor.div.remove();
  8823. editor.parent = null;
  8824. }
  8825. this.div = null;
  8826. this.#editors.clear();
  8827. this.#uiManager.removeLayer(this);
  8828. }
  8829. #cleanup() {
  8830. this.#isCleaningUp = true;
  8831. for (const editor of this.#editors.values()) {
  8832. if (editor.isEmpty()) {
  8833. editor.remove();
  8834. }
  8835. }
  8836. this.#isCleaningUp = false;
  8837. }
  8838. render(parameters) {
  8839. this.viewport = parameters.viewport;
  8840. (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
  8841. this.setDimensions();
  8842. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  8843. this.add(editor);
  8844. }
  8845. this.updateMode();
  8846. }
  8847. update(parameters) {
  8848. this.#uiManager.commitOrRemove();
  8849. this.viewport = parameters.viewport;
  8850. this.setDimensions();
  8851. this.updateMode();
  8852. }
  8853. get scaleFactor() {
  8854. return this.viewport.scale;
  8855. }
  8856. get pageDimensions() {
  8857. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  8858. const width = pageURx - pageLLx;
  8859. const height = pageURy - pageLLy;
  8860. return [width, height];
  8861. }
  8862. get viewportBaseDimensions() {
  8863. const {
  8864. width,
  8865. height,
  8866. rotation
  8867. } = this.viewport;
  8868. return rotation % 180 === 0 ? [width, height] : [height, width];
  8869. }
  8870. setDimensions() {
  8871. const {
  8872. width,
  8873. height,
  8874. rotation
  8875. } = this.viewport;
  8876. const flipOrientation = rotation % 180 !== 0,
  8877. widthStr = Math.floor(width) + "px",
  8878. heightStr = Math.floor(height) + "px";
  8879. this.div.style.width = flipOrientation ? heightStr : widthStr;
  8880. this.div.style.height = flipOrientation ? widthStr : heightStr;
  8881. this.div.setAttribute("data-main-rotation", rotation);
  8882. }
  8883. }
  8884. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  8885. /***/ }),
  8886. /* 22 */
  8887. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8888. Object.defineProperty(exports, "__esModule", ({
  8889. value: true
  8890. }));
  8891. exports.FreeTextEditor = void 0;
  8892. var _util = __w_pdfjs_require__(1);
  8893. var _tools = __w_pdfjs_require__(5);
  8894. var _editor = __w_pdfjs_require__(4);
  8895. class FreeTextEditor extends _editor.AnnotationEditor {
  8896. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  8897. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  8898. #boundEditorDivInput = this.editorDivInput.bind(this);
  8899. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  8900. #color;
  8901. #content = "";
  8902. #editorDivId = `${this.id}-editor`;
  8903. #hasAlreadyBeenCommitted = false;
  8904. #fontSize;
  8905. static _freeTextDefaultContent = "";
  8906. static _l10nPromise;
  8907. static _internalPadding = 0;
  8908. static _defaultColor = null;
  8909. static _defaultFontSize = 10;
  8910. static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  8911. static _type = "freetext";
  8912. constructor(params) {
  8913. super({
  8914. ...params,
  8915. name: "freeTextEditor"
  8916. });
  8917. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  8918. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  8919. }
  8920. static initialize(l10n) {
  8921. this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
  8922. const style = getComputedStyle(document.documentElement);
  8923. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  8924. }
  8925. static updateDefaultParams(type, value) {
  8926. switch (type) {
  8927. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  8928. FreeTextEditor._defaultFontSize = value;
  8929. break;
  8930. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  8931. FreeTextEditor._defaultColor = value;
  8932. break;
  8933. }
  8934. }
  8935. updateParams(type, value) {
  8936. switch (type) {
  8937. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  8938. this.#updateFontSize(value);
  8939. break;
  8940. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  8941. this.#updateColor(value);
  8942. break;
  8943. }
  8944. }
  8945. static get defaultPropertiesToUpdate() {
  8946. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  8947. }
  8948. get propertiesToUpdate() {
  8949. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  8950. }
  8951. #updateFontSize(fontSize) {
  8952. const setFontsize = size => {
  8953. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  8954. this.translate(0, -(size - this.#fontSize) * this.parent.scaleFactor);
  8955. this.#fontSize = size;
  8956. this.#setEditorDimensions();
  8957. };
  8958. const savedFontsize = this.#fontSize;
  8959. this.parent.addCommands({
  8960. cmd: () => {
  8961. setFontsize(fontSize);
  8962. },
  8963. undo: () => {
  8964. setFontsize(savedFontsize);
  8965. },
  8966. mustExec: true,
  8967. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  8968. overwriteIfSameType: true,
  8969. keepUndo: true
  8970. });
  8971. }
  8972. #updateColor(color) {
  8973. const savedColor = this.#color;
  8974. this.parent.addCommands({
  8975. cmd: () => {
  8976. this.#color = color;
  8977. this.editorDiv.style.color = color;
  8978. },
  8979. undo: () => {
  8980. this.#color = savedColor;
  8981. this.editorDiv.style.color = savedColor;
  8982. },
  8983. mustExec: true,
  8984. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  8985. overwriteIfSameType: true,
  8986. keepUndo: true
  8987. });
  8988. }
  8989. getInitialTranslation() {
  8990. return [-FreeTextEditor._internalPadding * this.parent.scaleFactor, -(FreeTextEditor._internalPadding + this.#fontSize) * this.parent.scaleFactor];
  8991. }
  8992. rebuild() {
  8993. super.rebuild();
  8994. if (this.div === null) {
  8995. return;
  8996. }
  8997. if (!this.isAttachedToDOM) {
  8998. this.parent.add(this);
  8999. }
  9000. }
  9001. enableEditMode() {
  9002. if (this.isInEditMode()) {
  9003. return;
  9004. }
  9005. this.parent.setEditingState(false);
  9006. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  9007. super.enableEditMode();
  9008. this.overlayDiv.classList.remove("enabled");
  9009. this.editorDiv.contentEditable = true;
  9010. this.div.draggable = false;
  9011. this.div.removeAttribute("aria-activedescendant");
  9012. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  9013. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  9014. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  9015. this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  9016. }
  9017. disableEditMode() {
  9018. if (!this.isInEditMode()) {
  9019. return;
  9020. }
  9021. this.parent.setEditingState(true);
  9022. super.disableEditMode();
  9023. this.overlayDiv.classList.add("enabled");
  9024. this.editorDiv.contentEditable = false;
  9025. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  9026. this.div.draggable = true;
  9027. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  9028. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  9029. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  9030. this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
  9031. this.div.focus();
  9032. this.isEditing = false;
  9033. this.parent.div.classList.add("freeTextEditing");
  9034. }
  9035. focusin(event) {
  9036. super.focusin(event);
  9037. if (event.target !== this.editorDiv) {
  9038. this.editorDiv.focus();
  9039. }
  9040. }
  9041. onceAdded() {
  9042. if (this.width) {
  9043. return;
  9044. }
  9045. this.enableEditMode();
  9046. this.editorDiv.focus();
  9047. }
  9048. isEmpty() {
  9049. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  9050. }
  9051. remove() {
  9052. this.isEditing = false;
  9053. this.parent.setEditingState(true);
  9054. this.parent.div.classList.add("freeTextEditing");
  9055. super.remove();
  9056. }
  9057. #extractText() {
  9058. const divs = this.editorDiv.getElementsByTagName("div");
  9059. if (divs.length === 0) {
  9060. return this.editorDiv.innerText;
  9061. }
  9062. const buffer = [];
  9063. for (const div of divs) {
  9064. const first = div.firstChild;
  9065. if (first?.nodeName === "#text") {
  9066. buffer.push(first.data);
  9067. } else {
  9068. buffer.push("");
  9069. }
  9070. }
  9071. return buffer.join("\n");
  9072. }
  9073. #setEditorDimensions() {
  9074. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9075. const rect = this.div.getBoundingClientRect();
  9076. this.width = rect.width / parentWidth;
  9077. this.height = rect.height / parentHeight;
  9078. }
  9079. commit() {
  9080. super.commit();
  9081. if (!this.#hasAlreadyBeenCommitted) {
  9082. this.#hasAlreadyBeenCommitted = true;
  9083. this.parent.addUndoableEditor(this);
  9084. }
  9085. this.disableEditMode();
  9086. this.#content = this.#extractText().trimEnd();
  9087. this.#setEditorDimensions();
  9088. }
  9089. shouldGetKeyboardEvents() {
  9090. return this.isInEditMode();
  9091. }
  9092. dblclick(event) {
  9093. this.enableEditMode();
  9094. this.editorDiv.focus();
  9095. }
  9096. keydown(event) {
  9097. if (event.target === this.div && event.key === "Enter") {
  9098. this.enableEditMode();
  9099. this.editorDiv.focus();
  9100. }
  9101. }
  9102. editorDivKeydown(event) {
  9103. FreeTextEditor._keyboardManager.exec(this, event);
  9104. }
  9105. editorDivFocus(event) {
  9106. this.isEditing = true;
  9107. }
  9108. editorDivBlur(event) {
  9109. this.isEditing = false;
  9110. }
  9111. editorDivInput(event) {
  9112. this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  9113. }
  9114. disableEditing() {
  9115. this.editorDiv.setAttribute("role", "comment");
  9116. this.editorDiv.removeAttribute("aria-multiline");
  9117. }
  9118. enableEditing() {
  9119. this.editorDiv.setAttribute("role", "textbox");
  9120. this.editorDiv.setAttribute("aria-multiline", true);
  9121. }
  9122. render() {
  9123. if (this.div) {
  9124. return this.div;
  9125. }
  9126. let baseX, baseY;
  9127. if (this.width) {
  9128. baseX = this.x;
  9129. baseY = this.y;
  9130. }
  9131. super.render();
  9132. this.editorDiv = document.createElement("div");
  9133. this.editorDiv.className = "internal";
  9134. this.editorDiv.setAttribute("id", this.#editorDivId);
  9135. this.enableEditing();
  9136. FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  9137. FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  9138. this.editorDiv.contentEditable = true;
  9139. const {
  9140. style
  9141. } = this.editorDiv;
  9142. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  9143. style.color = this.#color;
  9144. this.div.append(this.editorDiv);
  9145. this.overlayDiv = document.createElement("div");
  9146. this.overlayDiv.classList.add("overlay", "enabled");
  9147. this.div.append(this.overlayDiv);
  9148. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  9149. if (this.width) {
  9150. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9151. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9152. for (const line of this.#content.split("\n")) {
  9153. const div = document.createElement("div");
  9154. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  9155. this.editorDiv.append(div);
  9156. }
  9157. this.div.draggable = true;
  9158. this.editorDiv.contentEditable = false;
  9159. } else {
  9160. this.div.draggable = false;
  9161. this.editorDiv.contentEditable = true;
  9162. }
  9163. return this.div;
  9164. }
  9165. get contentDiv() {
  9166. return this.editorDiv;
  9167. }
  9168. static deserialize(data, parent) {
  9169. const editor = super.deserialize(data, parent);
  9170. editor.#fontSize = data.fontSize;
  9171. editor.#color = _util.Util.makeHexColor(...data.color);
  9172. editor.#content = data.value;
  9173. return editor;
  9174. }
  9175. serialize() {
  9176. if (this.isEmpty()) {
  9177. return null;
  9178. }
  9179. const padding = FreeTextEditor._internalPadding * this.parent.scaleFactor;
  9180. const rect = this.getRect(padding, padding);
  9181. const color = _editor.AnnotationEditor._colorManager.convert(getComputedStyle(this.editorDiv).color);
  9182. return {
  9183. annotationType: _util.AnnotationEditorType.FREETEXT,
  9184. color,
  9185. fontSize: this.#fontSize,
  9186. value: this.#content,
  9187. pageIndex: this.parent.pageIndex,
  9188. rect,
  9189. rotation: this.rotation
  9190. };
  9191. }
  9192. }
  9193. exports.FreeTextEditor = FreeTextEditor;
  9194. /***/ }),
  9195. /* 23 */
  9196. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9197. Object.defineProperty(exports, "__esModule", ({
  9198. value: true
  9199. }));
  9200. exports.InkEditor = void 0;
  9201. Object.defineProperty(exports, "fitCurve", ({
  9202. enumerable: true,
  9203. get: function () {
  9204. return _pdfjsFitCurve.fitCurve;
  9205. }
  9206. }));
  9207. var _util = __w_pdfjs_require__(1);
  9208. var _editor = __w_pdfjs_require__(4);
  9209. var _pdfjsFitCurve = __w_pdfjs_require__(24);
  9210. var _tools = __w_pdfjs_require__(5);
  9211. const RESIZER_SIZE = 16;
  9212. const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
  9213. class InkEditor extends _editor.AnnotationEditor {
  9214. #aspectRatio = 0;
  9215. #baseHeight = 0;
  9216. #baseWidth = 0;
  9217. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  9218. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  9219. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  9220. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  9221. #disableEditing = false;
  9222. #isCanvasInitialized = false;
  9223. #lastPoint = null;
  9224. #observer = null;
  9225. #realWidth = 0;
  9226. #realHeight = 0;
  9227. #requestFrameCallback = null;
  9228. static _defaultColor = null;
  9229. static _defaultOpacity = 1;
  9230. static _defaultThickness = 1;
  9231. static _l10nPromise;
  9232. static _type = "ink";
  9233. constructor(params) {
  9234. super({
  9235. ...params,
  9236. name: "inkEditor"
  9237. });
  9238. this.color = params.color || null;
  9239. this.thickness = params.thickness || null;
  9240. this.opacity = params.opacity || null;
  9241. this.paths = [];
  9242. this.bezierPath2D = [];
  9243. this.currentPath = [];
  9244. this.scaleFactor = 1;
  9245. this.translationX = this.translationY = 0;
  9246. this.x = 0;
  9247. this.y = 0;
  9248. }
  9249. static initialize(l10n) {
  9250. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  9251. }
  9252. static updateDefaultParams(type, value) {
  9253. switch (type) {
  9254. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9255. InkEditor._defaultThickness = value;
  9256. break;
  9257. case _util.AnnotationEditorParamsType.INK_COLOR:
  9258. InkEditor._defaultColor = value;
  9259. break;
  9260. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9261. InkEditor._defaultOpacity = value / 100;
  9262. break;
  9263. }
  9264. }
  9265. updateParams(type, value) {
  9266. switch (type) {
  9267. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9268. this.#updateThickness(value);
  9269. break;
  9270. case _util.AnnotationEditorParamsType.INK_COLOR:
  9271. this.#updateColor(value);
  9272. break;
  9273. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9274. this.#updateOpacity(value);
  9275. break;
  9276. }
  9277. }
  9278. static get defaultPropertiesToUpdate() {
  9279. 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)]];
  9280. }
  9281. get propertiesToUpdate() {
  9282. 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))]];
  9283. }
  9284. #updateThickness(thickness) {
  9285. const savedThickness = this.thickness;
  9286. this.parent.addCommands({
  9287. cmd: () => {
  9288. this.thickness = thickness;
  9289. this.#fitToContent();
  9290. },
  9291. undo: () => {
  9292. this.thickness = savedThickness;
  9293. this.#fitToContent();
  9294. },
  9295. mustExec: true,
  9296. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  9297. overwriteIfSameType: true,
  9298. keepUndo: true
  9299. });
  9300. }
  9301. #updateColor(color) {
  9302. const savedColor = this.color;
  9303. this.parent.addCommands({
  9304. cmd: () => {
  9305. this.color = color;
  9306. this.#redraw();
  9307. },
  9308. undo: () => {
  9309. this.color = savedColor;
  9310. this.#redraw();
  9311. },
  9312. mustExec: true,
  9313. type: _util.AnnotationEditorParamsType.INK_COLOR,
  9314. overwriteIfSameType: true,
  9315. keepUndo: true
  9316. });
  9317. }
  9318. #updateOpacity(opacity) {
  9319. opacity /= 100;
  9320. const savedOpacity = this.opacity;
  9321. this.parent.addCommands({
  9322. cmd: () => {
  9323. this.opacity = opacity;
  9324. this.#redraw();
  9325. },
  9326. undo: () => {
  9327. this.opacity = savedOpacity;
  9328. this.#redraw();
  9329. },
  9330. mustExec: true,
  9331. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  9332. overwriteIfSameType: true,
  9333. keepUndo: true
  9334. });
  9335. }
  9336. rebuild() {
  9337. super.rebuild();
  9338. if (this.div === null) {
  9339. return;
  9340. }
  9341. if (!this.canvas) {
  9342. this.#createCanvas();
  9343. this.#createObserver();
  9344. }
  9345. if (!this.isAttachedToDOM) {
  9346. this.parent.add(this);
  9347. this.#setCanvasDims();
  9348. }
  9349. this.#fitToContent();
  9350. }
  9351. remove() {
  9352. if (this.canvas === null) {
  9353. return;
  9354. }
  9355. if (!this.isEmpty()) {
  9356. this.commit();
  9357. }
  9358. this.canvas.width = this.canvas.height = 0;
  9359. this.canvas.remove();
  9360. this.canvas = null;
  9361. this.#observer.disconnect();
  9362. this.#observer = null;
  9363. super.remove();
  9364. }
  9365. enableEditMode() {
  9366. if (this.#disableEditing || this.canvas === null) {
  9367. return;
  9368. }
  9369. super.enableEditMode();
  9370. this.div.draggable = false;
  9371. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  9372. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  9373. }
  9374. disableEditMode() {
  9375. if (!this.isInEditMode() || this.canvas === null) {
  9376. return;
  9377. }
  9378. super.disableEditMode();
  9379. this.div.draggable = !this.isEmpty();
  9380. this.div.classList.remove("editing");
  9381. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  9382. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  9383. }
  9384. onceAdded() {
  9385. this.div.draggable = !this.isEmpty();
  9386. }
  9387. isEmpty() {
  9388. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  9389. }
  9390. #getInitialBBox() {
  9391. const {
  9392. width,
  9393. height,
  9394. rotation
  9395. } = this.parent.viewport;
  9396. switch (rotation) {
  9397. case 90:
  9398. return [0, width, width, height];
  9399. case 180:
  9400. return [width, height, width, height];
  9401. case 270:
  9402. return [height, 0, width, height];
  9403. default:
  9404. return [0, 0, width, height];
  9405. }
  9406. }
  9407. #setStroke() {
  9408. this.ctx.lineWidth = this.thickness * this.parent.scaleFactor / this.scaleFactor;
  9409. this.ctx.lineCap = "round";
  9410. this.ctx.lineJoin = "round";
  9411. this.ctx.miterLimit = 10;
  9412. this.ctx.strokeStyle = `${this.color}${(0, _tools.opacityToHex)(this.opacity)}`;
  9413. }
  9414. #startDrawing(x, y) {
  9415. this.isEditing = true;
  9416. if (!this.#isCanvasInitialized) {
  9417. this.#isCanvasInitialized = true;
  9418. this.#setCanvasDims();
  9419. this.thickness ||= InkEditor._defaultThickness;
  9420. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9421. this.opacity ??= InkEditor._defaultOpacity;
  9422. }
  9423. this.currentPath.push([x, y]);
  9424. this.#lastPoint = null;
  9425. this.#setStroke();
  9426. this.ctx.beginPath();
  9427. this.ctx.moveTo(x, y);
  9428. this.#requestFrameCallback = () => {
  9429. if (!this.#requestFrameCallback) {
  9430. return;
  9431. }
  9432. if (this.#lastPoint) {
  9433. if (this.isEmpty()) {
  9434. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  9435. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  9436. } else {
  9437. this.#redraw();
  9438. }
  9439. this.ctx.lineTo(...this.#lastPoint);
  9440. this.#lastPoint = null;
  9441. this.ctx.stroke();
  9442. }
  9443. window.requestAnimationFrame(this.#requestFrameCallback);
  9444. };
  9445. window.requestAnimationFrame(this.#requestFrameCallback);
  9446. }
  9447. #draw(x, y) {
  9448. const [lastX, lastY] = this.currentPath.at(-1);
  9449. if (x === lastX && y === lastY) {
  9450. return;
  9451. }
  9452. this.currentPath.push([x, y]);
  9453. this.#lastPoint = [x, y];
  9454. }
  9455. #stopDrawing(x, y) {
  9456. this.ctx.closePath();
  9457. this.#requestFrameCallback = null;
  9458. x = Math.min(Math.max(x, 0), this.canvas.width);
  9459. y = Math.min(Math.max(y, 0), this.canvas.height);
  9460. const [lastX, lastY] = this.currentPath.at(-1);
  9461. if (x !== lastX || y !== lastY) {
  9462. this.currentPath.push([x, y]);
  9463. }
  9464. let bezier;
  9465. if (this.currentPath.length !== 1) {
  9466. bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
  9467. } else {
  9468. const xy = [x, y];
  9469. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  9470. }
  9471. const path2D = InkEditor.#buildPath2D(bezier);
  9472. this.currentPath.length = 0;
  9473. const cmd = () => {
  9474. this.paths.push(bezier);
  9475. this.bezierPath2D.push(path2D);
  9476. this.rebuild();
  9477. };
  9478. const undo = () => {
  9479. this.paths.pop();
  9480. this.bezierPath2D.pop();
  9481. if (this.paths.length === 0) {
  9482. this.remove();
  9483. } else {
  9484. if (!this.canvas) {
  9485. this.#createCanvas();
  9486. this.#createObserver();
  9487. }
  9488. this.#fitToContent();
  9489. }
  9490. };
  9491. this.parent.addCommands({
  9492. cmd,
  9493. undo,
  9494. mustExec: true
  9495. });
  9496. }
  9497. #redraw() {
  9498. if (this.isEmpty()) {
  9499. this.#updateTransform();
  9500. return;
  9501. }
  9502. this.#setStroke();
  9503. const {
  9504. canvas,
  9505. ctx
  9506. } = this;
  9507. ctx.setTransform(1, 0, 0, 1, 0, 0);
  9508. ctx.clearRect(0, 0, canvas.width, canvas.height);
  9509. this.#updateTransform();
  9510. for (const path of this.bezierPath2D) {
  9511. ctx.stroke(path);
  9512. }
  9513. }
  9514. commit() {
  9515. if (this.#disableEditing) {
  9516. return;
  9517. }
  9518. super.commit();
  9519. this.isEditing = false;
  9520. this.disableEditMode();
  9521. this.setInForeground();
  9522. this.#disableEditing = true;
  9523. this.div.classList.add("disabled");
  9524. this.#fitToContent(true);
  9525. this.parent.addInkEditorIfNeeded(true);
  9526. this.parent.moveEditorInDOM(this);
  9527. this.div.focus();
  9528. }
  9529. focusin(event) {
  9530. super.focusin(event);
  9531. this.enableEditMode();
  9532. }
  9533. canvasPointerdown(event) {
  9534. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  9535. return;
  9536. }
  9537. this.setInForeground();
  9538. if (event.type !== "mouse") {
  9539. this.div.focus();
  9540. }
  9541. event.stopPropagation();
  9542. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  9543. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  9544. this.#startDrawing(event.offsetX, event.offsetY);
  9545. }
  9546. canvasPointermove(event) {
  9547. event.stopPropagation();
  9548. this.#draw(event.offsetX, event.offsetY);
  9549. }
  9550. canvasPointerup(event) {
  9551. if (event.button !== 0) {
  9552. return;
  9553. }
  9554. if (this.isInEditMode() && this.currentPath.length !== 0) {
  9555. event.stopPropagation();
  9556. this.#endDrawing(event);
  9557. this.setInBackground();
  9558. }
  9559. }
  9560. canvasPointerleave(event) {
  9561. this.#endDrawing(event);
  9562. this.setInBackground();
  9563. }
  9564. #endDrawing(event) {
  9565. this.#stopDrawing(event.offsetX, event.offsetY);
  9566. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  9567. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  9568. this.parent.addToAnnotationStorage(this);
  9569. }
  9570. #createCanvas() {
  9571. this.canvas = document.createElement("canvas");
  9572. this.canvas.width = this.canvas.height = 0;
  9573. this.canvas.className = "inkEditorCanvas";
  9574. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  9575. this.div.append(this.canvas);
  9576. this.ctx = this.canvas.getContext("2d");
  9577. }
  9578. #createObserver() {
  9579. let timeoutId = null;
  9580. this.#observer = new ResizeObserver(entries => {
  9581. const rect = entries[0].contentRect;
  9582. if (rect.width && rect.height) {
  9583. if (timeoutId !== null) {
  9584. clearTimeout(timeoutId);
  9585. }
  9586. timeoutId = setTimeout(() => {
  9587. this.fixDims();
  9588. timeoutId = null;
  9589. }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
  9590. this.setDimensions(rect.width, rect.height);
  9591. }
  9592. });
  9593. this.#observer.observe(this.div);
  9594. }
  9595. render() {
  9596. if (this.div) {
  9597. return this.div;
  9598. }
  9599. let baseX, baseY;
  9600. if (this.width) {
  9601. baseX = this.x;
  9602. baseY = this.y;
  9603. }
  9604. super.render();
  9605. InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  9606. const [x, y, w, h] = this.#getInitialBBox();
  9607. this.setAt(x, y, 0, 0);
  9608. this.setDims(w, h);
  9609. this.#createCanvas();
  9610. if (this.width) {
  9611. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9612. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9613. this.#isCanvasInitialized = true;
  9614. this.#setCanvasDims();
  9615. this.setDims(this.width * parentWidth, this.height * parentHeight);
  9616. this.#redraw();
  9617. this.#setMinDims();
  9618. this.div.classList.add("disabled");
  9619. } else {
  9620. this.div.classList.add("editing");
  9621. this.enableEditMode();
  9622. }
  9623. this.#createObserver();
  9624. return this.div;
  9625. }
  9626. #setCanvasDims() {
  9627. if (!this.#isCanvasInitialized) {
  9628. return;
  9629. }
  9630. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9631. this.canvas.width = Math.ceil(this.width * parentWidth);
  9632. this.canvas.height = Math.ceil(this.height * parentHeight);
  9633. this.#updateTransform();
  9634. }
  9635. setDimensions(width, height) {
  9636. const roundedWidth = Math.round(width);
  9637. const roundedHeight = Math.round(height);
  9638. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  9639. return;
  9640. }
  9641. this.#realWidth = roundedWidth;
  9642. this.#realHeight = roundedHeight;
  9643. this.canvas.style.visibility = "hidden";
  9644. if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
  9645. height = Math.ceil(width / this.#aspectRatio);
  9646. this.setDims(width, height);
  9647. }
  9648. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9649. this.width = width / parentWidth;
  9650. this.height = height / parentHeight;
  9651. if (this.#disableEditing) {
  9652. this.#setScaleFactor(width, height);
  9653. }
  9654. this.#setCanvasDims();
  9655. this.#redraw();
  9656. this.canvas.style.visibility = "visible";
  9657. }
  9658. #setScaleFactor(width, height) {
  9659. const padding = this.#getPadding();
  9660. const scaleFactorW = (width - padding) / this.#baseWidth;
  9661. const scaleFactorH = (height - padding) / this.#baseHeight;
  9662. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  9663. }
  9664. #updateTransform() {
  9665. const padding = this.#getPadding() / 2;
  9666. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  9667. }
  9668. static #buildPath2D(bezier) {
  9669. const path2D = new Path2D();
  9670. for (let i = 0, ii = bezier.length; i < ii; i++) {
  9671. const [first, control1, control2, second] = bezier[i];
  9672. if (i === 0) {
  9673. path2D.moveTo(...first);
  9674. }
  9675. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  9676. }
  9677. return path2D;
  9678. }
  9679. #serializePaths(s, tx, ty, h) {
  9680. const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
  9681. const paths = [];
  9682. const padding = this.thickness / 2;
  9683. let buffer, points;
  9684. for (const bezier of this.paths) {
  9685. buffer = [];
  9686. points = [];
  9687. for (let i = 0, ii = bezier.length; i < ii; i++) {
  9688. const [first, control1, control2, second] = bezier[i];
  9689. const p10 = s * (first[0] + tx) + padding;
  9690. const p11 = h - s * (first[1] + ty) - padding;
  9691. const p20 = s * (control1[0] + tx) + padding;
  9692. const p21 = h - s * (control1[1] + ty) - padding;
  9693. const p30 = s * (control2[0] + tx) + padding;
  9694. const p31 = h - s * (control2[1] + ty) - padding;
  9695. const p40 = s * (second[0] + tx) + padding;
  9696. const p41 = h - s * (second[1] + ty) - padding;
  9697. if (i === 0) {
  9698. buffer.push(p10, p11);
  9699. points.push(p10, p11);
  9700. }
  9701. buffer.push(p20, p21, p30, p31, p40, p41);
  9702. this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
  9703. }
  9704. paths.push({
  9705. bezier: buffer,
  9706. points
  9707. });
  9708. }
  9709. return paths;
  9710. }
  9711. #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
  9712. if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
  9713. points.push(p40, p41);
  9714. return;
  9715. }
  9716. for (let i = 1; i < n - 1; i++) {
  9717. const t = i / n;
  9718. const mt = 1 - t;
  9719. let q10 = t * p10 + mt * p20;
  9720. let q11 = t * p11 + mt * p21;
  9721. let q20 = t * p20 + mt * p30;
  9722. let q21 = t * p21 + mt * p31;
  9723. const q30 = t * p30 + mt * p40;
  9724. const q31 = t * p31 + mt * p41;
  9725. q10 = t * q10 + mt * q20;
  9726. q11 = t * q11 + mt * q21;
  9727. q20 = t * q20 + mt * q30;
  9728. q21 = t * q21 + mt * q31;
  9729. q10 = t * q10 + mt * q20;
  9730. q11 = t * q11 + mt * q21;
  9731. points.push(q10, q11);
  9732. }
  9733. points.push(p40, p41);
  9734. }
  9735. #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
  9736. const tol = 10;
  9737. const ax = (3 * p20 - 2 * p10 - p40) ** 2;
  9738. const ay = (3 * p21 - 2 * p11 - p41) ** 2;
  9739. const bx = (3 * p30 - p10 - 2 * p40) ** 2;
  9740. const by = (3 * p31 - p11 - 2 * p41) ** 2;
  9741. return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  9742. }
  9743. #getBbox() {
  9744. let xMin = Infinity;
  9745. let xMax = -Infinity;
  9746. let yMin = Infinity;
  9747. let yMax = -Infinity;
  9748. for (const path of this.paths) {
  9749. for (const [first, control1, control2, second] of path) {
  9750. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  9751. xMin = Math.min(xMin, bbox[0]);
  9752. yMin = Math.min(yMin, bbox[1]);
  9753. xMax = Math.max(xMax, bbox[2]);
  9754. yMax = Math.max(yMax, bbox[3]);
  9755. }
  9756. }
  9757. return [xMin, yMin, xMax, yMax];
  9758. }
  9759. #getPadding() {
  9760. return this.#disableEditing ? Math.ceil(this.thickness * this.parent.scaleFactor) : 0;
  9761. }
  9762. #fitToContent(firstTime = false) {
  9763. if (this.isEmpty()) {
  9764. return;
  9765. }
  9766. if (!this.#disableEditing) {
  9767. this.#redraw();
  9768. return;
  9769. }
  9770. const bbox = this.#getBbox();
  9771. const padding = this.#getPadding();
  9772. this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  9773. this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  9774. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  9775. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  9776. const [parentWidth, parentHeight] = this.parent.viewportBaseDimensions;
  9777. this.width = width / parentWidth;
  9778. this.height = height / parentHeight;
  9779. this.#aspectRatio = width / height;
  9780. this.#setMinDims();
  9781. const prevTranslationX = this.translationX;
  9782. const prevTranslationY = this.translationY;
  9783. this.translationX = -bbox[0];
  9784. this.translationY = -bbox[1];
  9785. this.#setCanvasDims();
  9786. this.#redraw();
  9787. this.#realWidth = width;
  9788. this.#realHeight = height;
  9789. this.setDims(width, height);
  9790. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  9791. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  9792. }
  9793. #setMinDims() {
  9794. const {
  9795. style
  9796. } = this.div;
  9797. if (this.#aspectRatio >= 1) {
  9798. style.minHeight = `${RESIZER_SIZE}px`;
  9799. style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
  9800. } else {
  9801. style.minWidth = `${RESIZER_SIZE}px`;
  9802. style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
  9803. }
  9804. }
  9805. static deserialize(data, parent) {
  9806. const editor = super.deserialize(data, parent);
  9807. editor.thickness = data.thickness;
  9808. editor.color = _util.Util.makeHexColor(...data.color);
  9809. editor.opacity = data.opacity;
  9810. const [pageWidth, pageHeight] = parent.pageDimensions;
  9811. const width = editor.width * pageWidth;
  9812. const height = editor.height * pageHeight;
  9813. const scaleFactor = parent.scaleFactor;
  9814. const padding = data.thickness / 2;
  9815. editor.#aspectRatio = width / height;
  9816. editor.#disableEditing = true;
  9817. editor.#realWidth = Math.round(width);
  9818. editor.#realHeight = Math.round(height);
  9819. for (const {
  9820. bezier
  9821. } of data.paths) {
  9822. const path = [];
  9823. editor.paths.push(path);
  9824. let p0 = scaleFactor * (bezier[0] - padding);
  9825. let p1 = scaleFactor * (height - bezier[1] - padding);
  9826. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  9827. const p10 = scaleFactor * (bezier[i] - padding);
  9828. const p11 = scaleFactor * (height - bezier[i + 1] - padding);
  9829. const p20 = scaleFactor * (bezier[i + 2] - padding);
  9830. const p21 = scaleFactor * (height - bezier[i + 3] - padding);
  9831. const p30 = scaleFactor * (bezier[i + 4] - padding);
  9832. const p31 = scaleFactor * (height - bezier[i + 5] - padding);
  9833. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  9834. p0 = p30;
  9835. p1 = p31;
  9836. }
  9837. const path2D = this.#buildPath2D(path);
  9838. editor.bezierPath2D.push(path2D);
  9839. }
  9840. const bbox = editor.#getBbox();
  9841. editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  9842. editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  9843. editor.#setScaleFactor(width, height);
  9844. return editor;
  9845. }
  9846. serialize() {
  9847. if (this.isEmpty()) {
  9848. return null;
  9849. }
  9850. const rect = this.getRect(0, 0);
  9851. const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
  9852. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  9853. return {
  9854. annotationType: _util.AnnotationEditorType.INK,
  9855. color,
  9856. thickness: this.thickness,
  9857. opacity: this.opacity,
  9858. paths: this.#serializePaths(this.scaleFactor / this.parent.scaleFactor, this.translationX, this.translationY, height),
  9859. pageIndex: this.parent.pageIndex,
  9860. rect,
  9861. rotation: this.rotation
  9862. };
  9863. }
  9864. }
  9865. exports.InkEditor = InkEditor;
  9866. /***/ }),
  9867. /* 24 */
  9868. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9869. Object.defineProperty(exports, "__esModule", ({
  9870. value: true
  9871. }));
  9872. exports.fitCurve = void 0;
  9873. const fitCurve = __w_pdfjs_require__(25);
  9874. exports.fitCurve = fitCurve;
  9875. /***/ }),
  9876. /* 25 */
  9877. /***/ ((module) => {
  9878. function fitCurve(points, maxError, progressCallback) {
  9879. if (!Array.isArray(points)) {
  9880. throw new TypeError("First argument should be an array");
  9881. }
  9882. points.forEach(point => {
  9883. if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
  9884. throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
  9885. }
  9886. });
  9887. points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  9888. if (points.length < 2) {
  9889. return [];
  9890. }
  9891. const len = points.length;
  9892. const leftTangent = createTangent(points[1], points[0]);
  9893. const rightTangent = createTangent(points[len - 2], points[len - 1]);
  9894. return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
  9895. }
  9896. function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  9897. const MaxIterations = 20;
  9898. var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  9899. if (points.length === 2) {
  9900. dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
  9901. bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
  9902. return [bezCurve];
  9903. }
  9904. u = chordLengthParameterize(points);
  9905. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  9906. if (maxError === 0 || maxError < error) {
  9907. return [bezCurve];
  9908. }
  9909. if (maxError < error * error) {
  9910. uPrime = u;
  9911. prevErr = maxError;
  9912. prevSplit = splitPoint;
  9913. for (i = 0; i < MaxIterations; i++) {
  9914. uPrime = reparameterize(bezCurve, points, uPrime);
  9915. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
  9916. if (maxError < error) {
  9917. return [bezCurve];
  9918. } else if (splitPoint === prevSplit) {
  9919. let errChange = maxError / prevErr;
  9920. if (errChange > .9999 && errChange < 1.0001) {
  9921. break;
  9922. }
  9923. }
  9924. prevErr = maxError;
  9925. prevSplit = splitPoint;
  9926. }
  9927. }
  9928. beziers = [];
  9929. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  9930. if (centerVector.every(val => val === 0)) {
  9931. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
  9932. [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  9933. }
  9934. toCenterTangent = maths.normalize(centerVector);
  9935. fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  9936. beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  9937. beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  9938. return beziers;
  9939. }
  9940. ;
  9941. function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  9942. var bezCurve, maxError, splitPoint;
  9943. bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  9944. [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  9945. if (progressCallback) {
  9946. progressCallback({
  9947. bez: bezCurve,
  9948. points: points,
  9949. params: paramsOrig,
  9950. maxErr: maxError,
  9951. maxPoint: splitPoint
  9952. });
  9953. }
  9954. return [bezCurve, maxError, splitPoint];
  9955. }
  9956. function generateBezier(points, parameters, leftTangent, rightTangent) {
  9957. var bezCurve,
  9958. A,
  9959. a,
  9960. C,
  9961. X,
  9962. det_C0_C1,
  9963. det_C0_X,
  9964. det_X_C1,
  9965. alpha_l,
  9966. alpha_r,
  9967. epsilon,
  9968. segLength,
  9969. i,
  9970. len,
  9971. tmp,
  9972. u,
  9973. ux,
  9974. firstPoint = points[0],
  9975. lastPoint = points[points.length - 1];
  9976. bezCurve = [firstPoint, null, null, lastPoint];
  9977. A = maths.zeros_Xx2x2(parameters.length);
  9978. for (i = 0, len = parameters.length; i < len; i++) {
  9979. u = parameters[i];
  9980. ux = 1 - u;
  9981. a = A[i];
  9982. a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
  9983. a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  9984. }
  9985. C = [[0, 0], [0, 0]];
  9986. X = [0, 0];
  9987. for (i = 0, len = points.length; i < len; i++) {
  9988. u = parameters[i];
  9989. a = A[i];
  9990. C[0][0] += maths.dot(a[0], a[0]);
  9991. C[0][1] += maths.dot(a[0], a[1]);
  9992. C[1][0] += maths.dot(a[0], a[1]);
  9993. C[1][1] += maths.dot(a[1], a[1]);
  9994. tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
  9995. X[0] += maths.dot(a[0], tmp);
  9996. X[1] += maths.dot(a[1], tmp);
  9997. }
  9998. det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  9999. det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  10000. det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  10001. alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  10002. alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  10003. segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  10004. epsilon = 1.0e-6 * segLength;
  10005. if (alpha_l < epsilon || alpha_r < epsilon) {
  10006. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
  10007. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  10008. } else {
  10009. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
  10010. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  10011. }
  10012. return bezCurve;
  10013. }
  10014. ;
  10015. function reparameterize(bezier, points, parameters) {
  10016. return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
  10017. }
  10018. ;
  10019. function newtonRaphsonRootFind(bez, point, u) {
  10020. var d = maths.subtract(bezier.q(bez, u), point),
  10021. qprime = bezier.qprime(bez, u),
  10022. numerator = maths.mulMatrix(d, qprime),
  10023. denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  10024. if (denominator === 0) {
  10025. return u;
  10026. } else {
  10027. return u - numerator / denominator;
  10028. }
  10029. }
  10030. ;
  10031. function chordLengthParameterize(points) {
  10032. var u = [],
  10033. currU,
  10034. prevU,
  10035. prevP;
  10036. points.forEach((p, i) => {
  10037. currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
  10038. u.push(currU);
  10039. prevU = currU;
  10040. prevP = p;
  10041. });
  10042. u = u.map(x => x / prevU);
  10043. return u;
  10044. }
  10045. ;
  10046. function computeMaxError(points, bez, parameters) {
  10047. var dist, maxDist, splitPoint, v, i, count, point, t;
  10048. maxDist = 0;
  10049. splitPoint = Math.floor(points.length / 2);
  10050. const t_distMap = mapTtoRelativeDistances(bez, 10);
  10051. for (i = 0, count = points.length; i < count; i++) {
  10052. point = points[i];
  10053. t = find_t(bez, parameters[i], t_distMap, 10);
  10054. v = maths.subtract(bezier.q(bez, t), point);
  10055. dist = v[0] * v[0] + v[1] * v[1];
  10056. if (dist > maxDist) {
  10057. maxDist = dist;
  10058. splitPoint = i;
  10059. }
  10060. }
  10061. return [maxDist, splitPoint];
  10062. }
  10063. ;
  10064. var mapTtoRelativeDistances = function (bez, B_parts) {
  10065. var B_t_curr;
  10066. var B_t_dist = [0];
  10067. var B_t_prev = bez[0];
  10068. var sumLen = 0;
  10069. for (var i = 1; i <= B_parts; i++) {
  10070. B_t_curr = bezier.q(bez, i / B_parts);
  10071. sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
  10072. B_t_dist.push(sumLen);
  10073. B_t_prev = B_t_curr;
  10074. }
  10075. B_t_dist = B_t_dist.map(x => x / sumLen);
  10076. return B_t_dist;
  10077. };
  10078. function find_t(bez, param, t_distMap, B_parts) {
  10079. if (param < 0) {
  10080. return 0;
  10081. }
  10082. if (param > 1) {
  10083. return 1;
  10084. }
  10085. var lenMax, lenMin, tMax, tMin, t;
  10086. for (var i = 1; i <= B_parts; i++) {
  10087. if (param <= t_distMap[i]) {
  10088. tMin = (i - 1) / B_parts;
  10089. tMax = i / B_parts;
  10090. lenMin = t_distMap[i - 1];
  10091. lenMax = t_distMap[i];
  10092. t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
  10093. break;
  10094. }
  10095. }
  10096. return t;
  10097. }
  10098. function createTangent(pointA, pointB) {
  10099. return maths.normalize(maths.subtract(pointA, pointB));
  10100. }
  10101. class maths {
  10102. static zeros_Xx2x2(x) {
  10103. var zs = [];
  10104. while (x--) {
  10105. zs.push([0, 0]);
  10106. }
  10107. return zs;
  10108. }
  10109. static mulItems(items, multiplier) {
  10110. return items.map(x => x * multiplier);
  10111. }
  10112. static mulMatrix(m1, m2) {
  10113. return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  10114. }
  10115. static subtract(arr1, arr2) {
  10116. return arr1.map((x1, i) => x1 - arr2[i]);
  10117. }
  10118. static addArrays(arr1, arr2) {
  10119. return arr1.map((x1, i) => x1 + arr2[i]);
  10120. }
  10121. static addItems(items, addition) {
  10122. return items.map(x => x + addition);
  10123. }
  10124. static sum(items) {
  10125. return items.reduce((sum, x) => sum + x);
  10126. }
  10127. static dot(m1, m2) {
  10128. return maths.mulMatrix(m1, m2);
  10129. }
  10130. static vectorLen(v) {
  10131. return Math.hypot(...v);
  10132. }
  10133. static divItems(items, divisor) {
  10134. return items.map(x => x / divisor);
  10135. }
  10136. static squareItems(items) {
  10137. return items.map(x => x * x);
  10138. }
  10139. static normalize(v) {
  10140. return this.divItems(v, this.vectorLen(v));
  10141. }
  10142. }
  10143. class bezier {
  10144. static q(ctrlPoly, t) {
  10145. var tx = 1.0 - t;
  10146. var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
  10147. pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
  10148. pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
  10149. pD = maths.mulItems(ctrlPoly[3], t * t * t);
  10150. return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  10151. }
  10152. static qprime(ctrlPoly, t) {
  10153. var tx = 1.0 - t;
  10154. var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
  10155. pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
  10156. pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
  10157. return maths.addArrays(maths.addArrays(pA, pB), pC);
  10158. }
  10159. static qprimeprime(ctrlPoly, t) {
  10160. return maths.addArrays(maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[2], maths.mulItems(ctrlPoly[1], 2)), ctrlPoly[0]), 6 * (1.0 - t)), maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[3], maths.mulItems(ctrlPoly[2], 2)), ctrlPoly[1]), 6 * t));
  10161. }
  10162. }
  10163. module.exports = fitCurve;
  10164. module.exports.fitCubic = fitCubic;
  10165. module.exports.createTangent = createTangent;
  10166. /***/ }),
  10167. /* 26 */
  10168. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10169. Object.defineProperty(exports, "__esModule", ({
  10170. value: true
  10171. }));
  10172. exports.AnnotationLayer = void 0;
  10173. var _util = __w_pdfjs_require__(1);
  10174. var _display_utils = __w_pdfjs_require__(6);
  10175. var _annotation_storage = __w_pdfjs_require__(3);
  10176. var _scripting_utils = __w_pdfjs_require__(27);
  10177. var _xfa_layer = __w_pdfjs_require__(28);
  10178. const DEFAULT_TAB_INDEX = 1000;
  10179. const DEFAULT_FONT_SIZE = 9;
  10180. const GetElementsByNameSet = new WeakSet();
  10181. function getRectDims(rect) {
  10182. return {
  10183. width: rect[2] - rect[0],
  10184. height: rect[3] - rect[1]
  10185. };
  10186. }
  10187. class AnnotationElementFactory {
  10188. static create(parameters) {
  10189. const subtype = parameters.data.annotationType;
  10190. switch (subtype) {
  10191. case _util.AnnotationType.LINK:
  10192. return new LinkAnnotationElement(parameters);
  10193. case _util.AnnotationType.TEXT:
  10194. return new TextAnnotationElement(parameters);
  10195. case _util.AnnotationType.WIDGET:
  10196. const fieldType = parameters.data.fieldType;
  10197. switch (fieldType) {
  10198. case "Tx":
  10199. return new TextWidgetAnnotationElement(parameters);
  10200. case "Btn":
  10201. if (parameters.data.radioButton) {
  10202. return new RadioButtonWidgetAnnotationElement(parameters);
  10203. } else if (parameters.data.checkBox) {
  10204. return new CheckboxWidgetAnnotationElement(parameters);
  10205. }
  10206. return new PushButtonWidgetAnnotationElement(parameters);
  10207. case "Ch":
  10208. return new ChoiceWidgetAnnotationElement(parameters);
  10209. }
  10210. return new WidgetAnnotationElement(parameters);
  10211. case _util.AnnotationType.POPUP:
  10212. return new PopupAnnotationElement(parameters);
  10213. case _util.AnnotationType.FREETEXT:
  10214. return new FreeTextAnnotationElement(parameters);
  10215. case _util.AnnotationType.LINE:
  10216. return new LineAnnotationElement(parameters);
  10217. case _util.AnnotationType.SQUARE:
  10218. return new SquareAnnotationElement(parameters);
  10219. case _util.AnnotationType.CIRCLE:
  10220. return new CircleAnnotationElement(parameters);
  10221. case _util.AnnotationType.POLYLINE:
  10222. return new PolylineAnnotationElement(parameters);
  10223. case _util.AnnotationType.CARET:
  10224. return new CaretAnnotationElement(parameters);
  10225. case _util.AnnotationType.INK:
  10226. return new InkAnnotationElement(parameters);
  10227. case _util.AnnotationType.POLYGON:
  10228. return new PolygonAnnotationElement(parameters);
  10229. case _util.AnnotationType.HIGHLIGHT:
  10230. return new HighlightAnnotationElement(parameters);
  10231. case _util.AnnotationType.UNDERLINE:
  10232. return new UnderlineAnnotationElement(parameters);
  10233. case _util.AnnotationType.SQUIGGLY:
  10234. return new SquigglyAnnotationElement(parameters);
  10235. case _util.AnnotationType.STRIKEOUT:
  10236. return new StrikeOutAnnotationElement(parameters);
  10237. case _util.AnnotationType.STAMP:
  10238. return new StampAnnotationElement(parameters);
  10239. case _util.AnnotationType.FILEATTACHMENT:
  10240. return new FileAttachmentAnnotationElement(parameters);
  10241. default:
  10242. return new AnnotationElement(parameters);
  10243. }
  10244. }
  10245. }
  10246. class AnnotationElement {
  10247. constructor(parameters, {
  10248. isRenderable = false,
  10249. ignoreBorder = false,
  10250. createQuadrilaterals = false
  10251. } = {}) {
  10252. this.isRenderable = isRenderable;
  10253. this.data = parameters.data;
  10254. this.layer = parameters.layer;
  10255. this.page = parameters.page;
  10256. this.viewport = parameters.viewport;
  10257. this.linkService = parameters.linkService;
  10258. this.downloadManager = parameters.downloadManager;
  10259. this.imageResourcesPath = parameters.imageResourcesPath;
  10260. this.renderForms = parameters.renderForms;
  10261. this.svgFactory = parameters.svgFactory;
  10262. this.annotationStorage = parameters.annotationStorage;
  10263. this.enableScripting = parameters.enableScripting;
  10264. this.hasJSActions = parameters.hasJSActions;
  10265. this._fieldObjects = parameters.fieldObjects;
  10266. this._mouseState = parameters.mouseState;
  10267. if (isRenderable) {
  10268. this.container = this._createContainer(ignoreBorder);
  10269. }
  10270. if (createQuadrilaterals) {
  10271. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  10272. }
  10273. }
  10274. _createContainer(ignoreBorder = false) {
  10275. const data = this.data,
  10276. page = this.page,
  10277. viewport = this.viewport;
  10278. const container = document.createElement("section");
  10279. const {
  10280. width,
  10281. height
  10282. } = getRectDims(data.rect);
  10283. const [pageLLx, pageLLy, pageURx, pageURy] = viewport.viewBox;
  10284. const pageWidth = pageURx - pageLLx;
  10285. const pageHeight = pageURy - pageLLy;
  10286. container.setAttribute("data-annotation-id", data.id);
  10287. 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]]);
  10288. if (!ignoreBorder && data.borderStyle.width > 0) {
  10289. container.style.borderWidth = `${data.borderStyle.width}px`;
  10290. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  10291. const verticalRadius = data.borderStyle.verticalCornerRadius;
  10292. if (horizontalRadius > 0 || verticalRadius > 0) {
  10293. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  10294. container.style.borderRadius = radius;
  10295. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  10296. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  10297. container.style.borderRadius = radius;
  10298. }
  10299. switch (data.borderStyle.style) {
  10300. case _util.AnnotationBorderStyleType.SOLID:
  10301. container.style.borderStyle = "solid";
  10302. break;
  10303. case _util.AnnotationBorderStyleType.DASHED:
  10304. container.style.borderStyle = "dashed";
  10305. break;
  10306. case _util.AnnotationBorderStyleType.BEVELED:
  10307. (0, _util.warn)("Unimplemented border style: beveled");
  10308. break;
  10309. case _util.AnnotationBorderStyleType.INSET:
  10310. (0, _util.warn)("Unimplemented border style: inset");
  10311. break;
  10312. case _util.AnnotationBorderStyleType.UNDERLINE:
  10313. container.style.borderBottomStyle = "solid";
  10314. break;
  10315. default:
  10316. break;
  10317. }
  10318. const borderColor = data.borderColor || null;
  10319. if (borderColor) {
  10320. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  10321. } else {
  10322. container.style.borderWidth = 0;
  10323. }
  10324. }
  10325. container.style.left = `${100 * (rect[0] - pageLLx) / pageWidth}%`;
  10326. container.style.top = `${100 * (rect[1] - pageLLy) / pageHeight}%`;
  10327. const {
  10328. rotation
  10329. } = data;
  10330. if (data.hasOwnCanvas || rotation === 0) {
  10331. container.style.width = `${100 * width / pageWidth}%`;
  10332. container.style.height = `${100 * height / pageHeight}%`;
  10333. } else {
  10334. this.setRotation(rotation, container);
  10335. }
  10336. return container;
  10337. }
  10338. setRotation(angle, container = this.container) {
  10339. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  10340. const pageWidth = pageURx - pageLLx;
  10341. const pageHeight = pageURy - pageLLy;
  10342. const {
  10343. width,
  10344. height
  10345. } = getRectDims(this.data.rect);
  10346. let elementWidth, elementHeight;
  10347. if (angle % 180 === 0) {
  10348. elementWidth = 100 * width / pageWidth;
  10349. elementHeight = 100 * height / pageHeight;
  10350. } else {
  10351. elementWidth = 100 * height / pageWidth;
  10352. elementHeight = 100 * width / pageHeight;
  10353. }
  10354. container.style.width = `${elementWidth}%`;
  10355. container.style.height = `${elementHeight}%`;
  10356. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  10357. }
  10358. get _commonActions() {
  10359. const setColor = (jsName, styleName, event) => {
  10360. const color = event.detail[jsName];
  10361. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  10362. };
  10363. return (0, _util.shadow)(this, "_commonActions", {
  10364. display: event => {
  10365. const hidden = event.detail.display % 2 === 1;
  10366. this.container.style.visibility = hidden ? "hidden" : "visible";
  10367. this.annotationStorage.setValue(this.data.id, {
  10368. hidden,
  10369. print: event.detail.display === 0 || event.detail.display === 3
  10370. });
  10371. },
  10372. print: event => {
  10373. this.annotationStorage.setValue(this.data.id, {
  10374. print: event.detail.print
  10375. });
  10376. },
  10377. hidden: event => {
  10378. this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
  10379. this.annotationStorage.setValue(this.data.id, {
  10380. hidden: event.detail.hidden
  10381. });
  10382. },
  10383. focus: event => {
  10384. setTimeout(() => event.target.focus({
  10385. preventScroll: false
  10386. }), 0);
  10387. },
  10388. userName: event => {
  10389. event.target.title = event.detail.userName;
  10390. },
  10391. readonly: event => {
  10392. if (event.detail.readonly) {
  10393. event.target.setAttribute("readonly", "");
  10394. } else {
  10395. event.target.removeAttribute("readonly");
  10396. }
  10397. },
  10398. required: event => {
  10399. this._setRequired(event.target, event.detail.required);
  10400. },
  10401. bgColor: event => {
  10402. setColor("bgColor", "backgroundColor", event);
  10403. },
  10404. fillColor: event => {
  10405. setColor("fillColor", "backgroundColor", event);
  10406. },
  10407. fgColor: event => {
  10408. setColor("fgColor", "color", event);
  10409. },
  10410. textColor: event => {
  10411. setColor("textColor", "color", event);
  10412. },
  10413. borderColor: event => {
  10414. setColor("borderColor", "borderColor", event);
  10415. },
  10416. strokeColor: event => {
  10417. setColor("strokeColor", "borderColor", event);
  10418. },
  10419. rotation: event => {
  10420. const angle = event.detail.rotation;
  10421. this.setRotation(angle);
  10422. this.annotationStorage.setValue(this.data.id, {
  10423. rotation: angle
  10424. });
  10425. }
  10426. });
  10427. }
  10428. _dispatchEventFromSandbox(actions, jsEvent) {
  10429. const commonActions = this._commonActions;
  10430. for (const name of Object.keys(jsEvent.detail)) {
  10431. const action = actions[name] || commonActions[name];
  10432. action?.(jsEvent);
  10433. }
  10434. }
  10435. _setDefaultPropertiesFromJS(element) {
  10436. if (!this.enableScripting) {
  10437. return;
  10438. }
  10439. const storedData = this.annotationStorage.getRawValue(this.data.id);
  10440. if (!storedData) {
  10441. return;
  10442. }
  10443. const commonActions = this._commonActions;
  10444. for (const [actionName, detail] of Object.entries(storedData)) {
  10445. const action = commonActions[actionName];
  10446. if (action) {
  10447. const eventProxy = {
  10448. detail: {
  10449. [actionName]: detail
  10450. },
  10451. target: element
  10452. };
  10453. action(eventProxy);
  10454. delete storedData[actionName];
  10455. }
  10456. }
  10457. }
  10458. _createQuadrilaterals(ignoreBorder = false) {
  10459. if (!this.data.quadPoints) {
  10460. return null;
  10461. }
  10462. const quadrilaterals = [];
  10463. const savedRect = this.data.rect;
  10464. for (const quadPoint of this.data.quadPoints) {
  10465. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  10466. quadrilaterals.push(this._createContainer(ignoreBorder));
  10467. }
  10468. this.data.rect = savedRect;
  10469. return quadrilaterals;
  10470. }
  10471. _createPopup(trigger, data) {
  10472. let container = this.container;
  10473. if (this.quadrilaterals) {
  10474. trigger = trigger || this.quadrilaterals;
  10475. container = this.quadrilaterals[0];
  10476. }
  10477. if (!trigger) {
  10478. trigger = document.createElement("div");
  10479. trigger.className = "popupTriggerArea";
  10480. container.append(trigger);
  10481. }
  10482. const popupElement = new PopupElement({
  10483. container,
  10484. trigger,
  10485. color: data.color,
  10486. titleObj: data.titleObj,
  10487. modificationDate: data.modificationDate,
  10488. contentsObj: data.contentsObj,
  10489. richText: data.richText,
  10490. hideWrapper: true
  10491. });
  10492. const popup = popupElement.render();
  10493. popup.style.left = "100%";
  10494. container.append(popup);
  10495. }
  10496. _renderQuadrilaterals(className) {
  10497. for (const quadrilateral of this.quadrilaterals) {
  10498. quadrilateral.className = className;
  10499. }
  10500. return this.quadrilaterals;
  10501. }
  10502. render() {
  10503. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  10504. }
  10505. _getElementsByName(name, skipId = null) {
  10506. const fields = [];
  10507. if (this._fieldObjects) {
  10508. const fieldObj = this._fieldObjects[name];
  10509. if (fieldObj) {
  10510. for (const {
  10511. page,
  10512. id,
  10513. exportValues
  10514. } of fieldObj) {
  10515. if (page === -1) {
  10516. continue;
  10517. }
  10518. if (id === skipId) {
  10519. continue;
  10520. }
  10521. const exportValue = typeof exportValues === "string" ? exportValues : null;
  10522. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  10523. if (domElement && !GetElementsByNameSet.has(domElement)) {
  10524. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  10525. continue;
  10526. }
  10527. fields.push({
  10528. id,
  10529. exportValue,
  10530. domElement
  10531. });
  10532. }
  10533. }
  10534. return fields;
  10535. }
  10536. for (const domElement of document.getElementsByName(name)) {
  10537. const {
  10538. exportValue
  10539. } = domElement;
  10540. const id = domElement.getAttribute("data-element-id");
  10541. if (id === skipId) {
  10542. continue;
  10543. }
  10544. if (!GetElementsByNameSet.has(domElement)) {
  10545. continue;
  10546. }
  10547. fields.push({
  10548. id,
  10549. exportValue,
  10550. domElement
  10551. });
  10552. }
  10553. return fields;
  10554. }
  10555. static get platform() {
  10556. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  10557. return (0, _util.shadow)(this, "platform", {
  10558. isWin: platform.includes("Win"),
  10559. isMac: platform.includes("Mac")
  10560. });
  10561. }
  10562. }
  10563. class LinkAnnotationElement extends AnnotationElement {
  10564. constructor(parameters, options = null) {
  10565. super(parameters, {
  10566. isRenderable: true,
  10567. ignoreBorder: !!options?.ignoreBorder,
  10568. createQuadrilaterals: true
  10569. });
  10570. this.isTooltipOnly = parameters.data.isTooltipOnly;
  10571. }
  10572. render() {
  10573. const {
  10574. data,
  10575. linkService
  10576. } = this;
  10577. const link = document.createElement("a");
  10578. link.setAttribute("data-element-id", data.id);
  10579. let isBound = false;
  10580. if (data.url) {
  10581. linkService.addLinkAttributes(link, data.url, data.newWindow);
  10582. isBound = true;
  10583. } else if (data.action) {
  10584. this._bindNamedAction(link, data.action);
  10585. isBound = true;
  10586. } else if (data.attachment) {
  10587. this._bindAttachment(link, data.attachment);
  10588. isBound = true;
  10589. } else if (data.setOCGState) {
  10590. this.#bindSetOCGState(link, data.setOCGState);
  10591. isBound = true;
  10592. } else if (data.dest) {
  10593. this._bindLink(link, data.dest);
  10594. isBound = true;
  10595. } else {
  10596. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  10597. this._bindJSAction(link, data);
  10598. isBound = true;
  10599. }
  10600. if (data.resetForm) {
  10601. this._bindResetFormAction(link, data.resetForm);
  10602. isBound = true;
  10603. } else if (this.isTooltipOnly && !isBound) {
  10604. this._bindLink(link, "");
  10605. isBound = true;
  10606. }
  10607. }
  10608. if (this.quadrilaterals) {
  10609. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  10610. const linkElement = index === 0 ? link : link.cloneNode();
  10611. quadrilateral.append(linkElement);
  10612. return quadrilateral;
  10613. });
  10614. }
  10615. this.container.className = "linkAnnotation";
  10616. if (isBound) {
  10617. this.container.append(link);
  10618. }
  10619. return this.container;
  10620. }
  10621. _bindLink(link, destination) {
  10622. link.href = this.linkService.getDestinationHash(destination);
  10623. link.onclick = () => {
  10624. if (destination) {
  10625. this.linkService.goToDestination(destination);
  10626. }
  10627. return false;
  10628. };
  10629. if (destination || destination === "") {
  10630. link.className = "internalLink";
  10631. }
  10632. }
  10633. _bindNamedAction(link, action) {
  10634. link.href = this.linkService.getAnchorUrl("");
  10635. link.onclick = () => {
  10636. this.linkService.executeNamedAction(action);
  10637. return false;
  10638. };
  10639. link.className = "internalLink";
  10640. }
  10641. _bindAttachment(link, attachment) {
  10642. link.href = this.linkService.getAnchorUrl("");
  10643. link.onclick = () => {
  10644. this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
  10645. return false;
  10646. };
  10647. link.className = "internalLink";
  10648. }
  10649. #bindSetOCGState(link, action) {
  10650. link.href = this.linkService.getAnchorUrl("");
  10651. link.onclick = () => {
  10652. this.linkService.executeSetOCGState(action);
  10653. return false;
  10654. };
  10655. link.className = "internalLink";
  10656. }
  10657. _bindJSAction(link, data) {
  10658. link.href = this.linkService.getAnchorUrl("");
  10659. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  10660. for (const name of Object.keys(data.actions)) {
  10661. const jsName = map.get(name);
  10662. if (!jsName) {
  10663. continue;
  10664. }
  10665. link[jsName] = () => {
  10666. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10667. source: this,
  10668. detail: {
  10669. id: data.id,
  10670. name
  10671. }
  10672. });
  10673. return false;
  10674. };
  10675. }
  10676. if (!link.onclick) {
  10677. link.onclick = () => false;
  10678. }
  10679. link.className = "internalLink";
  10680. }
  10681. _bindResetFormAction(link, resetForm) {
  10682. const otherClickAction = link.onclick;
  10683. if (!otherClickAction) {
  10684. link.href = this.linkService.getAnchorUrl("");
  10685. }
  10686. link.className = "internalLink";
  10687. if (!this._fieldObjects) {
  10688. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  10689. if (!otherClickAction) {
  10690. link.onclick = () => false;
  10691. }
  10692. return;
  10693. }
  10694. link.onclick = () => {
  10695. otherClickAction?.();
  10696. const {
  10697. fields: resetFormFields,
  10698. refs: resetFormRefs,
  10699. include
  10700. } = resetForm;
  10701. const allFields = [];
  10702. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  10703. const fieldIds = new Set(resetFormRefs);
  10704. for (const fieldName of resetFormFields) {
  10705. const fields = this._fieldObjects[fieldName] || [];
  10706. for (const {
  10707. id
  10708. } of fields) {
  10709. fieldIds.add(id);
  10710. }
  10711. }
  10712. for (const fields of Object.values(this._fieldObjects)) {
  10713. for (const field of fields) {
  10714. if (fieldIds.has(field.id) === include) {
  10715. allFields.push(field);
  10716. }
  10717. }
  10718. }
  10719. } else {
  10720. for (const fields of Object.values(this._fieldObjects)) {
  10721. allFields.push(...fields);
  10722. }
  10723. }
  10724. const storage = this.annotationStorage;
  10725. const allIds = [];
  10726. for (const field of allFields) {
  10727. const {
  10728. id
  10729. } = field;
  10730. allIds.push(id);
  10731. switch (field.type) {
  10732. case "text":
  10733. {
  10734. const value = field.defaultValue || "";
  10735. storage.setValue(id, {
  10736. value
  10737. });
  10738. break;
  10739. }
  10740. case "checkbox":
  10741. case "radiobutton":
  10742. {
  10743. const value = field.defaultValue === field.exportValues;
  10744. storage.setValue(id, {
  10745. value
  10746. });
  10747. break;
  10748. }
  10749. case "combobox":
  10750. case "listbox":
  10751. {
  10752. const value = field.defaultValue || "";
  10753. storage.setValue(id, {
  10754. value
  10755. });
  10756. break;
  10757. }
  10758. default:
  10759. continue;
  10760. }
  10761. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  10762. if (!domElement) {
  10763. continue;
  10764. } else if (!GetElementsByNameSet.has(domElement)) {
  10765. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  10766. continue;
  10767. }
  10768. domElement.dispatchEvent(new Event("resetform"));
  10769. }
  10770. if (this.enableScripting) {
  10771. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10772. source: this,
  10773. detail: {
  10774. id: "app",
  10775. ids: allIds,
  10776. name: "ResetForm"
  10777. }
  10778. });
  10779. }
  10780. return false;
  10781. };
  10782. }
  10783. }
  10784. class TextAnnotationElement extends AnnotationElement {
  10785. constructor(parameters) {
  10786. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  10787. super(parameters, {
  10788. isRenderable
  10789. });
  10790. }
  10791. render() {
  10792. this.container.className = "textAnnotation";
  10793. const image = document.createElement("img");
  10794. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  10795. image.alt = "[{{type}} Annotation]";
  10796. image.dataset.l10nId = "text_annotation_type";
  10797. image.dataset.l10nArgs = JSON.stringify({
  10798. type: this.data.name
  10799. });
  10800. if (!this.data.hasPopup) {
  10801. this._createPopup(image, this.data);
  10802. }
  10803. this.container.append(image);
  10804. return this.container;
  10805. }
  10806. }
  10807. class WidgetAnnotationElement extends AnnotationElement {
  10808. render() {
  10809. if (this.data.alternativeText) {
  10810. this.container.title = this.data.alternativeText;
  10811. }
  10812. return this.container;
  10813. }
  10814. _getKeyModifier(event) {
  10815. const {
  10816. isWin,
  10817. isMac
  10818. } = AnnotationElement.platform;
  10819. return isWin && event.ctrlKey || isMac && event.metaKey;
  10820. }
  10821. _setEventListener(element, baseName, eventName, valueGetter) {
  10822. if (baseName.includes("mouse")) {
  10823. element.addEventListener(baseName, event => {
  10824. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10825. source: this,
  10826. detail: {
  10827. id: this.data.id,
  10828. name: eventName,
  10829. value: valueGetter(event),
  10830. shift: event.shiftKey,
  10831. modifier: this._getKeyModifier(event)
  10832. }
  10833. });
  10834. });
  10835. } else {
  10836. element.addEventListener(baseName, event => {
  10837. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  10838. source: this,
  10839. detail: {
  10840. id: this.data.id,
  10841. name: eventName,
  10842. value: valueGetter(event)
  10843. }
  10844. });
  10845. });
  10846. }
  10847. }
  10848. _setEventListeners(element, names, getter) {
  10849. for (const [baseName, eventName] of names) {
  10850. if (eventName === "Action" || this.data.actions?.[eventName]) {
  10851. this._setEventListener(element, baseName, eventName, getter);
  10852. }
  10853. }
  10854. }
  10855. _setBackgroundColor(element) {
  10856. const color = this.data.backgroundColor || null;
  10857. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  10858. }
  10859. _setTextStyle(element) {
  10860. const TEXT_ALIGNMENT = ["left", "center", "right"];
  10861. const {
  10862. fontColor
  10863. } = this.data.defaultAppearanceData;
  10864. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  10865. const style = element.style;
  10866. let computedFontSize;
  10867. const BORDER_SIZE = 2;
  10868. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  10869. if (this.data.multiLine) {
  10870. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  10871. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  10872. const lineHeight = height / numberOfLines;
  10873. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
  10874. } else {
  10875. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  10876. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
  10877. }
  10878. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  10879. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  10880. if (this.data.textAlignment !== null) {
  10881. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  10882. }
  10883. }
  10884. _setRequired(element, isRequired) {
  10885. if (isRequired) {
  10886. element.setAttribute("required", true);
  10887. } else {
  10888. element.removeAttribute("required");
  10889. }
  10890. element.setAttribute("aria-required", isRequired);
  10891. }
  10892. }
  10893. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  10894. constructor(parameters) {
  10895. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  10896. super(parameters, {
  10897. isRenderable
  10898. });
  10899. }
  10900. setPropertyOnSiblings(base, key, value, keyInStorage) {
  10901. const storage = this.annotationStorage;
  10902. for (const element of this._getElementsByName(base.name, base.id)) {
  10903. if (element.domElement) {
  10904. element.domElement[key] = value;
  10905. }
  10906. storage.setValue(element.id, {
  10907. [keyInStorage]: value
  10908. });
  10909. }
  10910. }
  10911. render() {
  10912. const storage = this.annotationStorage;
  10913. const id = this.data.id;
  10914. this.container.className = "textWidgetAnnotation";
  10915. let element = null;
  10916. if (this.renderForms) {
  10917. const storedData = storage.getValue(id, {
  10918. value: this.data.fieldValue
  10919. });
  10920. let textContent = storedData.formattedValue || storedData.value || "";
  10921. const maxLen = storage.getValue(id, {
  10922. charLimit: this.data.maxLen
  10923. }).charLimit;
  10924. if (maxLen && textContent.length > maxLen) {
  10925. textContent = textContent.slice(0, maxLen);
  10926. }
  10927. const elementData = {
  10928. userValue: textContent,
  10929. formattedValue: null,
  10930. valueOnFocus: ""
  10931. };
  10932. if (this.data.multiLine) {
  10933. element = document.createElement("textarea");
  10934. element.textContent = textContent;
  10935. if (this.data.doNotScroll) {
  10936. element.style.overflowY = "hidden";
  10937. }
  10938. } else {
  10939. element = document.createElement("input");
  10940. element.type = "text";
  10941. element.setAttribute("value", textContent);
  10942. if (this.data.doNotScroll) {
  10943. element.style.overflowX = "hidden";
  10944. }
  10945. }
  10946. GetElementsByNameSet.add(element);
  10947. element.setAttribute("data-element-id", id);
  10948. element.disabled = this.data.readOnly;
  10949. element.name = this.data.fieldName;
  10950. element.tabIndex = DEFAULT_TAB_INDEX;
  10951. this._setRequired(element, this.data.required);
  10952. if (maxLen) {
  10953. element.maxLength = maxLen;
  10954. }
  10955. element.addEventListener("input", event => {
  10956. storage.setValue(id, {
  10957. value: event.target.value
  10958. });
  10959. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  10960. });
  10961. element.addEventListener("resetform", event => {
  10962. const defaultValue = this.data.defaultFieldValue ?? "";
  10963. element.value = elementData.userValue = defaultValue;
  10964. elementData.formattedValue = null;
  10965. });
  10966. let blurListener = event => {
  10967. const {
  10968. formattedValue
  10969. } = elementData;
  10970. if (formattedValue !== null && formattedValue !== undefined) {
  10971. event.target.value = formattedValue;
  10972. }
  10973. event.target.scrollLeft = 0;
  10974. };
  10975. if (this.enableScripting && this.hasJSActions) {
  10976. element.addEventListener("focus", event => {
  10977. if (elementData.userValue) {
  10978. event.target.value = elementData.userValue;
  10979. }
  10980. elementData.valueOnFocus = event.target.value;
  10981. });
  10982. element.addEventListener("updatefromsandbox", jsEvent => {
  10983. const actions = {
  10984. value(event) {
  10985. elementData.userValue = event.detail.value ?? "";
  10986. storage.setValue(id, {
  10987. value: elementData.userValue.toString()
  10988. });
  10989. event.target.value = elementData.userValue;
  10990. },
  10991. formattedValue(event) {
  10992. const {
  10993. formattedValue
  10994. } = event.detail;
  10995. elementData.formattedValue = formattedValue;
  10996. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  10997. event.target.value = formattedValue;
  10998. }
  10999. storage.setValue(id, {
  11000. formattedValue
  11001. });
  11002. },
  11003. selRange(event) {
  11004. event.target.setSelectionRange(...event.detail.selRange);
  11005. },
  11006. charLimit: event => {
  11007. const {
  11008. charLimit
  11009. } = event.detail;
  11010. const {
  11011. target
  11012. } = event;
  11013. if (charLimit === 0) {
  11014. target.removeAttribute("maxLength");
  11015. return;
  11016. }
  11017. target.setAttribute("maxLength", charLimit);
  11018. let value = elementData.userValue;
  11019. if (!value || value.length <= charLimit) {
  11020. return;
  11021. }
  11022. value = value.slice(0, charLimit);
  11023. target.value = elementData.userValue = value;
  11024. storage.setValue(id, {
  11025. value
  11026. });
  11027. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11028. source: this,
  11029. detail: {
  11030. id,
  11031. name: "Keystroke",
  11032. value,
  11033. willCommit: true,
  11034. commitKey: 1,
  11035. selStart: target.selectionStart,
  11036. selEnd: target.selectionEnd
  11037. }
  11038. });
  11039. }
  11040. };
  11041. this._dispatchEventFromSandbox(actions, jsEvent);
  11042. });
  11043. element.addEventListener("keydown", event => {
  11044. let commitKey = -1;
  11045. if (event.key === "Escape") {
  11046. commitKey = 0;
  11047. } else if (event.key === "Enter" && !this.data.multiLine) {
  11048. commitKey = 2;
  11049. } else if (event.key === "Tab") {
  11050. commitKey = 3;
  11051. }
  11052. if (commitKey === -1) {
  11053. return;
  11054. }
  11055. const {
  11056. value
  11057. } = event.target;
  11058. if (elementData.valueOnFocus === value) {
  11059. return;
  11060. }
  11061. elementData.userValue = value;
  11062. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11063. source: this,
  11064. detail: {
  11065. id,
  11066. name: "Keystroke",
  11067. value,
  11068. willCommit: true,
  11069. commitKey,
  11070. selStart: event.target.selectionStart,
  11071. selEnd: event.target.selectionEnd
  11072. }
  11073. });
  11074. });
  11075. const _blurListener = blurListener;
  11076. blurListener = null;
  11077. element.addEventListener("blur", event => {
  11078. const {
  11079. value
  11080. } = event.target;
  11081. elementData.userValue = value;
  11082. if (this._mouseState.isDown && elementData.valueOnFocus !== value) {
  11083. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11084. source: this,
  11085. detail: {
  11086. id,
  11087. name: "Keystroke",
  11088. value,
  11089. willCommit: true,
  11090. commitKey: 1,
  11091. selStart: event.target.selectionStart,
  11092. selEnd: event.target.selectionEnd
  11093. }
  11094. });
  11095. }
  11096. _blurListener(event);
  11097. });
  11098. if (this.data.actions?.Keystroke) {
  11099. element.addEventListener("beforeinput", event => {
  11100. const {
  11101. data,
  11102. target
  11103. } = event;
  11104. const {
  11105. value,
  11106. selectionStart,
  11107. selectionEnd
  11108. } = target;
  11109. let selStart = selectionStart,
  11110. selEnd = selectionEnd;
  11111. switch (event.inputType) {
  11112. case "deleteWordBackward":
  11113. {
  11114. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  11115. if (match) {
  11116. selStart -= match[0].length;
  11117. }
  11118. break;
  11119. }
  11120. case "deleteWordForward":
  11121. {
  11122. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  11123. if (match) {
  11124. selEnd += match[0].length;
  11125. }
  11126. break;
  11127. }
  11128. case "deleteContentBackward":
  11129. if (selectionStart === selectionEnd) {
  11130. selStart -= 1;
  11131. }
  11132. break;
  11133. case "deleteContentForward":
  11134. if (selectionStart === selectionEnd) {
  11135. selEnd += 1;
  11136. }
  11137. break;
  11138. }
  11139. event.preventDefault();
  11140. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11141. source: this,
  11142. detail: {
  11143. id,
  11144. name: "Keystroke",
  11145. value,
  11146. change: data || "",
  11147. willCommit: false,
  11148. selStart,
  11149. selEnd
  11150. }
  11151. });
  11152. });
  11153. }
  11154. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  11155. }
  11156. if (blurListener) {
  11157. element.addEventListener("blur", blurListener);
  11158. }
  11159. if (this.data.comb) {
  11160. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  11161. const combWidth = fieldWidth / maxLen;
  11162. element.classList.add("comb");
  11163. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  11164. }
  11165. } else {
  11166. element = document.createElement("div");
  11167. element.textContent = this.data.fieldValue;
  11168. element.style.verticalAlign = "middle";
  11169. element.style.display = "table-cell";
  11170. }
  11171. this._setTextStyle(element);
  11172. this._setBackgroundColor(element);
  11173. this._setDefaultPropertiesFromJS(element);
  11174. this.container.append(element);
  11175. return this.container;
  11176. }
  11177. }
  11178. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  11179. constructor(parameters) {
  11180. super(parameters, {
  11181. isRenderable: parameters.renderForms
  11182. });
  11183. }
  11184. render() {
  11185. const storage = this.annotationStorage;
  11186. const data = this.data;
  11187. const id = data.id;
  11188. let value = storage.getValue(id, {
  11189. value: data.exportValue === data.fieldValue
  11190. }).value;
  11191. if (typeof value === "string") {
  11192. value = value !== "Off";
  11193. storage.setValue(id, {
  11194. value
  11195. });
  11196. }
  11197. this.container.className = "buttonWidgetAnnotation checkBox";
  11198. const element = document.createElement("input");
  11199. GetElementsByNameSet.add(element);
  11200. element.setAttribute("data-element-id", id);
  11201. element.disabled = data.readOnly;
  11202. this._setRequired(element, this.data.required);
  11203. element.type = "checkbox";
  11204. element.name = data.fieldName;
  11205. if (value) {
  11206. element.setAttribute("checked", true);
  11207. }
  11208. element.setAttribute("exportValue", data.exportValue);
  11209. element.tabIndex = DEFAULT_TAB_INDEX;
  11210. element.addEventListener("change", event => {
  11211. const {
  11212. name,
  11213. checked
  11214. } = event.target;
  11215. for (const checkbox of this._getElementsByName(name, id)) {
  11216. const curChecked = checked && checkbox.exportValue === data.exportValue;
  11217. if (checkbox.domElement) {
  11218. checkbox.domElement.checked = curChecked;
  11219. }
  11220. storage.setValue(checkbox.id, {
  11221. value: curChecked
  11222. });
  11223. }
  11224. storage.setValue(id, {
  11225. value: checked
  11226. });
  11227. });
  11228. element.addEventListener("resetform", event => {
  11229. const defaultValue = data.defaultFieldValue || "Off";
  11230. event.target.checked = defaultValue === data.exportValue;
  11231. });
  11232. if (this.enableScripting && this.hasJSActions) {
  11233. element.addEventListener("updatefromsandbox", jsEvent => {
  11234. const actions = {
  11235. value(event) {
  11236. event.target.checked = event.detail.value !== "Off";
  11237. storage.setValue(id, {
  11238. value: event.target.checked
  11239. });
  11240. }
  11241. };
  11242. this._dispatchEventFromSandbox(actions, jsEvent);
  11243. });
  11244. 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);
  11245. }
  11246. this._setBackgroundColor(element);
  11247. this._setDefaultPropertiesFromJS(element);
  11248. this.container.append(element);
  11249. return this.container;
  11250. }
  11251. }
  11252. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  11253. constructor(parameters) {
  11254. super(parameters, {
  11255. isRenderable: parameters.renderForms
  11256. });
  11257. }
  11258. render() {
  11259. this.container.className = "buttonWidgetAnnotation radioButton";
  11260. const storage = this.annotationStorage;
  11261. const data = this.data;
  11262. const id = data.id;
  11263. let value = storage.getValue(id, {
  11264. value: data.fieldValue === data.buttonValue
  11265. }).value;
  11266. if (typeof value === "string") {
  11267. value = value !== data.buttonValue;
  11268. storage.setValue(id, {
  11269. value
  11270. });
  11271. }
  11272. const element = document.createElement("input");
  11273. GetElementsByNameSet.add(element);
  11274. element.setAttribute("data-element-id", id);
  11275. element.disabled = data.readOnly;
  11276. this._setRequired(element, this.data.required);
  11277. element.type = "radio";
  11278. element.name = data.fieldName;
  11279. if (value) {
  11280. element.setAttribute("checked", true);
  11281. }
  11282. element.tabIndex = DEFAULT_TAB_INDEX;
  11283. element.addEventListener("change", event => {
  11284. const {
  11285. name,
  11286. checked
  11287. } = event.target;
  11288. for (const radio of this._getElementsByName(name, id)) {
  11289. storage.setValue(radio.id, {
  11290. value: false
  11291. });
  11292. }
  11293. storage.setValue(id, {
  11294. value: checked
  11295. });
  11296. });
  11297. element.addEventListener("resetform", event => {
  11298. const defaultValue = data.defaultFieldValue;
  11299. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  11300. });
  11301. if (this.enableScripting && this.hasJSActions) {
  11302. const pdfButtonValue = data.buttonValue;
  11303. element.addEventListener("updatefromsandbox", jsEvent => {
  11304. const actions = {
  11305. value: event => {
  11306. const checked = pdfButtonValue === event.detail.value;
  11307. for (const radio of this._getElementsByName(event.target.name)) {
  11308. const curChecked = checked && radio.id === id;
  11309. if (radio.domElement) {
  11310. radio.domElement.checked = curChecked;
  11311. }
  11312. storage.setValue(radio.id, {
  11313. value: curChecked
  11314. });
  11315. }
  11316. }
  11317. };
  11318. this._dispatchEventFromSandbox(actions, jsEvent);
  11319. });
  11320. 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);
  11321. }
  11322. this._setBackgroundColor(element);
  11323. this._setDefaultPropertiesFromJS(element);
  11324. this.container.append(element);
  11325. return this.container;
  11326. }
  11327. }
  11328. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  11329. constructor(parameters) {
  11330. super(parameters, {
  11331. ignoreBorder: parameters.data.hasAppearance
  11332. });
  11333. }
  11334. render() {
  11335. const container = super.render();
  11336. container.className = "buttonWidgetAnnotation pushButton";
  11337. if (this.data.alternativeText) {
  11338. container.title = this.data.alternativeText;
  11339. }
  11340. const linkElement = container.lastChild;
  11341. if (this.enableScripting && this.hasJSActions && linkElement) {
  11342. this._setDefaultPropertiesFromJS(linkElement);
  11343. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  11344. this._dispatchEventFromSandbox({}, jsEvent);
  11345. });
  11346. }
  11347. return container;
  11348. }
  11349. }
  11350. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  11351. constructor(parameters) {
  11352. super(parameters, {
  11353. isRenderable: parameters.renderForms
  11354. });
  11355. }
  11356. render() {
  11357. this.container.className = "choiceWidgetAnnotation";
  11358. const storage = this.annotationStorage;
  11359. const id = this.data.id;
  11360. const storedData = storage.getValue(id, {
  11361. value: this.data.fieldValue
  11362. });
  11363. const selectElement = document.createElement("select");
  11364. GetElementsByNameSet.add(selectElement);
  11365. selectElement.setAttribute("data-element-id", id);
  11366. selectElement.disabled = this.data.readOnly;
  11367. this._setRequired(selectElement, this.data.required);
  11368. selectElement.name = this.data.fieldName;
  11369. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  11370. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  11371. if (!this.data.combo) {
  11372. selectElement.size = this.data.options.length;
  11373. if (this.data.multiSelect) {
  11374. selectElement.multiple = true;
  11375. }
  11376. }
  11377. selectElement.addEventListener("resetform", event => {
  11378. const defaultValue = this.data.defaultFieldValue;
  11379. for (const option of selectElement.options) {
  11380. option.selected = option.value === defaultValue;
  11381. }
  11382. });
  11383. for (const option of this.data.options) {
  11384. const optionElement = document.createElement("option");
  11385. optionElement.textContent = option.displayValue;
  11386. optionElement.value = option.exportValue;
  11387. if (storedData.value.includes(option.exportValue)) {
  11388. optionElement.setAttribute("selected", true);
  11389. addAnEmptyEntry = false;
  11390. }
  11391. selectElement.append(optionElement);
  11392. }
  11393. let removeEmptyEntry = null;
  11394. if (addAnEmptyEntry) {
  11395. const noneOptionElement = document.createElement("option");
  11396. noneOptionElement.value = " ";
  11397. noneOptionElement.setAttribute("hidden", true);
  11398. noneOptionElement.setAttribute("selected", true);
  11399. selectElement.prepend(noneOptionElement);
  11400. removeEmptyEntry = () => {
  11401. noneOptionElement.remove();
  11402. selectElement.removeEventListener("input", removeEmptyEntry);
  11403. removeEmptyEntry = null;
  11404. };
  11405. selectElement.addEventListener("input", removeEmptyEntry);
  11406. }
  11407. const getValue = (event, isExport) => {
  11408. const name = isExport ? "value" : "textContent";
  11409. const options = event.target.options;
  11410. if (!event.target.multiple) {
  11411. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  11412. }
  11413. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  11414. };
  11415. const getItems = event => {
  11416. const options = event.target.options;
  11417. return Array.prototype.map.call(options, option => {
  11418. return {
  11419. displayValue: option.textContent,
  11420. exportValue: option.value
  11421. };
  11422. });
  11423. };
  11424. if (this.enableScripting && this.hasJSActions) {
  11425. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  11426. const actions = {
  11427. value(event) {
  11428. removeEmptyEntry?.();
  11429. const value = event.detail.value;
  11430. const values = new Set(Array.isArray(value) ? value : [value]);
  11431. for (const option of selectElement.options) {
  11432. option.selected = values.has(option.value);
  11433. }
  11434. storage.setValue(id, {
  11435. value: getValue(event, true)
  11436. });
  11437. },
  11438. multipleSelection(event) {
  11439. selectElement.multiple = true;
  11440. },
  11441. remove(event) {
  11442. const options = selectElement.options;
  11443. const index = event.detail.remove;
  11444. options[index].selected = false;
  11445. selectElement.remove(index);
  11446. if (options.length > 0) {
  11447. const i = Array.prototype.findIndex.call(options, option => option.selected);
  11448. if (i === -1) {
  11449. options[0].selected = true;
  11450. }
  11451. }
  11452. storage.setValue(id, {
  11453. value: getValue(event, true),
  11454. items: getItems(event)
  11455. });
  11456. },
  11457. clear(event) {
  11458. while (selectElement.length !== 0) {
  11459. selectElement.remove(0);
  11460. }
  11461. storage.setValue(id, {
  11462. value: null,
  11463. items: []
  11464. });
  11465. },
  11466. insert(event) {
  11467. const {
  11468. index,
  11469. displayValue,
  11470. exportValue
  11471. } = event.detail.insert;
  11472. const selectChild = selectElement.children[index];
  11473. const optionElement = document.createElement("option");
  11474. optionElement.textContent = displayValue;
  11475. optionElement.value = exportValue;
  11476. if (selectChild) {
  11477. selectChild.before(optionElement);
  11478. } else {
  11479. selectElement.append(optionElement);
  11480. }
  11481. storage.setValue(id, {
  11482. value: getValue(event, true),
  11483. items: getItems(event)
  11484. });
  11485. },
  11486. items(event) {
  11487. const {
  11488. items
  11489. } = event.detail;
  11490. while (selectElement.length !== 0) {
  11491. selectElement.remove(0);
  11492. }
  11493. for (const item of items) {
  11494. const {
  11495. displayValue,
  11496. exportValue
  11497. } = item;
  11498. const optionElement = document.createElement("option");
  11499. optionElement.textContent = displayValue;
  11500. optionElement.value = exportValue;
  11501. selectElement.append(optionElement);
  11502. }
  11503. if (selectElement.options.length > 0) {
  11504. selectElement.options[0].selected = true;
  11505. }
  11506. storage.setValue(id, {
  11507. value: getValue(event, true),
  11508. items: getItems(event)
  11509. });
  11510. },
  11511. indices(event) {
  11512. const indices = new Set(event.detail.indices);
  11513. for (const option of event.target.options) {
  11514. option.selected = indices.has(option.index);
  11515. }
  11516. storage.setValue(id, {
  11517. value: getValue(event, true)
  11518. });
  11519. },
  11520. editable(event) {
  11521. event.target.disabled = !event.detail.editable;
  11522. }
  11523. };
  11524. this._dispatchEventFromSandbox(actions, jsEvent);
  11525. });
  11526. selectElement.addEventListener("input", event => {
  11527. const exportValue = getValue(event, true);
  11528. const value = getValue(event, false);
  11529. storage.setValue(id, {
  11530. value: exportValue
  11531. });
  11532. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11533. source: this,
  11534. detail: {
  11535. id,
  11536. name: "Keystroke",
  11537. value,
  11538. changeEx: exportValue,
  11539. willCommit: true,
  11540. commitKey: 1,
  11541. keyDown: false
  11542. }
  11543. });
  11544. });
  11545. this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked);
  11546. } else {
  11547. selectElement.addEventListener("input", function (event) {
  11548. storage.setValue(id, {
  11549. value: getValue(event, true)
  11550. });
  11551. });
  11552. }
  11553. if (this.data.combo) {
  11554. this._setTextStyle(selectElement);
  11555. } else {}
  11556. this._setBackgroundColor(selectElement);
  11557. this._setDefaultPropertiesFromJS(selectElement);
  11558. this.container.append(selectElement);
  11559. return this.container;
  11560. }
  11561. }
  11562. class PopupAnnotationElement extends AnnotationElement {
  11563. static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
  11564. constructor(parameters) {
  11565. const {
  11566. data
  11567. } = parameters;
  11568. const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  11569. super(parameters, {
  11570. isRenderable
  11571. });
  11572. }
  11573. render() {
  11574. this.container.className = "popupAnnotation";
  11575. const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
  11576. if (parentElements.length === 0) {
  11577. return this.container;
  11578. }
  11579. const popup = new PopupElement({
  11580. container: this.container,
  11581. trigger: Array.from(parentElements),
  11582. color: this.data.color,
  11583. titleObj: this.data.titleObj,
  11584. modificationDate: this.data.modificationDate,
  11585. contentsObj: this.data.contentsObj,
  11586. richText: this.data.richText
  11587. });
  11588. const page = this.page;
  11589. const rect = _util.Util.normalizeRect([this.data.parentRect[0], page.view[3] - this.data.parentRect[1] + page.view[1], this.data.parentRect[2], page.view[3] - this.data.parentRect[3] + page.view[1]]);
  11590. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  11591. const popupTop = rect[1];
  11592. const [pageLLx, pageLLy, pageURx, pageURy] = this.viewport.viewBox;
  11593. const pageWidth = pageURx - pageLLx;
  11594. const pageHeight = pageURy - pageLLy;
  11595. this.container.style.left = `${100 * (popupLeft - pageLLx) / pageWidth}%`;
  11596. this.container.style.top = `${100 * (popupTop - pageLLy) / pageHeight}%`;
  11597. this.container.append(popup.render());
  11598. return this.container;
  11599. }
  11600. }
  11601. class PopupElement {
  11602. constructor(parameters) {
  11603. this.container = parameters.container;
  11604. this.trigger = parameters.trigger;
  11605. this.color = parameters.color;
  11606. this.titleObj = parameters.titleObj;
  11607. this.modificationDate = parameters.modificationDate;
  11608. this.contentsObj = parameters.contentsObj;
  11609. this.richText = parameters.richText;
  11610. this.hideWrapper = parameters.hideWrapper || false;
  11611. this.pinned = false;
  11612. }
  11613. render() {
  11614. const BACKGROUND_ENLIGHT = 0.7;
  11615. const wrapper = document.createElement("div");
  11616. wrapper.className = "popupWrapper";
  11617. this.hideElement = this.hideWrapper ? wrapper : this.container;
  11618. this.hideElement.hidden = true;
  11619. const popup = document.createElement("div");
  11620. popup.className = "popup";
  11621. const color = this.color;
  11622. if (color) {
  11623. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  11624. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  11625. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  11626. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  11627. }
  11628. const title = document.createElement("h1");
  11629. title.dir = this.titleObj.dir;
  11630. title.textContent = this.titleObj.str;
  11631. popup.append(title);
  11632. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  11633. if (dateObject) {
  11634. const modificationDate = document.createElement("span");
  11635. modificationDate.className = "popupDate";
  11636. modificationDate.textContent = "{{date}}, {{time}}";
  11637. modificationDate.dataset.l10nId = "annotation_date_string";
  11638. modificationDate.dataset.l10nArgs = JSON.stringify({
  11639. date: dateObject.toLocaleDateString(),
  11640. time: dateObject.toLocaleTimeString()
  11641. });
  11642. popup.append(modificationDate);
  11643. }
  11644. if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
  11645. _xfa_layer.XfaLayer.render({
  11646. xfaHtml: this.richText.html,
  11647. intent: "richText",
  11648. div: popup
  11649. });
  11650. popup.lastChild.className = "richText popupContent";
  11651. } else {
  11652. const contents = this._formatContents(this.contentsObj);
  11653. popup.append(contents);
  11654. }
  11655. if (!Array.isArray(this.trigger)) {
  11656. this.trigger = [this.trigger];
  11657. }
  11658. for (const element of this.trigger) {
  11659. element.addEventListener("click", this._toggle.bind(this));
  11660. element.addEventListener("mouseover", this._show.bind(this, false));
  11661. element.addEventListener("mouseout", this._hide.bind(this, false));
  11662. }
  11663. popup.addEventListener("click", this._hide.bind(this, true));
  11664. wrapper.append(popup);
  11665. return wrapper;
  11666. }
  11667. _formatContents({
  11668. str,
  11669. dir
  11670. }) {
  11671. const p = document.createElement("p");
  11672. p.className = "popupContent";
  11673. p.dir = dir;
  11674. const lines = str.split(/(?:\r\n?|\n)/);
  11675. for (let i = 0, ii = lines.length; i < ii; ++i) {
  11676. const line = lines[i];
  11677. p.append(document.createTextNode(line));
  11678. if (i < ii - 1) {
  11679. p.append(document.createElement("br"));
  11680. }
  11681. }
  11682. return p;
  11683. }
  11684. _toggle() {
  11685. if (this.pinned) {
  11686. this._hide(true);
  11687. } else {
  11688. this._show(true);
  11689. }
  11690. }
  11691. _show(pin = false) {
  11692. if (pin) {
  11693. this.pinned = true;
  11694. }
  11695. if (this.hideElement.hidden) {
  11696. this.hideElement.hidden = false;
  11697. this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
  11698. }
  11699. }
  11700. _hide(unpin = true) {
  11701. if (unpin) {
  11702. this.pinned = false;
  11703. }
  11704. if (!this.hideElement.hidden && !this.pinned) {
  11705. this.hideElement.hidden = true;
  11706. this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
  11707. }
  11708. }
  11709. }
  11710. class FreeTextAnnotationElement extends AnnotationElement {
  11711. constructor(parameters) {
  11712. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11713. super(parameters, {
  11714. isRenderable,
  11715. ignoreBorder: true
  11716. });
  11717. this.textContent = parameters.data.textContent;
  11718. }
  11719. render() {
  11720. this.container.className = "freeTextAnnotation";
  11721. if (this.textContent) {
  11722. const content = document.createElement("div");
  11723. content.className = "annotationTextContent";
  11724. content.setAttribute("role", "comment");
  11725. for (const line of this.textContent) {
  11726. const lineSpan = document.createElement("span");
  11727. lineSpan.textContent = line;
  11728. content.append(lineSpan);
  11729. }
  11730. this.container.append(content);
  11731. }
  11732. if (!this.data.hasPopup) {
  11733. this._createPopup(null, this.data);
  11734. }
  11735. return this.container;
  11736. }
  11737. }
  11738. class LineAnnotationElement extends AnnotationElement {
  11739. constructor(parameters) {
  11740. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11741. super(parameters, {
  11742. isRenderable,
  11743. ignoreBorder: true
  11744. });
  11745. }
  11746. render() {
  11747. this.container.className = "lineAnnotation";
  11748. const data = this.data;
  11749. const {
  11750. width,
  11751. height
  11752. } = getRectDims(data.rect);
  11753. const svg = this.svgFactory.create(width, height, true);
  11754. const line = this.svgFactory.createElement("svg:line");
  11755. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  11756. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  11757. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  11758. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  11759. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  11760. line.setAttribute("stroke", "transparent");
  11761. line.setAttribute("fill", "transparent");
  11762. svg.append(line);
  11763. this.container.append(svg);
  11764. this._createPopup(line, data);
  11765. return this.container;
  11766. }
  11767. }
  11768. class SquareAnnotationElement extends AnnotationElement {
  11769. constructor(parameters) {
  11770. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11771. super(parameters, {
  11772. isRenderable,
  11773. ignoreBorder: true
  11774. });
  11775. }
  11776. render() {
  11777. this.container.className = "squareAnnotation";
  11778. const data = this.data;
  11779. const {
  11780. width,
  11781. height
  11782. } = getRectDims(data.rect);
  11783. const svg = this.svgFactory.create(width, height, true);
  11784. const borderWidth = data.borderStyle.width;
  11785. const square = this.svgFactory.createElement("svg:rect");
  11786. square.setAttribute("x", borderWidth / 2);
  11787. square.setAttribute("y", borderWidth / 2);
  11788. square.setAttribute("width", width - borderWidth);
  11789. square.setAttribute("height", height - borderWidth);
  11790. square.setAttribute("stroke-width", borderWidth || 1);
  11791. square.setAttribute("stroke", "transparent");
  11792. square.setAttribute("fill", "transparent");
  11793. svg.append(square);
  11794. this.container.append(svg);
  11795. this._createPopup(square, data);
  11796. return this.container;
  11797. }
  11798. }
  11799. class CircleAnnotationElement extends AnnotationElement {
  11800. constructor(parameters) {
  11801. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11802. super(parameters, {
  11803. isRenderable,
  11804. ignoreBorder: true
  11805. });
  11806. }
  11807. render() {
  11808. this.container.className = "circleAnnotation";
  11809. const data = this.data;
  11810. const {
  11811. width,
  11812. height
  11813. } = getRectDims(data.rect);
  11814. const svg = this.svgFactory.create(width, height, true);
  11815. const borderWidth = data.borderStyle.width;
  11816. const circle = this.svgFactory.createElement("svg:ellipse");
  11817. circle.setAttribute("cx", width / 2);
  11818. circle.setAttribute("cy", height / 2);
  11819. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  11820. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  11821. circle.setAttribute("stroke-width", borderWidth || 1);
  11822. circle.setAttribute("stroke", "transparent");
  11823. circle.setAttribute("fill", "transparent");
  11824. svg.append(circle);
  11825. this.container.append(svg);
  11826. this._createPopup(circle, data);
  11827. return this.container;
  11828. }
  11829. }
  11830. class PolylineAnnotationElement extends AnnotationElement {
  11831. constructor(parameters) {
  11832. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11833. super(parameters, {
  11834. isRenderable,
  11835. ignoreBorder: true
  11836. });
  11837. this.containerClassName = "polylineAnnotation";
  11838. this.svgElementName = "svg:polyline";
  11839. }
  11840. render() {
  11841. this.container.className = this.containerClassName;
  11842. const data = this.data;
  11843. const {
  11844. width,
  11845. height
  11846. } = getRectDims(data.rect);
  11847. const svg = this.svgFactory.create(width, height, true);
  11848. let points = [];
  11849. for (const coordinate of data.vertices) {
  11850. const x = coordinate.x - data.rect[0];
  11851. const y = data.rect[3] - coordinate.y;
  11852. points.push(x + "," + y);
  11853. }
  11854. points = points.join(" ");
  11855. const polyline = this.svgFactory.createElement(this.svgElementName);
  11856. polyline.setAttribute("points", points);
  11857. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  11858. polyline.setAttribute("stroke", "transparent");
  11859. polyline.setAttribute("fill", "transparent");
  11860. svg.append(polyline);
  11861. this.container.append(svg);
  11862. this._createPopup(polyline, data);
  11863. return this.container;
  11864. }
  11865. }
  11866. class PolygonAnnotationElement extends PolylineAnnotationElement {
  11867. constructor(parameters) {
  11868. super(parameters);
  11869. this.containerClassName = "polygonAnnotation";
  11870. this.svgElementName = "svg:polygon";
  11871. }
  11872. }
  11873. class CaretAnnotationElement extends AnnotationElement {
  11874. constructor(parameters) {
  11875. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11876. super(parameters, {
  11877. isRenderable,
  11878. ignoreBorder: true
  11879. });
  11880. }
  11881. render() {
  11882. this.container.className = "caretAnnotation";
  11883. if (!this.data.hasPopup) {
  11884. this._createPopup(null, this.data);
  11885. }
  11886. return this.container;
  11887. }
  11888. }
  11889. class InkAnnotationElement extends AnnotationElement {
  11890. constructor(parameters) {
  11891. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11892. super(parameters, {
  11893. isRenderable,
  11894. ignoreBorder: true
  11895. });
  11896. this.containerClassName = "inkAnnotation";
  11897. this.svgElementName = "svg:polyline";
  11898. }
  11899. render() {
  11900. this.container.className = this.containerClassName;
  11901. const data = this.data;
  11902. const {
  11903. width,
  11904. height
  11905. } = getRectDims(data.rect);
  11906. const svg = this.svgFactory.create(width, height, true);
  11907. for (const inkList of data.inkLists) {
  11908. let points = [];
  11909. for (const coordinate of inkList) {
  11910. const x = coordinate.x - data.rect[0];
  11911. const y = data.rect[3] - coordinate.y;
  11912. points.push(`${x},${y}`);
  11913. }
  11914. points = points.join(" ");
  11915. const polyline = this.svgFactory.createElement(this.svgElementName);
  11916. polyline.setAttribute("points", points);
  11917. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  11918. polyline.setAttribute("stroke", "transparent");
  11919. polyline.setAttribute("fill", "transparent");
  11920. this._createPopup(polyline, data);
  11921. svg.append(polyline);
  11922. }
  11923. this.container.append(svg);
  11924. return this.container;
  11925. }
  11926. }
  11927. class HighlightAnnotationElement extends AnnotationElement {
  11928. constructor(parameters) {
  11929. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11930. super(parameters, {
  11931. isRenderable,
  11932. ignoreBorder: true,
  11933. createQuadrilaterals: true
  11934. });
  11935. }
  11936. render() {
  11937. if (!this.data.hasPopup) {
  11938. this._createPopup(null, this.data);
  11939. }
  11940. if (this.quadrilaterals) {
  11941. return this._renderQuadrilaterals("highlightAnnotation");
  11942. }
  11943. this.container.className = "highlightAnnotation";
  11944. return this.container;
  11945. }
  11946. }
  11947. class UnderlineAnnotationElement extends AnnotationElement {
  11948. constructor(parameters) {
  11949. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11950. super(parameters, {
  11951. isRenderable,
  11952. ignoreBorder: true,
  11953. createQuadrilaterals: true
  11954. });
  11955. }
  11956. render() {
  11957. if (!this.data.hasPopup) {
  11958. this._createPopup(null, this.data);
  11959. }
  11960. if (this.quadrilaterals) {
  11961. return this._renderQuadrilaterals("underlineAnnotation");
  11962. }
  11963. this.container.className = "underlineAnnotation";
  11964. return this.container;
  11965. }
  11966. }
  11967. class SquigglyAnnotationElement extends AnnotationElement {
  11968. constructor(parameters) {
  11969. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11970. super(parameters, {
  11971. isRenderable,
  11972. ignoreBorder: true,
  11973. createQuadrilaterals: true
  11974. });
  11975. }
  11976. render() {
  11977. if (!this.data.hasPopup) {
  11978. this._createPopup(null, this.data);
  11979. }
  11980. if (this.quadrilaterals) {
  11981. return this._renderQuadrilaterals("squigglyAnnotation");
  11982. }
  11983. this.container.className = "squigglyAnnotation";
  11984. return this.container;
  11985. }
  11986. }
  11987. class StrikeOutAnnotationElement extends AnnotationElement {
  11988. constructor(parameters) {
  11989. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11990. super(parameters, {
  11991. isRenderable,
  11992. ignoreBorder: true,
  11993. createQuadrilaterals: true
  11994. });
  11995. }
  11996. render() {
  11997. if (!this.data.hasPopup) {
  11998. this._createPopup(null, this.data);
  11999. }
  12000. if (this.quadrilaterals) {
  12001. return this._renderQuadrilaterals("strikeoutAnnotation");
  12002. }
  12003. this.container.className = "strikeoutAnnotation";
  12004. return this.container;
  12005. }
  12006. }
  12007. class StampAnnotationElement extends AnnotationElement {
  12008. constructor(parameters) {
  12009. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12010. super(parameters, {
  12011. isRenderable,
  12012. ignoreBorder: true
  12013. });
  12014. }
  12015. render() {
  12016. this.container.className = "stampAnnotation";
  12017. if (!this.data.hasPopup) {
  12018. this._createPopup(null, this.data);
  12019. }
  12020. return this.container;
  12021. }
  12022. }
  12023. class FileAttachmentAnnotationElement extends AnnotationElement {
  12024. constructor(parameters) {
  12025. super(parameters, {
  12026. isRenderable: true
  12027. });
  12028. const {
  12029. filename,
  12030. content
  12031. } = this.data.file;
  12032. this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
  12033. this.content = content;
  12034. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  12035. source: this,
  12036. filename,
  12037. content
  12038. });
  12039. }
  12040. render() {
  12041. this.container.className = "fileAttachmentAnnotation";
  12042. const trigger = document.createElement("div");
  12043. trigger.className = "popupTriggerArea";
  12044. trigger.addEventListener("dblclick", this._download.bind(this));
  12045. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
  12046. this._createPopup(trigger, this.data);
  12047. }
  12048. this.container.append(trigger);
  12049. return this.container;
  12050. }
  12051. _download() {
  12052. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  12053. }
  12054. }
  12055. class AnnotationLayer {
  12056. static #appendElement(element, id, div, accessibilityManager) {
  12057. const contentElement = element.firstChild || element;
  12058. contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
  12059. div.append(element);
  12060. accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
  12061. }
  12062. static render(parameters) {
  12063. const {
  12064. annotations,
  12065. div,
  12066. viewport,
  12067. accessibilityManager
  12068. } = parameters;
  12069. this.#setDimensions(div, viewport);
  12070. let zIndex = 0;
  12071. for (const data of annotations) {
  12072. if (data.annotationType !== _util.AnnotationType.POPUP) {
  12073. const {
  12074. width,
  12075. height
  12076. } = getRectDims(data.rect);
  12077. if (width <= 0 || height <= 0) {
  12078. continue;
  12079. }
  12080. }
  12081. const element = AnnotationElementFactory.create({
  12082. data,
  12083. layer: div,
  12084. page: parameters.page,
  12085. viewport,
  12086. linkService: parameters.linkService,
  12087. downloadManager: parameters.downloadManager,
  12088. imageResourcesPath: parameters.imageResourcesPath || "",
  12089. renderForms: parameters.renderForms !== false,
  12090. svgFactory: new _display_utils.DOMSVGFactory(),
  12091. annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
  12092. enableScripting: parameters.enableScripting,
  12093. hasJSActions: parameters.hasJSActions,
  12094. fieldObjects: parameters.fieldObjects,
  12095. mouseState: parameters.mouseState || {
  12096. isDown: false
  12097. }
  12098. });
  12099. if (element.isRenderable) {
  12100. const rendered = element.render();
  12101. if (data.hidden) {
  12102. rendered.style.visibility = "hidden";
  12103. }
  12104. if (Array.isArray(rendered)) {
  12105. for (const renderedElement of rendered) {
  12106. renderedElement.style.zIndex = zIndex++;
  12107. AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
  12108. }
  12109. } else {
  12110. rendered.style.zIndex = zIndex++;
  12111. if (element instanceof PopupAnnotationElement) {
  12112. div.prepend(rendered);
  12113. } else {
  12114. AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
  12115. }
  12116. }
  12117. }
  12118. }
  12119. this.#setAnnotationCanvasMap(div, parameters.annotationCanvasMap);
  12120. }
  12121. static update(parameters) {
  12122. const {
  12123. annotationCanvasMap,
  12124. div,
  12125. viewport
  12126. } = parameters;
  12127. this.#setDimensions(div, viewport);
  12128. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  12129. div.hidden = false;
  12130. }
  12131. static #setDimensions(div, {
  12132. width,
  12133. height,
  12134. rotation
  12135. }) {
  12136. const {
  12137. style
  12138. } = div;
  12139. const flipOrientation = rotation % 180 !== 0,
  12140. widthStr = Math.floor(width) + "px",
  12141. heightStr = Math.floor(height) + "px";
  12142. style.width = flipOrientation ? heightStr : widthStr;
  12143. style.height = flipOrientation ? widthStr : heightStr;
  12144. div.setAttribute("data-main-rotation", rotation);
  12145. }
  12146. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  12147. if (!annotationCanvasMap) {
  12148. return;
  12149. }
  12150. for (const [id, canvas] of annotationCanvasMap) {
  12151. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  12152. if (!element) {
  12153. continue;
  12154. }
  12155. const {
  12156. firstChild
  12157. } = element;
  12158. if (!firstChild) {
  12159. element.append(canvas);
  12160. } else if (firstChild.nodeName === "CANVAS") {
  12161. firstChild.replaceWith(canvas);
  12162. } else {
  12163. firstChild.before(canvas);
  12164. }
  12165. }
  12166. annotationCanvasMap.clear();
  12167. }
  12168. }
  12169. exports.AnnotationLayer = AnnotationLayer;
  12170. /***/ }),
  12171. /* 27 */
  12172. /***/ ((__unused_webpack_module, exports) => {
  12173. Object.defineProperty(exports, "__esModule", ({
  12174. value: true
  12175. }));
  12176. exports.ColorConverters = void 0;
  12177. function makeColorComp(n) {
  12178. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  12179. }
  12180. class ColorConverters {
  12181. static CMYK_G([c, y, m, k]) {
  12182. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  12183. }
  12184. static G_CMYK([g]) {
  12185. return ["CMYK", 0, 0, 0, 1 - g];
  12186. }
  12187. static G_RGB([g]) {
  12188. return ["RGB", g, g, g];
  12189. }
  12190. static G_HTML([g]) {
  12191. const G = makeColorComp(g);
  12192. return `#${G}${G}${G}`;
  12193. }
  12194. static RGB_G([r, g, b]) {
  12195. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  12196. }
  12197. static RGB_HTML([r, g, b]) {
  12198. const R = makeColorComp(r);
  12199. const G = makeColorComp(g);
  12200. const B = makeColorComp(b);
  12201. return `#${R}${G}${B}`;
  12202. }
  12203. static T_HTML() {
  12204. return "#00000000";
  12205. }
  12206. static CMYK_RGB([c, y, m, k]) {
  12207. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  12208. }
  12209. static CMYK_HTML(components) {
  12210. const rgb = this.CMYK_RGB(components).slice(1);
  12211. return this.RGB_HTML(rgb);
  12212. }
  12213. static RGB_CMYK([r, g, b]) {
  12214. const c = 1 - r;
  12215. const m = 1 - g;
  12216. const y = 1 - b;
  12217. const k = Math.min(c, m, y);
  12218. return ["CMYK", c, m, y, k];
  12219. }
  12220. }
  12221. exports.ColorConverters = ColorConverters;
  12222. /***/ }),
  12223. /* 28 */
  12224. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12225. Object.defineProperty(exports, "__esModule", ({
  12226. value: true
  12227. }));
  12228. exports.XfaLayer = void 0;
  12229. var _xfa_text = __w_pdfjs_require__(19);
  12230. class XfaLayer {
  12231. static setupStorage(html, id, element, storage, intent) {
  12232. const storedData = storage.getValue(id, {
  12233. value: null
  12234. });
  12235. switch (element.name) {
  12236. case "textarea":
  12237. if (storedData.value !== null) {
  12238. html.textContent = storedData.value;
  12239. }
  12240. if (intent === "print") {
  12241. break;
  12242. }
  12243. html.addEventListener("input", event => {
  12244. storage.setValue(id, {
  12245. value: event.target.value
  12246. });
  12247. });
  12248. break;
  12249. case "input":
  12250. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  12251. if (storedData.value === element.attributes.xfaOn) {
  12252. html.setAttribute("checked", true);
  12253. } else if (storedData.value === element.attributes.xfaOff) {
  12254. html.removeAttribute("checked");
  12255. }
  12256. if (intent === "print") {
  12257. break;
  12258. }
  12259. html.addEventListener("change", event => {
  12260. storage.setValue(id, {
  12261. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  12262. });
  12263. });
  12264. } else {
  12265. if (storedData.value !== null) {
  12266. html.setAttribute("value", storedData.value);
  12267. }
  12268. if (intent === "print") {
  12269. break;
  12270. }
  12271. html.addEventListener("input", event => {
  12272. storage.setValue(id, {
  12273. value: event.target.value
  12274. });
  12275. });
  12276. }
  12277. break;
  12278. case "select":
  12279. if (storedData.value !== null) {
  12280. for (const option of element.children) {
  12281. if (option.attributes.value === storedData.value) {
  12282. option.attributes.selected = true;
  12283. }
  12284. }
  12285. }
  12286. html.addEventListener("input", event => {
  12287. const options = event.target.options;
  12288. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  12289. storage.setValue(id, {
  12290. value
  12291. });
  12292. });
  12293. break;
  12294. }
  12295. }
  12296. static setAttributes({
  12297. html,
  12298. element,
  12299. storage = null,
  12300. intent,
  12301. linkService
  12302. }) {
  12303. const {
  12304. attributes
  12305. } = element;
  12306. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  12307. if (attributes.type === "radio") {
  12308. attributes.name = `${attributes.name}-${intent}`;
  12309. }
  12310. for (const [key, value] of Object.entries(attributes)) {
  12311. if (value === null || value === undefined) {
  12312. continue;
  12313. }
  12314. switch (key) {
  12315. case "class":
  12316. if (value.length) {
  12317. html.setAttribute(key, value.join(" "));
  12318. }
  12319. break;
  12320. case "dataId":
  12321. break;
  12322. case "id":
  12323. html.setAttribute("data-element-id", value);
  12324. break;
  12325. case "style":
  12326. Object.assign(html.style, value);
  12327. break;
  12328. case "textContent":
  12329. html.textContent = value;
  12330. break;
  12331. default:
  12332. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  12333. html.setAttribute(key, value);
  12334. }
  12335. }
  12336. }
  12337. if (isHTMLAnchorElement) {
  12338. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  12339. }
  12340. if (storage && attributes.dataId) {
  12341. this.setupStorage(html, attributes.dataId, element, storage);
  12342. }
  12343. }
  12344. static render(parameters) {
  12345. const storage = parameters.annotationStorage;
  12346. const linkService = parameters.linkService;
  12347. const root = parameters.xfaHtml;
  12348. const intent = parameters.intent || "display";
  12349. const rootHtml = document.createElement(root.name);
  12350. if (root.attributes) {
  12351. this.setAttributes({
  12352. html: rootHtml,
  12353. element: root,
  12354. intent,
  12355. linkService
  12356. });
  12357. }
  12358. const stack = [[root, -1, rootHtml]];
  12359. const rootDiv = parameters.div;
  12360. rootDiv.append(rootHtml);
  12361. if (parameters.viewport) {
  12362. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12363. rootDiv.style.transform = transform;
  12364. }
  12365. if (intent !== "richText") {
  12366. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  12367. }
  12368. const textDivs = [];
  12369. while (stack.length > 0) {
  12370. const [parent, i, html] = stack.at(-1);
  12371. if (i + 1 === parent.children.length) {
  12372. stack.pop();
  12373. continue;
  12374. }
  12375. const child = parent.children[++stack.at(-1)[1]];
  12376. if (child === null) {
  12377. continue;
  12378. }
  12379. const {
  12380. name
  12381. } = child;
  12382. if (name === "#text") {
  12383. const node = document.createTextNode(child.value);
  12384. textDivs.push(node);
  12385. html.append(node);
  12386. continue;
  12387. }
  12388. let childHtml;
  12389. if (child?.attributes?.xmlns) {
  12390. childHtml = document.createElementNS(child.attributes.xmlns, name);
  12391. } else {
  12392. childHtml = document.createElement(name);
  12393. }
  12394. html.append(childHtml);
  12395. if (child.attributes) {
  12396. this.setAttributes({
  12397. html: childHtml,
  12398. element: child,
  12399. storage,
  12400. intent,
  12401. linkService
  12402. });
  12403. }
  12404. if (child.children && child.children.length > 0) {
  12405. stack.push([child, -1, childHtml]);
  12406. } else if (child.value) {
  12407. const node = document.createTextNode(child.value);
  12408. if (_xfa_text.XfaText.shouldBuildText(name)) {
  12409. textDivs.push(node);
  12410. }
  12411. childHtml.append(node);
  12412. }
  12413. }
  12414. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  12415. el.setAttribute("readOnly", true);
  12416. }
  12417. return {
  12418. textDivs
  12419. };
  12420. }
  12421. static update(parameters) {
  12422. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12423. parameters.div.style.transform = transform;
  12424. parameters.div.hidden = false;
  12425. }
  12426. }
  12427. exports.XfaLayer = XfaLayer;
  12428. /***/ }),
  12429. /* 29 */
  12430. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12431. Object.defineProperty(exports, "__esModule", ({
  12432. value: true
  12433. }));
  12434. exports.TextLayerRenderTask = void 0;
  12435. exports.renderTextLayer = renderTextLayer;
  12436. var _util = __w_pdfjs_require__(1);
  12437. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  12438. const DEFAULT_FONT_SIZE = 30;
  12439. const DEFAULT_FONT_ASCENT = 0.8;
  12440. const ascentCache = new Map();
  12441. function getAscent(fontFamily, ctx) {
  12442. const cachedAscent = ascentCache.get(fontFamily);
  12443. if (cachedAscent) {
  12444. return cachedAscent;
  12445. }
  12446. ctx.save();
  12447. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  12448. const metrics = ctx.measureText("");
  12449. let ascent = metrics.fontBoundingBoxAscent;
  12450. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  12451. if (ascent) {
  12452. ctx.restore();
  12453. const ratio = ascent / (ascent + descent);
  12454. ascentCache.set(fontFamily, ratio);
  12455. return ratio;
  12456. }
  12457. ctx.strokeStyle = "red";
  12458. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12459. ctx.strokeText("g", 0, 0);
  12460. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12461. descent = 0;
  12462. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  12463. if (pixels[i] > 0) {
  12464. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  12465. break;
  12466. }
  12467. }
  12468. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  12469. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  12470. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  12471. ascent = 0;
  12472. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  12473. if (pixels[i] > 0) {
  12474. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  12475. break;
  12476. }
  12477. }
  12478. ctx.restore();
  12479. if (ascent) {
  12480. const ratio = ascent / (ascent + descent);
  12481. ascentCache.set(fontFamily, ratio);
  12482. return ratio;
  12483. }
  12484. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  12485. return DEFAULT_FONT_ASCENT;
  12486. }
  12487. function appendText(task, geom, styles, ctx) {
  12488. const textDiv = document.createElement("span");
  12489. const textDivProperties = {
  12490. angle: 0,
  12491. canvasWidth: 0,
  12492. hasText: geom.str !== "",
  12493. hasEOL: geom.hasEOL,
  12494. fontSize: 0
  12495. };
  12496. task._textDivs.push(textDiv);
  12497. const tx = _util.Util.transform(task._viewport.transform, geom.transform);
  12498. let angle = Math.atan2(tx[1], tx[0]);
  12499. const style = styles[geom.fontName];
  12500. if (style.vertical) {
  12501. angle += Math.PI / 2;
  12502. }
  12503. const fontHeight = Math.hypot(tx[2], tx[3]);
  12504. const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
  12505. let left, top;
  12506. if (angle === 0) {
  12507. left = tx[4];
  12508. top = tx[5] - fontAscent;
  12509. } else {
  12510. left = tx[4] + fontAscent * Math.sin(angle);
  12511. top = tx[5] - fontAscent * Math.cos(angle);
  12512. }
  12513. textDiv.style.left = `${left}px`;
  12514. textDiv.style.top = `${top}px`;
  12515. textDiv.style.fontSize = `${fontHeight}px`;
  12516. textDiv.style.fontFamily = style.fontFamily;
  12517. textDivProperties.fontSize = fontHeight;
  12518. textDiv.setAttribute("role", "presentation");
  12519. textDiv.textContent = geom.str;
  12520. textDiv.dir = geom.dir;
  12521. if (task._fontInspectorEnabled) {
  12522. textDiv.dataset.fontName = geom.fontName;
  12523. }
  12524. if (angle !== 0) {
  12525. textDivProperties.angle = angle * (180 / Math.PI);
  12526. }
  12527. let shouldScaleText = false;
  12528. if (geom.str.length > 1) {
  12529. shouldScaleText = true;
  12530. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  12531. const absScaleX = Math.abs(geom.transform[0]),
  12532. absScaleY = Math.abs(geom.transform[3]);
  12533. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  12534. shouldScaleText = true;
  12535. }
  12536. }
  12537. if (shouldScaleText) {
  12538. if (style.vertical) {
  12539. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  12540. } else {
  12541. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  12542. }
  12543. }
  12544. task._textDivProperties.set(textDiv, textDivProperties);
  12545. if (task._textContentStream) {
  12546. task._layoutText(textDiv);
  12547. }
  12548. }
  12549. function render(task) {
  12550. if (task._canceled) {
  12551. return;
  12552. }
  12553. const textDivs = task._textDivs;
  12554. const capability = task._capability;
  12555. const textDivsLength = textDivs.length;
  12556. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  12557. task._renderingDone = true;
  12558. capability.resolve();
  12559. return;
  12560. }
  12561. if (!task._textContentStream) {
  12562. for (const textDiv of textDivs) {
  12563. task._layoutText(textDiv);
  12564. }
  12565. }
  12566. task._renderingDone = true;
  12567. capability.resolve();
  12568. }
  12569. class TextLayerRenderTask {
  12570. constructor({
  12571. textContent,
  12572. textContentStream,
  12573. container,
  12574. viewport,
  12575. textDivs,
  12576. textContentItemsStr
  12577. }) {
  12578. this._textContent = textContent;
  12579. this._textContentStream = textContentStream;
  12580. this._container = container;
  12581. this._document = container.ownerDocument;
  12582. this._viewport = viewport;
  12583. this._textDivs = textDivs || [];
  12584. this._textContentItemsStr = textContentItemsStr || [];
  12585. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  12586. this._reader = null;
  12587. this._layoutTextLastFontSize = null;
  12588. this._layoutTextLastFontFamily = null;
  12589. this._layoutTextCtx = null;
  12590. this._textDivProperties = new WeakMap();
  12591. this._renderingDone = false;
  12592. this._canceled = false;
  12593. this._capability = (0, _util.createPromiseCapability)();
  12594. this._renderTimer = null;
  12595. this._bounds = [];
  12596. this._devicePixelRatio = globalThis.devicePixelRatio || 1;
  12597. this._capability.promise.finally(() => {
  12598. this._textDivProperties = null;
  12599. if (this._layoutTextCtx) {
  12600. this._layoutTextCtx.canvas.width = 0;
  12601. this._layoutTextCtx.canvas.height = 0;
  12602. this._layoutTextCtx = null;
  12603. }
  12604. }).catch(() => {});
  12605. }
  12606. get promise() {
  12607. return this._capability.promise;
  12608. }
  12609. cancel() {
  12610. this._canceled = true;
  12611. if (this._reader) {
  12612. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  12613. this._reader = null;
  12614. }
  12615. if (this._renderTimer !== null) {
  12616. clearTimeout(this._renderTimer);
  12617. this._renderTimer = null;
  12618. }
  12619. this._capability.reject(new Error("TextLayer task cancelled."));
  12620. }
  12621. _processItems(items, styleCache) {
  12622. for (const item of items) {
  12623. if (item.str === undefined) {
  12624. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  12625. const parent = this._container;
  12626. this._container = document.createElement("span");
  12627. this._container.classList.add("markedContent");
  12628. if (item.id !== null) {
  12629. this._container.setAttribute("id", `${item.id}`);
  12630. }
  12631. parent.append(this._container);
  12632. } else if (item.type === "endMarkedContent") {
  12633. this._container = this._container.parentNode;
  12634. }
  12635. continue;
  12636. }
  12637. this._textContentItemsStr.push(item.str);
  12638. appendText(this, item, styleCache, this._layoutTextCtx);
  12639. }
  12640. }
  12641. _layoutText(textDiv) {
  12642. const textDivProperties = this._textDivProperties.get(textDiv);
  12643. let transform = "";
  12644. if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
  12645. const {
  12646. fontFamily
  12647. } = textDiv.style;
  12648. const {
  12649. fontSize
  12650. } = textDivProperties;
  12651. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  12652. this._layoutTextCtx.font = `${fontSize * this._devicePixelRatio}px ${fontFamily}`;
  12653. this._layoutTextLastFontSize = fontSize;
  12654. this._layoutTextLastFontFamily = fontFamily;
  12655. }
  12656. const {
  12657. width
  12658. } = this._layoutTextCtx.measureText(textDiv.textContent);
  12659. if (width > 0) {
  12660. transform = `scaleX(${this._devicePixelRatio * textDivProperties.canvasWidth / width})`;
  12661. }
  12662. }
  12663. if (textDivProperties.angle !== 0) {
  12664. transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
  12665. }
  12666. if (transform.length > 0) {
  12667. textDiv.style.transform = transform;
  12668. }
  12669. if (textDivProperties.hasText) {
  12670. this._container.append(textDiv);
  12671. }
  12672. if (textDivProperties.hasEOL) {
  12673. const br = document.createElement("br");
  12674. br.setAttribute("role", "presentation");
  12675. this._container.append(br);
  12676. }
  12677. }
  12678. _render(timeout = 0) {
  12679. const capability = (0, _util.createPromiseCapability)();
  12680. let styleCache = Object.create(null);
  12681. const canvas = this._document.createElement("canvas");
  12682. canvas.height = canvas.width = DEFAULT_FONT_SIZE;
  12683. this._layoutTextCtx = canvas.getContext("2d", {
  12684. alpha: false
  12685. });
  12686. if (this._textContent) {
  12687. const textItems = this._textContent.items;
  12688. const textStyles = this._textContent.styles;
  12689. this._processItems(textItems, textStyles);
  12690. capability.resolve();
  12691. } else if (this._textContentStream) {
  12692. const pump = () => {
  12693. this._reader.read().then(({
  12694. value,
  12695. done
  12696. }) => {
  12697. if (done) {
  12698. capability.resolve();
  12699. return;
  12700. }
  12701. Object.assign(styleCache, value.styles);
  12702. this._processItems(value.items, styleCache);
  12703. pump();
  12704. }, capability.reject);
  12705. };
  12706. this._reader = this._textContentStream.getReader();
  12707. pump();
  12708. } else {
  12709. throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
  12710. }
  12711. capability.promise.then(() => {
  12712. styleCache = null;
  12713. if (!timeout) {
  12714. render(this);
  12715. } else {
  12716. this._renderTimer = setTimeout(() => {
  12717. render(this);
  12718. this._renderTimer = null;
  12719. }, timeout);
  12720. }
  12721. }, this._capability.reject);
  12722. }
  12723. }
  12724. exports.TextLayerRenderTask = TextLayerRenderTask;
  12725. function renderTextLayer(renderParameters) {
  12726. const task = new TextLayerRenderTask({
  12727. textContent: renderParameters.textContent,
  12728. textContentStream: renderParameters.textContentStream,
  12729. container: renderParameters.container,
  12730. viewport: renderParameters.viewport,
  12731. textDivs: renderParameters.textDivs,
  12732. textContentItemsStr: renderParameters.textContentItemsStr
  12733. });
  12734. task._render(renderParameters.timeout);
  12735. return task;
  12736. }
  12737. /***/ }),
  12738. /* 30 */
  12739. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12740. Object.defineProperty(exports, "__esModule", ({
  12741. value: true
  12742. }));
  12743. exports.SVGGraphics = void 0;
  12744. var _display_utils = __w_pdfjs_require__(6);
  12745. var _util = __w_pdfjs_require__(1);
  12746. var _is_node = __w_pdfjs_require__(12);
  12747. let SVGGraphics = class {
  12748. constructor() {
  12749. (0, _util.unreachable)("Not implemented: SVGGraphics");
  12750. }
  12751. };
  12752. exports.SVGGraphics = SVGGraphics;
  12753. {
  12754. const SVG_DEFAULTS = {
  12755. fontStyle: "normal",
  12756. fontWeight: "normal",
  12757. fillColor: "#000000"
  12758. };
  12759. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  12760. const XLINK_NS = "http://www.w3.org/1999/xlink";
  12761. const LINE_CAP_STYLES = ["butt", "round", "square"];
  12762. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  12763. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  12764. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  12765. return URL.createObjectURL(new Blob([data], {
  12766. type: contentType
  12767. }));
  12768. }
  12769. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  12770. let buffer = `data:${contentType};base64,`;
  12771. for (let i = 0, ii = data.length; i < ii; i += 3) {
  12772. const b1 = data[i] & 0xff;
  12773. const b2 = data[i + 1] & 0xff;
  12774. const b3 = data[i + 2] & 0xff;
  12775. const d1 = b1 >> 2,
  12776. d2 = (b1 & 3) << 4 | b2 >> 4;
  12777. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  12778. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  12779. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  12780. }
  12781. return buffer;
  12782. };
  12783. const convertImgDataToPng = function () {
  12784. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  12785. const CHUNK_WRAPPER_SIZE = 12;
  12786. const crcTable = new Int32Array(256);
  12787. for (let i = 0; i < 256; i++) {
  12788. let c = i;
  12789. for (let h = 0; h < 8; h++) {
  12790. if (c & 1) {
  12791. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  12792. } else {
  12793. c = c >> 1 & 0x7fffffff;
  12794. }
  12795. }
  12796. crcTable[i] = c;
  12797. }
  12798. function crc32(data, start, end) {
  12799. let crc = -1;
  12800. for (let i = start; i < end; i++) {
  12801. const a = (crc ^ data[i]) & 0xff;
  12802. const b = crcTable[a];
  12803. crc = crc >>> 8 ^ b;
  12804. }
  12805. return crc ^ -1;
  12806. }
  12807. function writePngChunk(type, body, data, offset) {
  12808. let p = offset;
  12809. const len = body.length;
  12810. data[p] = len >> 24 & 0xff;
  12811. data[p + 1] = len >> 16 & 0xff;
  12812. data[p + 2] = len >> 8 & 0xff;
  12813. data[p + 3] = len & 0xff;
  12814. p += 4;
  12815. data[p] = type.charCodeAt(0) & 0xff;
  12816. data[p + 1] = type.charCodeAt(1) & 0xff;
  12817. data[p + 2] = type.charCodeAt(2) & 0xff;
  12818. data[p + 3] = type.charCodeAt(3) & 0xff;
  12819. p += 4;
  12820. data.set(body, p);
  12821. p += body.length;
  12822. const crc = crc32(data, offset + 4, p);
  12823. data[p] = crc >> 24 & 0xff;
  12824. data[p + 1] = crc >> 16 & 0xff;
  12825. data[p + 2] = crc >> 8 & 0xff;
  12826. data[p + 3] = crc & 0xff;
  12827. }
  12828. function adler32(data, start, end) {
  12829. let a = 1;
  12830. let b = 0;
  12831. for (let i = start; i < end; ++i) {
  12832. a = (a + (data[i] & 0xff)) % 65521;
  12833. b = (b + a) % 65521;
  12834. }
  12835. return b << 16 | a;
  12836. }
  12837. function deflateSync(literals) {
  12838. if (!_is_node.isNodeJS) {
  12839. return deflateSyncUncompressed(literals);
  12840. }
  12841. try {
  12842. let input;
  12843. if (parseInt(process.versions.node) >= 8) {
  12844. input = literals;
  12845. } else {
  12846. input = Buffer.from(literals);
  12847. }
  12848. const output = require("zlib").deflateSync(input, {
  12849. level: 9
  12850. });
  12851. return output instanceof Uint8Array ? output : new Uint8Array(output);
  12852. } catch (e) {
  12853. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  12854. }
  12855. return deflateSyncUncompressed(literals);
  12856. }
  12857. function deflateSyncUncompressed(literals) {
  12858. let len = literals.length;
  12859. const maxBlockLength = 0xffff;
  12860. const deflateBlocks = Math.ceil(len / maxBlockLength);
  12861. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  12862. let pi = 0;
  12863. idat[pi++] = 0x78;
  12864. idat[pi++] = 0x9c;
  12865. let pos = 0;
  12866. while (len > maxBlockLength) {
  12867. idat[pi++] = 0x00;
  12868. idat[pi++] = 0xff;
  12869. idat[pi++] = 0xff;
  12870. idat[pi++] = 0x00;
  12871. idat[pi++] = 0x00;
  12872. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  12873. pi += maxBlockLength;
  12874. pos += maxBlockLength;
  12875. len -= maxBlockLength;
  12876. }
  12877. idat[pi++] = 0x01;
  12878. idat[pi++] = len & 0xff;
  12879. idat[pi++] = len >> 8 & 0xff;
  12880. idat[pi++] = ~len & 0xffff & 0xff;
  12881. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  12882. idat.set(literals.subarray(pos), pi);
  12883. pi += literals.length - pos;
  12884. const adler = adler32(literals, 0, literals.length);
  12885. idat[pi++] = adler >> 24 & 0xff;
  12886. idat[pi++] = adler >> 16 & 0xff;
  12887. idat[pi++] = adler >> 8 & 0xff;
  12888. idat[pi++] = adler & 0xff;
  12889. return idat;
  12890. }
  12891. function encode(imgData, kind, forceDataSchema, isMask) {
  12892. const width = imgData.width;
  12893. const height = imgData.height;
  12894. let bitDepth, colorType, lineSize;
  12895. const bytes = imgData.data;
  12896. switch (kind) {
  12897. case _util.ImageKind.GRAYSCALE_1BPP:
  12898. colorType = 0;
  12899. bitDepth = 1;
  12900. lineSize = width + 7 >> 3;
  12901. break;
  12902. case _util.ImageKind.RGB_24BPP:
  12903. colorType = 2;
  12904. bitDepth = 8;
  12905. lineSize = width * 3;
  12906. break;
  12907. case _util.ImageKind.RGBA_32BPP:
  12908. colorType = 6;
  12909. bitDepth = 8;
  12910. lineSize = width * 4;
  12911. break;
  12912. default:
  12913. throw new Error("invalid format");
  12914. }
  12915. const literals = new Uint8Array((1 + lineSize) * height);
  12916. let offsetLiterals = 0,
  12917. offsetBytes = 0;
  12918. for (let y = 0; y < height; ++y) {
  12919. literals[offsetLiterals++] = 0;
  12920. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  12921. offsetBytes += lineSize;
  12922. offsetLiterals += lineSize;
  12923. }
  12924. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  12925. offsetLiterals = 0;
  12926. for (let y = 0; y < height; y++) {
  12927. offsetLiterals++;
  12928. for (let i = 0; i < lineSize; i++) {
  12929. literals[offsetLiterals++] ^= 0xff;
  12930. }
  12931. }
  12932. }
  12933. 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]);
  12934. const idat = deflateSync(literals);
  12935. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  12936. const data = new Uint8Array(pngLength);
  12937. let offset = 0;
  12938. data.set(PNG_HEADER, offset);
  12939. offset += PNG_HEADER.length;
  12940. writePngChunk("IHDR", ihdr, data, offset);
  12941. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  12942. writePngChunk("IDATA", idat, data, offset);
  12943. offset += CHUNK_WRAPPER_SIZE + idat.length;
  12944. writePngChunk("IEND", new Uint8Array(0), data, offset);
  12945. return createObjectURL(data, "image/png", forceDataSchema);
  12946. }
  12947. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  12948. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  12949. return encode(imgData, kind, forceDataSchema, isMask);
  12950. };
  12951. }();
  12952. class SVGExtraState {
  12953. constructor() {
  12954. this.fontSizeScale = 1;
  12955. this.fontWeight = SVG_DEFAULTS.fontWeight;
  12956. this.fontSize = 0;
  12957. this.textMatrix = _util.IDENTITY_MATRIX;
  12958. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  12959. this.leading = 0;
  12960. this.textRenderingMode = _util.TextRenderingMode.FILL;
  12961. this.textMatrixScale = 1;
  12962. this.x = 0;
  12963. this.y = 0;
  12964. this.lineX = 0;
  12965. this.lineY = 0;
  12966. this.charSpacing = 0;
  12967. this.wordSpacing = 0;
  12968. this.textHScale = 1;
  12969. this.textRise = 0;
  12970. this.fillColor = SVG_DEFAULTS.fillColor;
  12971. this.strokeColor = "#000000";
  12972. this.fillAlpha = 1;
  12973. this.strokeAlpha = 1;
  12974. this.lineWidth = 1;
  12975. this.lineJoin = "";
  12976. this.lineCap = "";
  12977. this.miterLimit = 0;
  12978. this.dashArray = [];
  12979. this.dashPhase = 0;
  12980. this.dependencies = [];
  12981. this.activeClipUrl = null;
  12982. this.clipGroup = null;
  12983. this.maskId = "";
  12984. }
  12985. clone() {
  12986. return Object.create(this);
  12987. }
  12988. setCurrentPoint(x, y) {
  12989. this.x = x;
  12990. this.y = y;
  12991. }
  12992. }
  12993. function opListToTree(opList) {
  12994. let opTree = [];
  12995. const tmp = [];
  12996. for (const opListElement of opList) {
  12997. if (opListElement.fn === "save") {
  12998. opTree.push({
  12999. fnId: 92,
  13000. fn: "group",
  13001. items: []
  13002. });
  13003. tmp.push(opTree);
  13004. opTree = opTree.at(-1).items;
  13005. continue;
  13006. }
  13007. if (opListElement.fn === "restore") {
  13008. opTree = tmp.pop();
  13009. } else {
  13010. opTree.push(opListElement);
  13011. }
  13012. }
  13013. return opTree;
  13014. }
  13015. function pf(value) {
  13016. if (Number.isInteger(value)) {
  13017. return value.toString();
  13018. }
  13019. const s = value.toFixed(10);
  13020. let i = s.length - 1;
  13021. if (s[i] !== "0") {
  13022. return s;
  13023. }
  13024. do {
  13025. i--;
  13026. } while (s[i] === "0");
  13027. return s.substring(0, s[i] === "." ? i : i + 1);
  13028. }
  13029. function pm(m) {
  13030. if (m[4] === 0 && m[5] === 0) {
  13031. if (m[1] === 0 && m[2] === 0) {
  13032. if (m[0] === 1 && m[3] === 1) {
  13033. return "";
  13034. }
  13035. return `scale(${pf(m[0])} ${pf(m[3])})`;
  13036. }
  13037. if (m[0] === m[3] && m[1] === -m[2]) {
  13038. const a = Math.acos(m[0]) * 180 / Math.PI;
  13039. return `rotate(${pf(a)})`;
  13040. }
  13041. } else {
  13042. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  13043. return `translate(${pf(m[4])} ${pf(m[5])})`;
  13044. }
  13045. }
  13046. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  13047. }
  13048. let clipCount = 0;
  13049. let maskCount = 0;
  13050. let shadingCount = 0;
  13051. exports.SVGGraphics = SVGGraphics = class {
  13052. constructor(commonObjs, objs, forceDataSchema = false) {
  13053. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  13054. this.svgFactory = new _display_utils.DOMSVGFactory();
  13055. this.current = new SVGExtraState();
  13056. this.transformMatrix = _util.IDENTITY_MATRIX;
  13057. this.transformStack = [];
  13058. this.extraStack = [];
  13059. this.commonObjs = commonObjs;
  13060. this.objs = objs;
  13061. this.pendingClip = null;
  13062. this.pendingEOFill = false;
  13063. this.embedFonts = false;
  13064. this.embeddedFonts = Object.create(null);
  13065. this.cssStyle = null;
  13066. this.forceDataSchema = !!forceDataSchema;
  13067. this._operatorIdMapping = [];
  13068. for (const op in _util.OPS) {
  13069. this._operatorIdMapping[_util.OPS[op]] = op;
  13070. }
  13071. }
  13072. getObject(data, fallback = null) {
  13073. if (typeof data === "string") {
  13074. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  13075. }
  13076. return fallback;
  13077. }
  13078. save() {
  13079. this.transformStack.push(this.transformMatrix);
  13080. const old = this.current;
  13081. this.extraStack.push(old);
  13082. this.current = old.clone();
  13083. }
  13084. restore() {
  13085. this.transformMatrix = this.transformStack.pop();
  13086. this.current = this.extraStack.pop();
  13087. this.pendingClip = null;
  13088. this.tgrp = null;
  13089. }
  13090. group(items) {
  13091. this.save();
  13092. this.executeOpTree(items);
  13093. this.restore();
  13094. }
  13095. loadDependencies(operatorList) {
  13096. const fnArray = operatorList.fnArray;
  13097. const argsArray = operatorList.argsArray;
  13098. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13099. if (fnArray[i] !== _util.OPS.dependency) {
  13100. continue;
  13101. }
  13102. for (const obj of argsArray[i]) {
  13103. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  13104. const promise = new Promise(resolve => {
  13105. objsPool.get(obj, resolve);
  13106. });
  13107. this.current.dependencies.push(promise);
  13108. }
  13109. }
  13110. return Promise.all(this.current.dependencies);
  13111. }
  13112. transform(a, b, c, d, e, f) {
  13113. const transformMatrix = [a, b, c, d, e, f];
  13114. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  13115. this.tgrp = null;
  13116. }
  13117. getSVG(operatorList, viewport) {
  13118. this.viewport = viewport;
  13119. const svgElement = this._initialize(viewport);
  13120. return this.loadDependencies(operatorList).then(() => {
  13121. this.transformMatrix = _util.IDENTITY_MATRIX;
  13122. this.executeOpTree(this.convertOpList(operatorList));
  13123. return svgElement;
  13124. });
  13125. }
  13126. convertOpList(operatorList) {
  13127. const operatorIdMapping = this._operatorIdMapping;
  13128. const argsArray = operatorList.argsArray;
  13129. const fnArray = operatorList.fnArray;
  13130. const opList = [];
  13131. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13132. const fnId = fnArray[i];
  13133. opList.push({
  13134. fnId,
  13135. fn: operatorIdMapping[fnId],
  13136. args: argsArray[i]
  13137. });
  13138. }
  13139. return opListToTree(opList);
  13140. }
  13141. executeOpTree(opTree) {
  13142. for (const opTreeElement of opTree) {
  13143. const fn = opTreeElement.fn;
  13144. const fnId = opTreeElement.fnId;
  13145. const args = opTreeElement.args;
  13146. switch (fnId | 0) {
  13147. case _util.OPS.beginText:
  13148. this.beginText();
  13149. break;
  13150. case _util.OPS.dependency:
  13151. break;
  13152. case _util.OPS.setLeading:
  13153. this.setLeading(args);
  13154. break;
  13155. case _util.OPS.setLeadingMoveText:
  13156. this.setLeadingMoveText(args[0], args[1]);
  13157. break;
  13158. case _util.OPS.setFont:
  13159. this.setFont(args);
  13160. break;
  13161. case _util.OPS.showText:
  13162. this.showText(args[0]);
  13163. break;
  13164. case _util.OPS.showSpacedText:
  13165. this.showText(args[0]);
  13166. break;
  13167. case _util.OPS.endText:
  13168. this.endText();
  13169. break;
  13170. case _util.OPS.moveText:
  13171. this.moveText(args[0], args[1]);
  13172. break;
  13173. case _util.OPS.setCharSpacing:
  13174. this.setCharSpacing(args[0]);
  13175. break;
  13176. case _util.OPS.setWordSpacing:
  13177. this.setWordSpacing(args[0]);
  13178. break;
  13179. case _util.OPS.setHScale:
  13180. this.setHScale(args[0]);
  13181. break;
  13182. case _util.OPS.setTextMatrix:
  13183. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  13184. break;
  13185. case _util.OPS.setTextRise:
  13186. this.setTextRise(args[0]);
  13187. break;
  13188. case _util.OPS.setTextRenderingMode:
  13189. this.setTextRenderingMode(args[0]);
  13190. break;
  13191. case _util.OPS.setLineWidth:
  13192. this.setLineWidth(args[0]);
  13193. break;
  13194. case _util.OPS.setLineJoin:
  13195. this.setLineJoin(args[0]);
  13196. break;
  13197. case _util.OPS.setLineCap:
  13198. this.setLineCap(args[0]);
  13199. break;
  13200. case _util.OPS.setMiterLimit:
  13201. this.setMiterLimit(args[0]);
  13202. break;
  13203. case _util.OPS.setFillRGBColor:
  13204. this.setFillRGBColor(args[0], args[1], args[2]);
  13205. break;
  13206. case _util.OPS.setStrokeRGBColor:
  13207. this.setStrokeRGBColor(args[0], args[1], args[2]);
  13208. break;
  13209. case _util.OPS.setStrokeColorN:
  13210. this.setStrokeColorN(args);
  13211. break;
  13212. case _util.OPS.setFillColorN:
  13213. this.setFillColorN(args);
  13214. break;
  13215. case _util.OPS.shadingFill:
  13216. this.shadingFill(args[0]);
  13217. break;
  13218. case _util.OPS.setDash:
  13219. this.setDash(args[0], args[1]);
  13220. break;
  13221. case _util.OPS.setRenderingIntent:
  13222. this.setRenderingIntent(args[0]);
  13223. break;
  13224. case _util.OPS.setFlatness:
  13225. this.setFlatness(args[0]);
  13226. break;
  13227. case _util.OPS.setGState:
  13228. this.setGState(args[0]);
  13229. break;
  13230. case _util.OPS.fill:
  13231. this.fill();
  13232. break;
  13233. case _util.OPS.eoFill:
  13234. this.eoFill();
  13235. break;
  13236. case _util.OPS.stroke:
  13237. this.stroke();
  13238. break;
  13239. case _util.OPS.fillStroke:
  13240. this.fillStroke();
  13241. break;
  13242. case _util.OPS.eoFillStroke:
  13243. this.eoFillStroke();
  13244. break;
  13245. case _util.OPS.clip:
  13246. this.clip("nonzero");
  13247. break;
  13248. case _util.OPS.eoClip:
  13249. this.clip("evenodd");
  13250. break;
  13251. case _util.OPS.paintSolidColorImageMask:
  13252. this.paintSolidColorImageMask();
  13253. break;
  13254. case _util.OPS.paintImageXObject:
  13255. this.paintImageXObject(args[0]);
  13256. break;
  13257. case _util.OPS.paintInlineImageXObject:
  13258. this.paintInlineImageXObject(args[0]);
  13259. break;
  13260. case _util.OPS.paintImageMaskXObject:
  13261. this.paintImageMaskXObject(args[0]);
  13262. break;
  13263. case _util.OPS.paintFormXObjectBegin:
  13264. this.paintFormXObjectBegin(args[0], args[1]);
  13265. break;
  13266. case _util.OPS.paintFormXObjectEnd:
  13267. this.paintFormXObjectEnd();
  13268. break;
  13269. case _util.OPS.closePath:
  13270. this.closePath();
  13271. break;
  13272. case _util.OPS.closeStroke:
  13273. this.closeStroke();
  13274. break;
  13275. case _util.OPS.closeFillStroke:
  13276. this.closeFillStroke();
  13277. break;
  13278. case _util.OPS.closeEOFillStroke:
  13279. this.closeEOFillStroke();
  13280. break;
  13281. case _util.OPS.nextLine:
  13282. this.nextLine();
  13283. break;
  13284. case _util.OPS.transform:
  13285. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  13286. break;
  13287. case _util.OPS.constructPath:
  13288. this.constructPath(args[0], args[1]);
  13289. break;
  13290. case _util.OPS.endPath:
  13291. this.endPath();
  13292. break;
  13293. case 92:
  13294. this.group(opTreeElement.items);
  13295. break;
  13296. default:
  13297. (0, _util.warn)(`Unimplemented operator ${fn}`);
  13298. break;
  13299. }
  13300. }
  13301. }
  13302. setWordSpacing(wordSpacing) {
  13303. this.current.wordSpacing = wordSpacing;
  13304. }
  13305. setCharSpacing(charSpacing) {
  13306. this.current.charSpacing = charSpacing;
  13307. }
  13308. nextLine() {
  13309. this.moveText(0, this.current.leading);
  13310. }
  13311. setTextMatrix(a, b, c, d, e, f) {
  13312. const current = this.current;
  13313. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  13314. current.textMatrixScale = Math.hypot(a, b);
  13315. current.x = current.lineX = 0;
  13316. current.y = current.lineY = 0;
  13317. current.xcoords = [];
  13318. current.ycoords = [];
  13319. current.tspan = this.svgFactory.createElement("svg:tspan");
  13320. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13321. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13322. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13323. current.txtElement = this.svgFactory.createElement("svg:text");
  13324. current.txtElement.append(current.tspan);
  13325. }
  13326. beginText() {
  13327. const current = this.current;
  13328. current.x = current.lineX = 0;
  13329. current.y = current.lineY = 0;
  13330. current.textMatrix = _util.IDENTITY_MATRIX;
  13331. current.lineMatrix = _util.IDENTITY_MATRIX;
  13332. current.textMatrixScale = 1;
  13333. current.tspan = this.svgFactory.createElement("svg:tspan");
  13334. current.txtElement = this.svgFactory.createElement("svg:text");
  13335. current.txtgrp = this.svgFactory.createElement("svg:g");
  13336. current.xcoords = [];
  13337. current.ycoords = [];
  13338. }
  13339. moveText(x, y) {
  13340. const current = this.current;
  13341. current.x = current.lineX += x;
  13342. current.y = current.lineY += y;
  13343. current.xcoords = [];
  13344. current.ycoords = [];
  13345. current.tspan = this.svgFactory.createElement("svg:tspan");
  13346. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13347. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13348. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13349. }
  13350. showText(glyphs) {
  13351. const current = this.current;
  13352. const font = current.font;
  13353. const fontSize = current.fontSize;
  13354. if (fontSize === 0) {
  13355. return;
  13356. }
  13357. const fontSizeScale = current.fontSizeScale;
  13358. const charSpacing = current.charSpacing;
  13359. const wordSpacing = current.wordSpacing;
  13360. const fontDirection = current.fontDirection;
  13361. const textHScale = current.textHScale * fontDirection;
  13362. const vertical = font.vertical;
  13363. const spacingDir = vertical ? 1 : -1;
  13364. const defaultVMetrics = font.defaultVMetrics;
  13365. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  13366. let x = 0;
  13367. for (const glyph of glyphs) {
  13368. if (glyph === null) {
  13369. x += fontDirection * wordSpacing;
  13370. continue;
  13371. } else if (typeof glyph === "number") {
  13372. x += spacingDir * glyph * fontSize / 1000;
  13373. continue;
  13374. }
  13375. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  13376. const character = glyph.fontChar;
  13377. let scaledX, scaledY;
  13378. let width = glyph.width;
  13379. if (vertical) {
  13380. let vx;
  13381. const vmetric = glyph.vmetric || defaultVMetrics;
  13382. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  13383. vx = -vx * widthAdvanceScale;
  13384. const vy = vmetric[2] * widthAdvanceScale;
  13385. width = vmetric ? -vmetric[0] : width;
  13386. scaledX = vx / fontSizeScale;
  13387. scaledY = (x + vy) / fontSizeScale;
  13388. } else {
  13389. scaledX = x / fontSizeScale;
  13390. scaledY = 0;
  13391. }
  13392. if (glyph.isInFont || font.missingFile) {
  13393. current.xcoords.push(current.x + scaledX);
  13394. if (vertical) {
  13395. current.ycoords.push(-current.y + scaledY);
  13396. }
  13397. current.tspan.textContent += character;
  13398. } else {}
  13399. let charWidth;
  13400. if (vertical) {
  13401. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  13402. } else {
  13403. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  13404. }
  13405. x += charWidth;
  13406. }
  13407. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  13408. if (vertical) {
  13409. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  13410. } else {
  13411. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13412. }
  13413. if (vertical) {
  13414. current.y -= x;
  13415. } else {
  13416. current.x += x * textHScale;
  13417. }
  13418. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13419. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13420. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  13421. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  13422. }
  13423. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  13424. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  13425. }
  13426. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  13427. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13428. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  13429. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  13430. }
  13431. if (current.fillAlpha < 1) {
  13432. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  13433. }
  13434. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  13435. current.tspan.setAttributeNS(null, "fill", "transparent");
  13436. } else {
  13437. current.tspan.setAttributeNS(null, "fill", "none");
  13438. }
  13439. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13440. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  13441. this._setStrokeAttributes(current.tspan, lineWidthScale);
  13442. }
  13443. let textMatrix = current.textMatrix;
  13444. if (current.textRise !== 0) {
  13445. textMatrix = textMatrix.slice();
  13446. textMatrix[5] += current.textRise;
  13447. }
  13448. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  13449. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  13450. current.txtElement.append(current.tspan);
  13451. current.txtgrp.append(current.txtElement);
  13452. this._ensureTransformGroup().append(current.txtElement);
  13453. }
  13454. setLeadingMoveText(x, y) {
  13455. this.setLeading(-y);
  13456. this.moveText(x, y);
  13457. }
  13458. addFontStyle(fontObj) {
  13459. if (!fontObj.data) {
  13460. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  13461. }
  13462. if (!this.cssStyle) {
  13463. this.cssStyle = this.svgFactory.createElement("svg:style");
  13464. this.cssStyle.setAttributeNS(null, "type", "text/css");
  13465. this.defs.append(this.cssStyle);
  13466. }
  13467. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  13468. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  13469. }
  13470. setFont(details) {
  13471. const current = this.current;
  13472. const fontObj = this.commonObjs.get(details[0]);
  13473. let size = details[1];
  13474. current.font = fontObj;
  13475. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  13476. this.addFontStyle(fontObj);
  13477. this.embeddedFonts[fontObj.loadedName] = fontObj;
  13478. }
  13479. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  13480. let bold = "normal";
  13481. if (fontObj.black) {
  13482. bold = "900";
  13483. } else if (fontObj.bold) {
  13484. bold = "bold";
  13485. }
  13486. const italic = fontObj.italic ? "italic" : "normal";
  13487. if (size < 0) {
  13488. size = -size;
  13489. current.fontDirection = -1;
  13490. } else {
  13491. current.fontDirection = 1;
  13492. }
  13493. current.fontSize = size;
  13494. current.fontFamily = fontObj.loadedName;
  13495. current.fontWeight = bold;
  13496. current.fontStyle = italic;
  13497. current.tspan = this.svgFactory.createElement("svg:tspan");
  13498. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13499. current.xcoords = [];
  13500. current.ycoords = [];
  13501. }
  13502. endText() {
  13503. const current = this.current;
  13504. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  13505. current.element = current.txtElement;
  13506. this.clip("nonzero");
  13507. this.endPath();
  13508. }
  13509. }
  13510. setLineWidth(width) {
  13511. if (width > 0) {
  13512. this.current.lineWidth = width;
  13513. }
  13514. }
  13515. setLineCap(style) {
  13516. this.current.lineCap = LINE_CAP_STYLES[style];
  13517. }
  13518. setLineJoin(style) {
  13519. this.current.lineJoin = LINE_JOIN_STYLES[style];
  13520. }
  13521. setMiterLimit(limit) {
  13522. this.current.miterLimit = limit;
  13523. }
  13524. setStrokeAlpha(strokeAlpha) {
  13525. this.current.strokeAlpha = strokeAlpha;
  13526. }
  13527. setStrokeRGBColor(r, g, b) {
  13528. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  13529. }
  13530. setFillAlpha(fillAlpha) {
  13531. this.current.fillAlpha = fillAlpha;
  13532. }
  13533. setFillRGBColor(r, g, b) {
  13534. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  13535. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  13536. this.current.xcoords = [];
  13537. this.current.ycoords = [];
  13538. }
  13539. setStrokeColorN(args) {
  13540. this.current.strokeColor = this._makeColorN_Pattern(args);
  13541. }
  13542. setFillColorN(args) {
  13543. this.current.fillColor = this._makeColorN_Pattern(args);
  13544. }
  13545. shadingFill(args) {
  13546. const width = this.viewport.width;
  13547. const height = this.viewport.height;
  13548. const inv = _util.Util.inverseTransform(this.transformMatrix);
  13549. const bl = _util.Util.applyTransform([0, 0], inv);
  13550. const br = _util.Util.applyTransform([0, height], inv);
  13551. const ul = _util.Util.applyTransform([width, 0], inv);
  13552. const ur = _util.Util.applyTransform([width, height], inv);
  13553. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  13554. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  13555. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  13556. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  13557. const rect = this.svgFactory.createElement("svg:rect");
  13558. rect.setAttributeNS(null, "x", x0);
  13559. rect.setAttributeNS(null, "y", y0);
  13560. rect.setAttributeNS(null, "width", x1 - x0);
  13561. rect.setAttributeNS(null, "height", y1 - y0);
  13562. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  13563. if (this.current.fillAlpha < 1) {
  13564. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  13565. }
  13566. this._ensureTransformGroup().append(rect);
  13567. }
  13568. _makeColorN_Pattern(args) {
  13569. if (args[0] === "TilingPattern") {
  13570. return this._makeTilingPattern(args);
  13571. }
  13572. return this._makeShadingPattern(args);
  13573. }
  13574. _makeTilingPattern(args) {
  13575. const color = args[1];
  13576. const operatorList = args[2];
  13577. const matrix = args[3] || _util.IDENTITY_MATRIX;
  13578. const [x0, y0, x1, y1] = args[4];
  13579. const xstep = args[5];
  13580. const ystep = args[6];
  13581. const paintType = args[7];
  13582. const tilingId = `shading${shadingCount++}`;
  13583. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  13584. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  13585. const txstep = xstep * xscale;
  13586. const tystep = ystep * yscale;
  13587. const tiling = this.svgFactory.createElement("svg:pattern");
  13588. tiling.setAttributeNS(null, "id", tilingId);
  13589. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  13590. tiling.setAttributeNS(null, "width", txstep);
  13591. tiling.setAttributeNS(null, "height", tystep);
  13592. tiling.setAttributeNS(null, "x", `${tx0}`);
  13593. tiling.setAttributeNS(null, "y", `${ty0}`);
  13594. const svg = this.svg;
  13595. const transformMatrix = this.transformMatrix;
  13596. const fillColor = this.current.fillColor;
  13597. const strokeColor = this.current.strokeColor;
  13598. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  13599. this.svg = bbox;
  13600. this.transformMatrix = matrix;
  13601. if (paintType === 2) {
  13602. const cssColor = _util.Util.makeHexColor(...color);
  13603. this.current.fillColor = cssColor;
  13604. this.current.strokeColor = cssColor;
  13605. }
  13606. this.executeOpTree(this.convertOpList(operatorList));
  13607. this.svg = svg;
  13608. this.transformMatrix = transformMatrix;
  13609. this.current.fillColor = fillColor;
  13610. this.current.strokeColor = strokeColor;
  13611. tiling.append(bbox.childNodes[0]);
  13612. this.defs.append(tiling);
  13613. return `url(#${tilingId})`;
  13614. }
  13615. _makeShadingPattern(args) {
  13616. if (typeof args === "string") {
  13617. args = this.objs.get(args);
  13618. }
  13619. switch (args[0]) {
  13620. case "RadialAxial":
  13621. const shadingId = `shading${shadingCount++}`;
  13622. const colorStops = args[3];
  13623. let gradient;
  13624. switch (args[1]) {
  13625. case "axial":
  13626. const point0 = args[4];
  13627. const point1 = args[5];
  13628. gradient = this.svgFactory.createElement("svg:linearGradient");
  13629. gradient.setAttributeNS(null, "id", shadingId);
  13630. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13631. gradient.setAttributeNS(null, "x1", point0[0]);
  13632. gradient.setAttributeNS(null, "y1", point0[1]);
  13633. gradient.setAttributeNS(null, "x2", point1[0]);
  13634. gradient.setAttributeNS(null, "y2", point1[1]);
  13635. break;
  13636. case "radial":
  13637. const focalPoint = args[4];
  13638. const circlePoint = args[5];
  13639. const focalRadius = args[6];
  13640. const circleRadius = args[7];
  13641. gradient = this.svgFactory.createElement("svg:radialGradient");
  13642. gradient.setAttributeNS(null, "id", shadingId);
  13643. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13644. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  13645. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  13646. gradient.setAttributeNS(null, "r", circleRadius);
  13647. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  13648. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  13649. gradient.setAttributeNS(null, "fr", focalRadius);
  13650. break;
  13651. default:
  13652. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  13653. }
  13654. for (const colorStop of colorStops) {
  13655. const stop = this.svgFactory.createElement("svg:stop");
  13656. stop.setAttributeNS(null, "offset", colorStop[0]);
  13657. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  13658. gradient.append(stop);
  13659. }
  13660. this.defs.append(gradient);
  13661. return `url(#${shadingId})`;
  13662. case "Mesh":
  13663. (0, _util.warn)("Unimplemented pattern Mesh");
  13664. return null;
  13665. case "Dummy":
  13666. return "hotpink";
  13667. default:
  13668. throw new Error(`Unknown IR type: ${args[0]}`);
  13669. }
  13670. }
  13671. setDash(dashArray, dashPhase) {
  13672. this.current.dashArray = dashArray;
  13673. this.current.dashPhase = dashPhase;
  13674. }
  13675. constructPath(ops, args) {
  13676. const current = this.current;
  13677. let x = current.x,
  13678. y = current.y;
  13679. let d = [];
  13680. let j = 0;
  13681. for (const op of ops) {
  13682. switch (op | 0) {
  13683. case _util.OPS.rectangle:
  13684. x = args[j++];
  13685. y = args[j++];
  13686. const width = args[j++];
  13687. const height = args[j++];
  13688. const xw = x + width;
  13689. const yh = y + height;
  13690. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  13691. break;
  13692. case _util.OPS.moveTo:
  13693. x = args[j++];
  13694. y = args[j++];
  13695. d.push("M", pf(x), pf(y));
  13696. break;
  13697. case _util.OPS.lineTo:
  13698. x = args[j++];
  13699. y = args[j++];
  13700. d.push("L", pf(x), pf(y));
  13701. break;
  13702. case _util.OPS.curveTo:
  13703. x = args[j + 4];
  13704. y = args[j + 5];
  13705. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  13706. j += 6;
  13707. break;
  13708. case _util.OPS.curveTo2:
  13709. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  13710. x = args[j + 2];
  13711. y = args[j + 3];
  13712. j += 4;
  13713. break;
  13714. case _util.OPS.curveTo3:
  13715. x = args[j + 2];
  13716. y = args[j + 3];
  13717. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  13718. j += 4;
  13719. break;
  13720. case _util.OPS.closePath:
  13721. d.push("Z");
  13722. break;
  13723. }
  13724. }
  13725. d = d.join(" ");
  13726. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  13727. d = current.path.getAttributeNS(null, "d") + d;
  13728. } else {
  13729. current.path = this.svgFactory.createElement("svg:path");
  13730. this._ensureTransformGroup().append(current.path);
  13731. }
  13732. current.path.setAttributeNS(null, "d", d);
  13733. current.path.setAttributeNS(null, "fill", "none");
  13734. current.element = current.path;
  13735. current.setCurrentPoint(x, y);
  13736. }
  13737. endPath() {
  13738. const current = this.current;
  13739. current.path = null;
  13740. if (!this.pendingClip) {
  13741. return;
  13742. }
  13743. if (!current.element) {
  13744. this.pendingClip = null;
  13745. return;
  13746. }
  13747. const clipId = `clippath${clipCount++}`;
  13748. const clipPath = this.svgFactory.createElement("svg:clipPath");
  13749. clipPath.setAttributeNS(null, "id", clipId);
  13750. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  13751. const clipElement = current.element.cloneNode(true);
  13752. if (this.pendingClip === "evenodd") {
  13753. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  13754. } else {
  13755. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  13756. }
  13757. this.pendingClip = null;
  13758. clipPath.append(clipElement);
  13759. this.defs.append(clipPath);
  13760. if (current.activeClipUrl) {
  13761. current.clipGroup = null;
  13762. for (const prev of this.extraStack) {
  13763. prev.clipGroup = null;
  13764. }
  13765. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  13766. }
  13767. current.activeClipUrl = `url(#${clipId})`;
  13768. this.tgrp = null;
  13769. }
  13770. clip(type) {
  13771. this.pendingClip = type;
  13772. }
  13773. closePath() {
  13774. const current = this.current;
  13775. if (current.path) {
  13776. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  13777. current.path.setAttributeNS(null, "d", d);
  13778. }
  13779. }
  13780. setLeading(leading) {
  13781. this.current.leading = -leading;
  13782. }
  13783. setTextRise(textRise) {
  13784. this.current.textRise = textRise;
  13785. }
  13786. setTextRenderingMode(textRenderingMode) {
  13787. this.current.textRenderingMode = textRenderingMode;
  13788. }
  13789. setHScale(scale) {
  13790. this.current.textHScale = scale / 100;
  13791. }
  13792. setRenderingIntent(intent) {}
  13793. setFlatness(flatness) {}
  13794. setGState(states) {
  13795. for (const [key, value] of states) {
  13796. switch (key) {
  13797. case "LW":
  13798. this.setLineWidth(value);
  13799. break;
  13800. case "LC":
  13801. this.setLineCap(value);
  13802. break;
  13803. case "LJ":
  13804. this.setLineJoin(value);
  13805. break;
  13806. case "ML":
  13807. this.setMiterLimit(value);
  13808. break;
  13809. case "D":
  13810. this.setDash(value[0], value[1]);
  13811. break;
  13812. case "RI":
  13813. this.setRenderingIntent(value);
  13814. break;
  13815. case "FL":
  13816. this.setFlatness(value);
  13817. break;
  13818. case "Font":
  13819. this.setFont(value);
  13820. break;
  13821. case "CA":
  13822. this.setStrokeAlpha(value);
  13823. break;
  13824. case "ca":
  13825. this.setFillAlpha(value);
  13826. break;
  13827. default:
  13828. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  13829. break;
  13830. }
  13831. }
  13832. }
  13833. fill() {
  13834. const current = this.current;
  13835. if (current.element) {
  13836. current.element.setAttributeNS(null, "fill", current.fillColor);
  13837. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  13838. this.endPath();
  13839. }
  13840. }
  13841. stroke() {
  13842. const current = this.current;
  13843. if (current.element) {
  13844. this._setStrokeAttributes(current.element);
  13845. current.element.setAttributeNS(null, "fill", "none");
  13846. this.endPath();
  13847. }
  13848. }
  13849. _setStrokeAttributes(element, lineWidthScale = 1) {
  13850. const current = this.current;
  13851. let dashArray = current.dashArray;
  13852. if (lineWidthScale !== 1 && dashArray.length > 0) {
  13853. dashArray = dashArray.map(function (value) {
  13854. return lineWidthScale * value;
  13855. });
  13856. }
  13857. element.setAttributeNS(null, "stroke", current.strokeColor);
  13858. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  13859. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  13860. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  13861. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  13862. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  13863. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  13864. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  13865. }
  13866. eoFill() {
  13867. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  13868. this.fill();
  13869. }
  13870. fillStroke() {
  13871. this.stroke();
  13872. this.fill();
  13873. }
  13874. eoFillStroke() {
  13875. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  13876. this.fillStroke();
  13877. }
  13878. closeStroke() {
  13879. this.closePath();
  13880. this.stroke();
  13881. }
  13882. closeFillStroke() {
  13883. this.closePath();
  13884. this.fillStroke();
  13885. }
  13886. closeEOFillStroke() {
  13887. this.closePath();
  13888. this.eoFillStroke();
  13889. }
  13890. paintSolidColorImageMask() {
  13891. const rect = this.svgFactory.createElement("svg:rect");
  13892. rect.setAttributeNS(null, "x", "0");
  13893. rect.setAttributeNS(null, "y", "0");
  13894. rect.setAttributeNS(null, "width", "1px");
  13895. rect.setAttributeNS(null, "height", "1px");
  13896. rect.setAttributeNS(null, "fill", this.current.fillColor);
  13897. this._ensureTransformGroup().append(rect);
  13898. }
  13899. paintImageXObject(objId) {
  13900. const imgData = this.getObject(objId);
  13901. if (!imgData) {
  13902. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  13903. return;
  13904. }
  13905. this.paintInlineImageXObject(imgData);
  13906. }
  13907. paintInlineImageXObject(imgData, mask) {
  13908. const width = imgData.width;
  13909. const height = imgData.height;
  13910. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  13911. const cliprect = this.svgFactory.createElement("svg:rect");
  13912. cliprect.setAttributeNS(null, "x", "0");
  13913. cliprect.setAttributeNS(null, "y", "0");
  13914. cliprect.setAttributeNS(null, "width", pf(width));
  13915. cliprect.setAttributeNS(null, "height", pf(height));
  13916. this.current.element = cliprect;
  13917. this.clip("nonzero");
  13918. const imgEl = this.svgFactory.createElement("svg:image");
  13919. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  13920. imgEl.setAttributeNS(null, "x", "0");
  13921. imgEl.setAttributeNS(null, "y", pf(-height));
  13922. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  13923. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  13924. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  13925. if (mask) {
  13926. mask.append(imgEl);
  13927. } else {
  13928. this._ensureTransformGroup().append(imgEl);
  13929. }
  13930. }
  13931. paintImageMaskXObject(img) {
  13932. const imgData = this.getObject(img.data, img);
  13933. if (imgData.bitmap) {
  13934. (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
  13935. return;
  13936. }
  13937. const current = this.current;
  13938. const width = imgData.width;
  13939. const height = imgData.height;
  13940. const fillColor = current.fillColor;
  13941. current.maskId = `mask${maskCount++}`;
  13942. const mask = this.svgFactory.createElement("svg:mask");
  13943. mask.setAttributeNS(null, "id", current.maskId);
  13944. const rect = this.svgFactory.createElement("svg:rect");
  13945. rect.setAttributeNS(null, "x", "0");
  13946. rect.setAttributeNS(null, "y", "0");
  13947. rect.setAttributeNS(null, "width", pf(width));
  13948. rect.setAttributeNS(null, "height", pf(height));
  13949. rect.setAttributeNS(null, "fill", fillColor);
  13950. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  13951. this.defs.append(mask);
  13952. this._ensureTransformGroup().append(rect);
  13953. this.paintInlineImageXObject(imgData, mask);
  13954. }
  13955. paintFormXObjectBegin(matrix, bbox) {
  13956. if (Array.isArray(matrix) && matrix.length === 6) {
  13957. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  13958. }
  13959. if (bbox) {
  13960. const width = bbox[2] - bbox[0];
  13961. const height = bbox[3] - bbox[1];
  13962. const cliprect = this.svgFactory.createElement("svg:rect");
  13963. cliprect.setAttributeNS(null, "x", bbox[0]);
  13964. cliprect.setAttributeNS(null, "y", bbox[1]);
  13965. cliprect.setAttributeNS(null, "width", pf(width));
  13966. cliprect.setAttributeNS(null, "height", pf(height));
  13967. this.current.element = cliprect;
  13968. this.clip("nonzero");
  13969. this.endPath();
  13970. }
  13971. }
  13972. paintFormXObjectEnd() {}
  13973. _initialize(viewport) {
  13974. const svg = this.svgFactory.create(viewport.width, viewport.height);
  13975. const definitions = this.svgFactory.createElement("svg:defs");
  13976. svg.append(definitions);
  13977. this.defs = definitions;
  13978. const rootGroup = this.svgFactory.createElement("svg:g");
  13979. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  13980. svg.append(rootGroup);
  13981. this.svg = rootGroup;
  13982. return svg;
  13983. }
  13984. _ensureClipGroup() {
  13985. if (!this.current.clipGroup) {
  13986. const clipGroup = this.svgFactory.createElement("svg:g");
  13987. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  13988. this.svg.append(clipGroup);
  13989. this.current.clipGroup = clipGroup;
  13990. }
  13991. return this.current.clipGroup;
  13992. }
  13993. _ensureTransformGroup() {
  13994. if (!this.tgrp) {
  13995. this.tgrp = this.svgFactory.createElement("svg:g");
  13996. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  13997. if (this.current.activeClipUrl) {
  13998. this._ensureClipGroup().append(this.tgrp);
  13999. } else {
  14000. this.svg.append(this.tgrp);
  14001. }
  14002. }
  14003. return this.tgrp;
  14004. }
  14005. };
  14006. }
  14007. /***/ }),
  14008. /* 31 */
  14009. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14010. Object.defineProperty(exports, "__esModule", ({
  14011. value: true
  14012. }));
  14013. exports.PDFNodeStream = void 0;
  14014. var _util = __w_pdfjs_require__(1);
  14015. var _network_utils = __w_pdfjs_require__(32);
  14016. ;
  14017. const fs = require("fs");
  14018. const http = require("http");
  14019. const https = require("https");
  14020. const url = require("url");
  14021. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  14022. function parseUrl(sourceUrl) {
  14023. const parsedUrl = url.parse(sourceUrl);
  14024. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  14025. return parsedUrl;
  14026. }
  14027. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  14028. return url.parse(`file:///${sourceUrl}`);
  14029. }
  14030. if (!parsedUrl.host) {
  14031. parsedUrl.protocol = "file:";
  14032. }
  14033. return parsedUrl;
  14034. }
  14035. class PDFNodeStream {
  14036. constructor(source) {
  14037. this.source = source;
  14038. this.url = parseUrl(source.url);
  14039. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  14040. this.isFsUrl = this.url.protocol === "file:";
  14041. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  14042. this._fullRequestReader = null;
  14043. this._rangeRequestReaders = [];
  14044. }
  14045. get _progressiveDataLength() {
  14046. return this._fullRequestReader?._loaded ?? 0;
  14047. }
  14048. getFullReader() {
  14049. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  14050. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  14051. return this._fullRequestReader;
  14052. }
  14053. getRangeReader(start, end) {
  14054. if (end <= this._progressiveDataLength) {
  14055. return null;
  14056. }
  14057. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  14058. this._rangeRequestReaders.push(rangeReader);
  14059. return rangeReader;
  14060. }
  14061. cancelAllRequests(reason) {
  14062. this._fullRequestReader?.cancel(reason);
  14063. for (const reader of this._rangeRequestReaders.slice(0)) {
  14064. reader.cancel(reason);
  14065. }
  14066. }
  14067. }
  14068. exports.PDFNodeStream = PDFNodeStream;
  14069. class BaseFullReader {
  14070. constructor(stream) {
  14071. this._url = stream.url;
  14072. this._done = false;
  14073. this._storedError = null;
  14074. this.onProgress = null;
  14075. const source = stream.source;
  14076. this._contentLength = source.length;
  14077. this._loaded = 0;
  14078. this._filename = null;
  14079. this._disableRange = source.disableRange || false;
  14080. this._rangeChunkSize = source.rangeChunkSize;
  14081. if (!this._rangeChunkSize && !this._disableRange) {
  14082. this._disableRange = true;
  14083. }
  14084. this._isStreamingSupported = !source.disableStream;
  14085. this._isRangeSupported = !source.disableRange;
  14086. this._readableStream = null;
  14087. this._readCapability = (0, _util.createPromiseCapability)();
  14088. this._headersCapability = (0, _util.createPromiseCapability)();
  14089. }
  14090. get headersReady() {
  14091. return this._headersCapability.promise;
  14092. }
  14093. get filename() {
  14094. return this._filename;
  14095. }
  14096. get contentLength() {
  14097. return this._contentLength;
  14098. }
  14099. get isRangeSupported() {
  14100. return this._isRangeSupported;
  14101. }
  14102. get isStreamingSupported() {
  14103. return this._isStreamingSupported;
  14104. }
  14105. async read() {
  14106. await this._readCapability.promise;
  14107. if (this._done) {
  14108. return {
  14109. value: undefined,
  14110. done: true
  14111. };
  14112. }
  14113. if (this._storedError) {
  14114. throw this._storedError;
  14115. }
  14116. const chunk = this._readableStream.read();
  14117. if (chunk === null) {
  14118. this._readCapability = (0, _util.createPromiseCapability)();
  14119. return this.read();
  14120. }
  14121. this._loaded += chunk.length;
  14122. this.onProgress?.({
  14123. loaded: this._loaded,
  14124. total: this._contentLength
  14125. });
  14126. const buffer = new Uint8Array(chunk).buffer;
  14127. return {
  14128. value: buffer,
  14129. done: false
  14130. };
  14131. }
  14132. cancel(reason) {
  14133. if (!this._readableStream) {
  14134. this._error(reason);
  14135. return;
  14136. }
  14137. this._readableStream.destroy(reason);
  14138. }
  14139. _error(reason) {
  14140. this._storedError = reason;
  14141. this._readCapability.resolve();
  14142. }
  14143. _setReadableStream(readableStream) {
  14144. this._readableStream = readableStream;
  14145. readableStream.on("readable", () => {
  14146. this._readCapability.resolve();
  14147. });
  14148. readableStream.on("end", () => {
  14149. readableStream.destroy();
  14150. this._done = true;
  14151. this._readCapability.resolve();
  14152. });
  14153. readableStream.on("error", reason => {
  14154. this._error(reason);
  14155. });
  14156. if (!this._isStreamingSupported && this._isRangeSupported) {
  14157. this._error(new _util.AbortException("streaming is disabled"));
  14158. }
  14159. if (this._storedError) {
  14160. this._readableStream.destroy(this._storedError);
  14161. }
  14162. }
  14163. }
  14164. class BaseRangeReader {
  14165. constructor(stream) {
  14166. this._url = stream.url;
  14167. this._done = false;
  14168. this._storedError = null;
  14169. this.onProgress = null;
  14170. this._loaded = 0;
  14171. this._readableStream = null;
  14172. this._readCapability = (0, _util.createPromiseCapability)();
  14173. const source = stream.source;
  14174. this._isStreamingSupported = !source.disableStream;
  14175. }
  14176. get isStreamingSupported() {
  14177. return this._isStreamingSupported;
  14178. }
  14179. async read() {
  14180. await this._readCapability.promise;
  14181. if (this._done) {
  14182. return {
  14183. value: undefined,
  14184. done: true
  14185. };
  14186. }
  14187. if (this._storedError) {
  14188. throw this._storedError;
  14189. }
  14190. const chunk = this._readableStream.read();
  14191. if (chunk === null) {
  14192. this._readCapability = (0, _util.createPromiseCapability)();
  14193. return this.read();
  14194. }
  14195. this._loaded += chunk.length;
  14196. this.onProgress?.({
  14197. loaded: this._loaded
  14198. });
  14199. const buffer = new Uint8Array(chunk).buffer;
  14200. return {
  14201. value: buffer,
  14202. done: false
  14203. };
  14204. }
  14205. cancel(reason) {
  14206. if (!this._readableStream) {
  14207. this._error(reason);
  14208. return;
  14209. }
  14210. this._readableStream.destroy(reason);
  14211. }
  14212. _error(reason) {
  14213. this._storedError = reason;
  14214. this._readCapability.resolve();
  14215. }
  14216. _setReadableStream(readableStream) {
  14217. this._readableStream = readableStream;
  14218. readableStream.on("readable", () => {
  14219. this._readCapability.resolve();
  14220. });
  14221. readableStream.on("end", () => {
  14222. readableStream.destroy();
  14223. this._done = true;
  14224. this._readCapability.resolve();
  14225. });
  14226. readableStream.on("error", reason => {
  14227. this._error(reason);
  14228. });
  14229. if (this._storedError) {
  14230. this._readableStream.destroy(this._storedError);
  14231. }
  14232. }
  14233. }
  14234. function createRequestOptions(parsedUrl, headers) {
  14235. return {
  14236. protocol: parsedUrl.protocol,
  14237. auth: parsedUrl.auth,
  14238. host: parsedUrl.hostname,
  14239. port: parsedUrl.port,
  14240. path: parsedUrl.path,
  14241. method: "GET",
  14242. headers
  14243. };
  14244. }
  14245. class PDFNodeStreamFullReader extends BaseFullReader {
  14246. constructor(stream) {
  14247. super(stream);
  14248. const handleResponse = response => {
  14249. if (response.statusCode === 404) {
  14250. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14251. this._storedError = error;
  14252. this._headersCapability.reject(error);
  14253. return;
  14254. }
  14255. this._headersCapability.resolve();
  14256. this._setReadableStream(response);
  14257. const getResponseHeader = name => {
  14258. return this._readableStream.headers[name.toLowerCase()];
  14259. };
  14260. const {
  14261. allowRangeRequests,
  14262. suggestedLength
  14263. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14264. getResponseHeader,
  14265. isHttp: stream.isHttp,
  14266. rangeChunkSize: this._rangeChunkSize,
  14267. disableRange: this._disableRange
  14268. });
  14269. this._isRangeSupported = allowRangeRequests;
  14270. this._contentLength = suggestedLength || this._contentLength;
  14271. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14272. };
  14273. this._request = null;
  14274. if (this._url.protocol === "http:") {
  14275. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14276. } else {
  14277. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14278. }
  14279. this._request.on("error", reason => {
  14280. this._storedError = reason;
  14281. this._headersCapability.reject(reason);
  14282. });
  14283. this._request.end();
  14284. }
  14285. }
  14286. class PDFNodeStreamRangeReader extends BaseRangeReader {
  14287. constructor(stream, start, end) {
  14288. super(stream);
  14289. this._httpHeaders = {};
  14290. for (const property in stream.httpHeaders) {
  14291. const value = stream.httpHeaders[property];
  14292. if (typeof value === "undefined") {
  14293. continue;
  14294. }
  14295. this._httpHeaders[property] = value;
  14296. }
  14297. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  14298. const handleResponse = response => {
  14299. if (response.statusCode === 404) {
  14300. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14301. this._storedError = error;
  14302. return;
  14303. }
  14304. this._setReadableStream(response);
  14305. };
  14306. this._request = null;
  14307. if (this._url.protocol === "http:") {
  14308. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14309. } else {
  14310. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14311. }
  14312. this._request.on("error", reason => {
  14313. this._storedError = reason;
  14314. });
  14315. this._request.end();
  14316. }
  14317. }
  14318. class PDFNodeStreamFsFullReader extends BaseFullReader {
  14319. constructor(stream) {
  14320. super(stream);
  14321. let path = decodeURIComponent(this._url.path);
  14322. if (fileUriRegex.test(this._url.href)) {
  14323. path = path.replace(/^\//, "");
  14324. }
  14325. fs.lstat(path, (error, stat) => {
  14326. if (error) {
  14327. if (error.code === "ENOENT") {
  14328. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  14329. }
  14330. this._storedError = error;
  14331. this._headersCapability.reject(error);
  14332. return;
  14333. }
  14334. this._contentLength = stat.size;
  14335. this._setReadableStream(fs.createReadStream(path));
  14336. this._headersCapability.resolve();
  14337. });
  14338. }
  14339. }
  14340. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  14341. constructor(stream, start, end) {
  14342. super(stream);
  14343. let path = decodeURIComponent(this._url.path);
  14344. if (fileUriRegex.test(this._url.href)) {
  14345. path = path.replace(/^\//, "");
  14346. }
  14347. this._setReadableStream(fs.createReadStream(path, {
  14348. start,
  14349. end: end - 1
  14350. }));
  14351. }
  14352. }
  14353. /***/ }),
  14354. /* 32 */
  14355. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14356. Object.defineProperty(exports, "__esModule", ({
  14357. value: true
  14358. }));
  14359. exports.createResponseStatusError = createResponseStatusError;
  14360. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  14361. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  14362. exports.validateResponseStatus = validateResponseStatus;
  14363. var _util = __w_pdfjs_require__(1);
  14364. var _content_disposition = __w_pdfjs_require__(33);
  14365. var _display_utils = __w_pdfjs_require__(6);
  14366. function validateRangeRequestCapabilities({
  14367. getResponseHeader,
  14368. isHttp,
  14369. rangeChunkSize,
  14370. disableRange
  14371. }) {
  14372. const returnValues = {
  14373. allowRangeRequests: false,
  14374. suggestedLength: undefined
  14375. };
  14376. const length = parseInt(getResponseHeader("Content-Length"), 10);
  14377. if (!Number.isInteger(length)) {
  14378. return returnValues;
  14379. }
  14380. returnValues.suggestedLength = length;
  14381. if (length <= 2 * rangeChunkSize) {
  14382. return returnValues;
  14383. }
  14384. if (disableRange || !isHttp) {
  14385. return returnValues;
  14386. }
  14387. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  14388. return returnValues;
  14389. }
  14390. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  14391. if (contentEncoding !== "identity") {
  14392. return returnValues;
  14393. }
  14394. returnValues.allowRangeRequests = true;
  14395. return returnValues;
  14396. }
  14397. function extractFilenameFromHeader(getResponseHeader) {
  14398. const contentDisposition = getResponseHeader("Content-Disposition");
  14399. if (contentDisposition) {
  14400. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  14401. if (filename.includes("%")) {
  14402. try {
  14403. filename = decodeURIComponent(filename);
  14404. } catch (ex) {}
  14405. }
  14406. if ((0, _display_utils.isPdfFile)(filename)) {
  14407. return filename;
  14408. }
  14409. }
  14410. return null;
  14411. }
  14412. function createResponseStatusError(status, url) {
  14413. if (status === 404 || status === 0 && url.startsWith("file:")) {
  14414. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  14415. }
  14416. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  14417. }
  14418. function validateResponseStatus(status) {
  14419. return status === 200 || status === 206;
  14420. }
  14421. /***/ }),
  14422. /* 33 */
  14423. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14424. Object.defineProperty(exports, "__esModule", ({
  14425. value: true
  14426. }));
  14427. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  14428. var _util = __w_pdfjs_require__(1);
  14429. function getFilenameFromContentDispositionHeader(contentDisposition) {
  14430. let needsEncodingFixup = true;
  14431. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  14432. if (tmp) {
  14433. tmp = tmp[1];
  14434. let filename = rfc2616unquote(tmp);
  14435. filename = unescape(filename);
  14436. filename = rfc5987decode(filename);
  14437. filename = rfc2047decode(filename);
  14438. return fixupEncoding(filename);
  14439. }
  14440. tmp = rfc2231getparam(contentDisposition);
  14441. if (tmp) {
  14442. const filename = rfc2047decode(tmp);
  14443. return fixupEncoding(filename);
  14444. }
  14445. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  14446. if (tmp) {
  14447. tmp = tmp[1];
  14448. let filename = rfc2616unquote(tmp);
  14449. filename = rfc2047decode(filename);
  14450. return fixupEncoding(filename);
  14451. }
  14452. function toParamRegExp(attributePattern, flags) {
  14453. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  14454. }
  14455. function textdecode(encoding, value) {
  14456. if (encoding) {
  14457. if (!/^[\x00-\xFF]+$/.test(value)) {
  14458. return value;
  14459. }
  14460. try {
  14461. const decoder = new TextDecoder(encoding, {
  14462. fatal: true
  14463. });
  14464. const buffer = (0, _util.stringToBytes)(value);
  14465. value = decoder.decode(buffer);
  14466. needsEncodingFixup = false;
  14467. } catch (e) {}
  14468. }
  14469. return value;
  14470. }
  14471. function fixupEncoding(value) {
  14472. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  14473. value = textdecode("utf-8", value);
  14474. if (needsEncodingFixup) {
  14475. value = textdecode("iso-8859-1", value);
  14476. }
  14477. }
  14478. return value;
  14479. }
  14480. function rfc2231getparam(contentDispositionStr) {
  14481. const matches = [];
  14482. let match;
  14483. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  14484. while ((match = iter.exec(contentDispositionStr)) !== null) {
  14485. let [, n, quot, part] = match;
  14486. n = parseInt(n, 10);
  14487. if (n in matches) {
  14488. if (n === 0) {
  14489. break;
  14490. }
  14491. continue;
  14492. }
  14493. matches[n] = [quot, part];
  14494. }
  14495. const parts = [];
  14496. for (let n = 0; n < matches.length; ++n) {
  14497. if (!(n in matches)) {
  14498. break;
  14499. }
  14500. let [quot, part] = matches[n];
  14501. part = rfc2616unquote(part);
  14502. if (quot) {
  14503. part = unescape(part);
  14504. if (n === 0) {
  14505. part = rfc5987decode(part);
  14506. }
  14507. }
  14508. parts.push(part);
  14509. }
  14510. return parts.join("");
  14511. }
  14512. function rfc2616unquote(value) {
  14513. if (value.startsWith('"')) {
  14514. const parts = value.slice(1).split('\\"');
  14515. for (let i = 0; i < parts.length; ++i) {
  14516. const quotindex = parts[i].indexOf('"');
  14517. if (quotindex !== -1) {
  14518. parts[i] = parts[i].slice(0, quotindex);
  14519. parts.length = i + 1;
  14520. }
  14521. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  14522. }
  14523. value = parts.join('"');
  14524. }
  14525. return value;
  14526. }
  14527. function rfc5987decode(extvalue) {
  14528. const encodingend = extvalue.indexOf("'");
  14529. if (encodingend === -1) {
  14530. return extvalue;
  14531. }
  14532. const encoding = extvalue.slice(0, encodingend);
  14533. const langvalue = extvalue.slice(encodingend + 1);
  14534. const value = langvalue.replace(/^[^']*'/, "");
  14535. return textdecode(encoding, value);
  14536. }
  14537. function rfc2047decode(value) {
  14538. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  14539. return value;
  14540. }
  14541. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  14542. if (encoding === "q" || encoding === "Q") {
  14543. text = text.replace(/_/g, " ");
  14544. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  14545. return String.fromCharCode(parseInt(hex, 16));
  14546. });
  14547. return textdecode(charset, text);
  14548. }
  14549. try {
  14550. text = atob(text);
  14551. } catch (e) {}
  14552. return textdecode(charset, text);
  14553. });
  14554. }
  14555. return "";
  14556. }
  14557. /***/ }),
  14558. /* 34 */
  14559. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14560. Object.defineProperty(exports, "__esModule", ({
  14561. value: true
  14562. }));
  14563. exports.PDFNetworkStream = void 0;
  14564. var _util = __w_pdfjs_require__(1);
  14565. var _network_utils = __w_pdfjs_require__(32);
  14566. ;
  14567. const OK_RESPONSE = 200;
  14568. const PARTIAL_CONTENT_RESPONSE = 206;
  14569. function getArrayBuffer(xhr) {
  14570. const data = xhr.response;
  14571. if (typeof data !== "string") {
  14572. return data;
  14573. }
  14574. const array = (0, _util.stringToBytes)(data);
  14575. return array.buffer;
  14576. }
  14577. class NetworkManager {
  14578. constructor(url, args = {}) {
  14579. this.url = url;
  14580. this.isHttp = /^https?:/i.test(url);
  14581. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  14582. this.withCredentials = args.withCredentials || false;
  14583. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  14584. return new XMLHttpRequest();
  14585. };
  14586. this.currXhrId = 0;
  14587. this.pendingRequests = Object.create(null);
  14588. }
  14589. requestRange(begin, end, listeners) {
  14590. const args = {
  14591. begin,
  14592. end
  14593. };
  14594. for (const prop in listeners) {
  14595. args[prop] = listeners[prop];
  14596. }
  14597. return this.request(args);
  14598. }
  14599. requestFull(listeners) {
  14600. return this.request(listeners);
  14601. }
  14602. request(args) {
  14603. const xhr = this.getXhr();
  14604. const xhrId = this.currXhrId++;
  14605. const pendingRequest = this.pendingRequests[xhrId] = {
  14606. xhr
  14607. };
  14608. xhr.open("GET", this.url);
  14609. xhr.withCredentials = this.withCredentials;
  14610. for (const property in this.httpHeaders) {
  14611. const value = this.httpHeaders[property];
  14612. if (typeof value === "undefined") {
  14613. continue;
  14614. }
  14615. xhr.setRequestHeader(property, value);
  14616. }
  14617. if (this.isHttp && "begin" in args && "end" in args) {
  14618. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  14619. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  14620. } else {
  14621. pendingRequest.expectedStatus = OK_RESPONSE;
  14622. }
  14623. xhr.responseType = "arraybuffer";
  14624. if (args.onError) {
  14625. xhr.onerror = function (evt) {
  14626. args.onError(xhr.status);
  14627. };
  14628. }
  14629. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  14630. xhr.onprogress = this.onProgress.bind(this, xhrId);
  14631. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  14632. pendingRequest.onDone = args.onDone;
  14633. pendingRequest.onError = args.onError;
  14634. pendingRequest.onProgress = args.onProgress;
  14635. xhr.send(null);
  14636. return xhrId;
  14637. }
  14638. onProgress(xhrId, evt) {
  14639. const pendingRequest = this.pendingRequests[xhrId];
  14640. if (!pendingRequest) {
  14641. return;
  14642. }
  14643. pendingRequest.onProgress?.(evt);
  14644. }
  14645. onStateChange(xhrId, evt) {
  14646. const pendingRequest = this.pendingRequests[xhrId];
  14647. if (!pendingRequest) {
  14648. return;
  14649. }
  14650. const xhr = pendingRequest.xhr;
  14651. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  14652. pendingRequest.onHeadersReceived();
  14653. delete pendingRequest.onHeadersReceived;
  14654. }
  14655. if (xhr.readyState !== 4) {
  14656. return;
  14657. }
  14658. if (!(xhrId in this.pendingRequests)) {
  14659. return;
  14660. }
  14661. delete this.pendingRequests[xhrId];
  14662. if (xhr.status === 0 && this.isHttp) {
  14663. pendingRequest.onError?.(xhr.status);
  14664. return;
  14665. }
  14666. const xhrStatus = xhr.status || OK_RESPONSE;
  14667. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  14668. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  14669. pendingRequest.onError?.(xhr.status);
  14670. return;
  14671. }
  14672. const chunk = getArrayBuffer(xhr);
  14673. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  14674. const rangeHeader = xhr.getResponseHeader("Content-Range");
  14675. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  14676. pendingRequest.onDone({
  14677. begin: parseInt(matches[1], 10),
  14678. chunk
  14679. });
  14680. } else if (chunk) {
  14681. pendingRequest.onDone({
  14682. begin: 0,
  14683. chunk
  14684. });
  14685. } else {
  14686. pendingRequest.onError?.(xhr.status);
  14687. }
  14688. }
  14689. getRequestXhr(xhrId) {
  14690. return this.pendingRequests[xhrId].xhr;
  14691. }
  14692. isPendingRequest(xhrId) {
  14693. return xhrId in this.pendingRequests;
  14694. }
  14695. abortRequest(xhrId) {
  14696. const xhr = this.pendingRequests[xhrId].xhr;
  14697. delete this.pendingRequests[xhrId];
  14698. xhr.abort();
  14699. }
  14700. }
  14701. class PDFNetworkStream {
  14702. constructor(source) {
  14703. this._source = source;
  14704. this._manager = new NetworkManager(source.url, {
  14705. httpHeaders: source.httpHeaders,
  14706. withCredentials: source.withCredentials
  14707. });
  14708. this._rangeChunkSize = source.rangeChunkSize;
  14709. this._fullRequestReader = null;
  14710. this._rangeRequestReaders = [];
  14711. }
  14712. _onRangeRequestReaderClosed(reader) {
  14713. const i = this._rangeRequestReaders.indexOf(reader);
  14714. if (i >= 0) {
  14715. this._rangeRequestReaders.splice(i, 1);
  14716. }
  14717. }
  14718. getFullReader() {
  14719. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  14720. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  14721. return this._fullRequestReader;
  14722. }
  14723. getRangeReader(begin, end) {
  14724. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  14725. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  14726. this._rangeRequestReaders.push(reader);
  14727. return reader;
  14728. }
  14729. cancelAllRequests(reason) {
  14730. this._fullRequestReader?.cancel(reason);
  14731. for (const reader of this._rangeRequestReaders.slice(0)) {
  14732. reader.cancel(reason);
  14733. }
  14734. }
  14735. }
  14736. exports.PDFNetworkStream = PDFNetworkStream;
  14737. class PDFNetworkStreamFullRequestReader {
  14738. constructor(manager, source) {
  14739. this._manager = manager;
  14740. const args = {
  14741. onHeadersReceived: this._onHeadersReceived.bind(this),
  14742. onDone: this._onDone.bind(this),
  14743. onError: this._onError.bind(this),
  14744. onProgress: this._onProgress.bind(this)
  14745. };
  14746. this._url = source.url;
  14747. this._fullRequestId = manager.requestFull(args);
  14748. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  14749. this._disableRange = source.disableRange || false;
  14750. this._contentLength = source.length;
  14751. this._rangeChunkSize = source.rangeChunkSize;
  14752. if (!this._rangeChunkSize && !this._disableRange) {
  14753. this._disableRange = true;
  14754. }
  14755. this._isStreamingSupported = false;
  14756. this._isRangeSupported = false;
  14757. this._cachedChunks = [];
  14758. this._requests = [];
  14759. this._done = false;
  14760. this._storedError = undefined;
  14761. this._filename = null;
  14762. this.onProgress = null;
  14763. }
  14764. _onHeadersReceived() {
  14765. const fullRequestXhrId = this._fullRequestId;
  14766. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  14767. const getResponseHeader = name => {
  14768. return fullRequestXhr.getResponseHeader(name);
  14769. };
  14770. const {
  14771. allowRangeRequests,
  14772. suggestedLength
  14773. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14774. getResponseHeader,
  14775. isHttp: this._manager.isHttp,
  14776. rangeChunkSize: this._rangeChunkSize,
  14777. disableRange: this._disableRange
  14778. });
  14779. if (allowRangeRequests) {
  14780. this._isRangeSupported = true;
  14781. }
  14782. this._contentLength = suggestedLength || this._contentLength;
  14783. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14784. if (this._isRangeSupported) {
  14785. this._manager.abortRequest(fullRequestXhrId);
  14786. }
  14787. this._headersReceivedCapability.resolve();
  14788. }
  14789. _onDone(data) {
  14790. if (data) {
  14791. if (this._requests.length > 0) {
  14792. const requestCapability = this._requests.shift();
  14793. requestCapability.resolve({
  14794. value: data.chunk,
  14795. done: false
  14796. });
  14797. } else {
  14798. this._cachedChunks.push(data.chunk);
  14799. }
  14800. }
  14801. this._done = true;
  14802. if (this._cachedChunks.length > 0) {
  14803. return;
  14804. }
  14805. for (const requestCapability of this._requests) {
  14806. requestCapability.resolve({
  14807. value: undefined,
  14808. done: true
  14809. });
  14810. }
  14811. this._requests.length = 0;
  14812. }
  14813. _onError(status) {
  14814. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  14815. this._headersReceivedCapability.reject(this._storedError);
  14816. for (const requestCapability of this._requests) {
  14817. requestCapability.reject(this._storedError);
  14818. }
  14819. this._requests.length = 0;
  14820. this._cachedChunks.length = 0;
  14821. }
  14822. _onProgress(evt) {
  14823. this.onProgress?.({
  14824. loaded: evt.loaded,
  14825. total: evt.lengthComputable ? evt.total : this._contentLength
  14826. });
  14827. }
  14828. get filename() {
  14829. return this._filename;
  14830. }
  14831. get isRangeSupported() {
  14832. return this._isRangeSupported;
  14833. }
  14834. get isStreamingSupported() {
  14835. return this._isStreamingSupported;
  14836. }
  14837. get contentLength() {
  14838. return this._contentLength;
  14839. }
  14840. get headersReady() {
  14841. return this._headersReceivedCapability.promise;
  14842. }
  14843. async read() {
  14844. if (this._storedError) {
  14845. throw this._storedError;
  14846. }
  14847. if (this._cachedChunks.length > 0) {
  14848. const chunk = this._cachedChunks.shift();
  14849. return {
  14850. value: chunk,
  14851. done: false
  14852. };
  14853. }
  14854. if (this._done) {
  14855. return {
  14856. value: undefined,
  14857. done: true
  14858. };
  14859. }
  14860. const requestCapability = (0, _util.createPromiseCapability)();
  14861. this._requests.push(requestCapability);
  14862. return requestCapability.promise;
  14863. }
  14864. cancel(reason) {
  14865. this._done = true;
  14866. this._headersReceivedCapability.reject(reason);
  14867. for (const requestCapability of this._requests) {
  14868. requestCapability.resolve({
  14869. value: undefined,
  14870. done: true
  14871. });
  14872. }
  14873. this._requests.length = 0;
  14874. if (this._manager.isPendingRequest(this._fullRequestId)) {
  14875. this._manager.abortRequest(this._fullRequestId);
  14876. }
  14877. this._fullRequestReader = null;
  14878. }
  14879. }
  14880. class PDFNetworkStreamRangeRequestReader {
  14881. constructor(manager, begin, end) {
  14882. this._manager = manager;
  14883. const args = {
  14884. onDone: this._onDone.bind(this),
  14885. onError: this._onError.bind(this),
  14886. onProgress: this._onProgress.bind(this)
  14887. };
  14888. this._url = manager.url;
  14889. this._requestId = manager.requestRange(begin, end, args);
  14890. this._requests = [];
  14891. this._queuedChunk = null;
  14892. this._done = false;
  14893. this._storedError = undefined;
  14894. this.onProgress = null;
  14895. this.onClosed = null;
  14896. }
  14897. _close() {
  14898. this.onClosed?.(this);
  14899. }
  14900. _onDone(data) {
  14901. const chunk = data.chunk;
  14902. if (this._requests.length > 0) {
  14903. const requestCapability = this._requests.shift();
  14904. requestCapability.resolve({
  14905. value: chunk,
  14906. done: false
  14907. });
  14908. } else {
  14909. this._queuedChunk = chunk;
  14910. }
  14911. this._done = true;
  14912. for (const requestCapability of this._requests) {
  14913. requestCapability.resolve({
  14914. value: undefined,
  14915. done: true
  14916. });
  14917. }
  14918. this._requests.length = 0;
  14919. this._close();
  14920. }
  14921. _onError(status) {
  14922. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  14923. for (const requestCapability of this._requests) {
  14924. requestCapability.reject(this._storedError);
  14925. }
  14926. this._requests.length = 0;
  14927. this._queuedChunk = null;
  14928. }
  14929. _onProgress(evt) {
  14930. if (!this.isStreamingSupported) {
  14931. this.onProgress?.({
  14932. loaded: evt.loaded
  14933. });
  14934. }
  14935. }
  14936. get isStreamingSupported() {
  14937. return false;
  14938. }
  14939. async read() {
  14940. if (this._storedError) {
  14941. throw this._storedError;
  14942. }
  14943. if (this._queuedChunk !== null) {
  14944. const chunk = this._queuedChunk;
  14945. this._queuedChunk = null;
  14946. return {
  14947. value: chunk,
  14948. done: false
  14949. };
  14950. }
  14951. if (this._done) {
  14952. return {
  14953. value: undefined,
  14954. done: true
  14955. };
  14956. }
  14957. const requestCapability = (0, _util.createPromiseCapability)();
  14958. this._requests.push(requestCapability);
  14959. return requestCapability.promise;
  14960. }
  14961. cancel(reason) {
  14962. this._done = true;
  14963. for (const requestCapability of this._requests) {
  14964. requestCapability.resolve({
  14965. value: undefined,
  14966. done: true
  14967. });
  14968. }
  14969. this._requests.length = 0;
  14970. if (this._manager.isPendingRequest(this._requestId)) {
  14971. this._manager.abortRequest(this._requestId);
  14972. }
  14973. this._close();
  14974. }
  14975. }
  14976. /***/ }),
  14977. /* 35 */
  14978. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14979. Object.defineProperty(exports, "__esModule", ({
  14980. value: true
  14981. }));
  14982. exports.PDFFetchStream = void 0;
  14983. var _util = __w_pdfjs_require__(1);
  14984. var _network_utils = __w_pdfjs_require__(32);
  14985. ;
  14986. function createFetchOptions(headers, withCredentials, abortController) {
  14987. return {
  14988. method: "GET",
  14989. headers,
  14990. signal: abortController.signal,
  14991. mode: "cors",
  14992. credentials: withCredentials ? "include" : "same-origin",
  14993. redirect: "follow"
  14994. };
  14995. }
  14996. function createHeaders(httpHeaders) {
  14997. const headers = new Headers();
  14998. for (const property in httpHeaders) {
  14999. const value = httpHeaders[property];
  15000. if (typeof value === "undefined") {
  15001. continue;
  15002. }
  15003. headers.append(property, value);
  15004. }
  15005. return headers;
  15006. }
  15007. class PDFFetchStream {
  15008. constructor(source) {
  15009. this.source = source;
  15010. this.isHttp = /^https?:/i.test(source.url);
  15011. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  15012. this._fullRequestReader = null;
  15013. this._rangeRequestReaders = [];
  15014. }
  15015. get _progressiveDataLength() {
  15016. return this._fullRequestReader?._loaded ?? 0;
  15017. }
  15018. getFullReader() {
  15019. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  15020. this._fullRequestReader = new PDFFetchStreamReader(this);
  15021. return this._fullRequestReader;
  15022. }
  15023. getRangeReader(begin, end) {
  15024. if (end <= this._progressiveDataLength) {
  15025. return null;
  15026. }
  15027. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  15028. this._rangeRequestReaders.push(reader);
  15029. return reader;
  15030. }
  15031. cancelAllRequests(reason) {
  15032. this._fullRequestReader?.cancel(reason);
  15033. for (const reader of this._rangeRequestReaders.slice(0)) {
  15034. reader.cancel(reason);
  15035. }
  15036. }
  15037. }
  15038. exports.PDFFetchStream = PDFFetchStream;
  15039. class PDFFetchStreamReader {
  15040. constructor(stream) {
  15041. this._stream = stream;
  15042. this._reader = null;
  15043. this._loaded = 0;
  15044. this._filename = null;
  15045. const source = stream.source;
  15046. this._withCredentials = source.withCredentials || false;
  15047. this._contentLength = source.length;
  15048. this._headersCapability = (0, _util.createPromiseCapability)();
  15049. this._disableRange = source.disableRange || false;
  15050. this._rangeChunkSize = source.rangeChunkSize;
  15051. if (!this._rangeChunkSize && !this._disableRange) {
  15052. this._disableRange = true;
  15053. }
  15054. this._abortController = new AbortController();
  15055. this._isStreamingSupported = !source.disableStream;
  15056. this._isRangeSupported = !source.disableRange;
  15057. this._headers = createHeaders(this._stream.httpHeaders);
  15058. const url = source.url;
  15059. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15060. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15061. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15062. }
  15063. this._reader = response.body.getReader();
  15064. this._headersCapability.resolve();
  15065. const getResponseHeader = name => {
  15066. return response.headers.get(name);
  15067. };
  15068. const {
  15069. allowRangeRequests,
  15070. suggestedLength
  15071. } = (0, _network_utils.validateRangeRequestCapabilities)({
  15072. getResponseHeader,
  15073. isHttp: this._stream.isHttp,
  15074. rangeChunkSize: this._rangeChunkSize,
  15075. disableRange: this._disableRange
  15076. });
  15077. this._isRangeSupported = allowRangeRequests;
  15078. this._contentLength = suggestedLength || this._contentLength;
  15079. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15080. if (!this._isStreamingSupported && this._isRangeSupported) {
  15081. this.cancel(new _util.AbortException("Streaming is disabled."));
  15082. }
  15083. }).catch(this._headersCapability.reject);
  15084. this.onProgress = null;
  15085. }
  15086. get headersReady() {
  15087. return this._headersCapability.promise;
  15088. }
  15089. get filename() {
  15090. return this._filename;
  15091. }
  15092. get contentLength() {
  15093. return this._contentLength;
  15094. }
  15095. get isRangeSupported() {
  15096. return this._isRangeSupported;
  15097. }
  15098. get isStreamingSupported() {
  15099. return this._isStreamingSupported;
  15100. }
  15101. async read() {
  15102. await this._headersCapability.promise;
  15103. const {
  15104. value,
  15105. done
  15106. } = await this._reader.read();
  15107. if (done) {
  15108. return {
  15109. value,
  15110. done
  15111. };
  15112. }
  15113. this._loaded += value.byteLength;
  15114. this.onProgress?.({
  15115. loaded: this._loaded,
  15116. total: this._contentLength
  15117. });
  15118. const buffer = new Uint8Array(value).buffer;
  15119. return {
  15120. value: buffer,
  15121. done: false
  15122. };
  15123. }
  15124. cancel(reason) {
  15125. this._reader?.cancel(reason);
  15126. this._abortController.abort();
  15127. }
  15128. }
  15129. class PDFFetchStreamRangeReader {
  15130. constructor(stream, begin, end) {
  15131. this._stream = stream;
  15132. this._reader = null;
  15133. this._loaded = 0;
  15134. const source = stream.source;
  15135. this._withCredentials = source.withCredentials || false;
  15136. this._readCapability = (0, _util.createPromiseCapability)();
  15137. this._isStreamingSupported = !source.disableStream;
  15138. this._abortController = new AbortController();
  15139. this._headers = createHeaders(this._stream.httpHeaders);
  15140. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  15141. const url = source.url;
  15142. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15143. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15144. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15145. }
  15146. this._readCapability.resolve();
  15147. this._reader = response.body.getReader();
  15148. }).catch(this._readCapability.reject);
  15149. this.onProgress = null;
  15150. }
  15151. get isStreamingSupported() {
  15152. return this._isStreamingSupported;
  15153. }
  15154. async read() {
  15155. await this._readCapability.promise;
  15156. const {
  15157. value,
  15158. done
  15159. } = await this._reader.read();
  15160. if (done) {
  15161. return {
  15162. value,
  15163. done
  15164. };
  15165. }
  15166. this._loaded += value.byteLength;
  15167. this.onProgress?.({
  15168. loaded: this._loaded
  15169. });
  15170. const buffer = new Uint8Array(value).buffer;
  15171. return {
  15172. value: buffer,
  15173. done: false
  15174. };
  15175. }
  15176. cancel(reason) {
  15177. this._reader?.cancel(reason);
  15178. this._abortController.abort();
  15179. }
  15180. }
  15181. /***/ })
  15182. /******/ ]);
  15183. /************************************************************************/
  15184. /******/ // The module cache
  15185. /******/ var __webpack_module_cache__ = {};
  15186. /******/
  15187. /******/ // The require function
  15188. /******/ function __w_pdfjs_require__(moduleId) {
  15189. /******/ // Check if module is in cache
  15190. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  15191. /******/ if (cachedModule !== undefined) {
  15192. /******/ return cachedModule.exports;
  15193. /******/ }
  15194. /******/ // Create a new module (and put it into the cache)
  15195. /******/ var module = __webpack_module_cache__[moduleId] = {
  15196. /******/ // no module.id needed
  15197. /******/ // no module.loaded needed
  15198. /******/ exports: {}
  15199. /******/ };
  15200. /******/
  15201. /******/ // Execute the module function
  15202. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  15203. /******/
  15204. /******/ // Return the exports of the module
  15205. /******/ return module.exports;
  15206. /******/ }
  15207. /******/
  15208. /************************************************************************/
  15209. var __webpack_exports__ = {};
  15210. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  15211. (() => {
  15212. var exports = __webpack_exports__;
  15213. Object.defineProperty(exports, "__esModule", ({
  15214. value: true
  15215. }));
  15216. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  15217. enumerable: true,
  15218. get: function () {
  15219. return _annotation_editor_layer.AnnotationEditorLayer;
  15220. }
  15221. }));
  15222. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  15223. enumerable: true,
  15224. get: function () {
  15225. return _util.AnnotationEditorParamsType;
  15226. }
  15227. }));
  15228. Object.defineProperty(exports, "AnnotationEditorType", ({
  15229. enumerable: true,
  15230. get: function () {
  15231. return _util.AnnotationEditorType;
  15232. }
  15233. }));
  15234. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  15235. enumerable: true,
  15236. get: function () {
  15237. return _tools.AnnotationEditorUIManager;
  15238. }
  15239. }));
  15240. Object.defineProperty(exports, "AnnotationLayer", ({
  15241. enumerable: true,
  15242. get: function () {
  15243. return _annotation_layer.AnnotationLayer;
  15244. }
  15245. }));
  15246. Object.defineProperty(exports, "AnnotationMode", ({
  15247. enumerable: true,
  15248. get: function () {
  15249. return _util.AnnotationMode;
  15250. }
  15251. }));
  15252. Object.defineProperty(exports, "CMapCompressionType", ({
  15253. enumerable: true,
  15254. get: function () {
  15255. return _util.CMapCompressionType;
  15256. }
  15257. }));
  15258. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  15259. enumerable: true,
  15260. get: function () {
  15261. return _worker_options.GlobalWorkerOptions;
  15262. }
  15263. }));
  15264. Object.defineProperty(exports, "InvalidPDFException", ({
  15265. enumerable: true,
  15266. get: function () {
  15267. return _util.InvalidPDFException;
  15268. }
  15269. }));
  15270. Object.defineProperty(exports, "MissingPDFException", ({
  15271. enumerable: true,
  15272. get: function () {
  15273. return _util.MissingPDFException;
  15274. }
  15275. }));
  15276. Object.defineProperty(exports, "OPS", ({
  15277. enumerable: true,
  15278. get: function () {
  15279. return _util.OPS;
  15280. }
  15281. }));
  15282. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  15283. enumerable: true,
  15284. get: function () {
  15285. return _api.PDFDataRangeTransport;
  15286. }
  15287. }));
  15288. Object.defineProperty(exports, "PDFDateString", ({
  15289. enumerable: true,
  15290. get: function () {
  15291. return _display_utils.PDFDateString;
  15292. }
  15293. }));
  15294. Object.defineProperty(exports, "PDFWorker", ({
  15295. enumerable: true,
  15296. get: function () {
  15297. return _api.PDFWorker;
  15298. }
  15299. }));
  15300. Object.defineProperty(exports, "PasswordResponses", ({
  15301. enumerable: true,
  15302. get: function () {
  15303. return _util.PasswordResponses;
  15304. }
  15305. }));
  15306. Object.defineProperty(exports, "PermissionFlag", ({
  15307. enumerable: true,
  15308. get: function () {
  15309. return _util.PermissionFlag;
  15310. }
  15311. }));
  15312. Object.defineProperty(exports, "PixelsPerInch", ({
  15313. enumerable: true,
  15314. get: function () {
  15315. return _display_utils.PixelsPerInch;
  15316. }
  15317. }));
  15318. Object.defineProperty(exports, "RenderingCancelledException", ({
  15319. enumerable: true,
  15320. get: function () {
  15321. return _display_utils.RenderingCancelledException;
  15322. }
  15323. }));
  15324. Object.defineProperty(exports, "SVGGraphics", ({
  15325. enumerable: true,
  15326. get: function () {
  15327. return _svg.SVGGraphics;
  15328. }
  15329. }));
  15330. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  15331. enumerable: true,
  15332. get: function () {
  15333. return _util.UNSUPPORTED_FEATURES;
  15334. }
  15335. }));
  15336. Object.defineProperty(exports, "UnexpectedResponseException", ({
  15337. enumerable: true,
  15338. get: function () {
  15339. return _util.UnexpectedResponseException;
  15340. }
  15341. }));
  15342. Object.defineProperty(exports, "Util", ({
  15343. enumerable: true,
  15344. get: function () {
  15345. return _util.Util;
  15346. }
  15347. }));
  15348. Object.defineProperty(exports, "VerbosityLevel", ({
  15349. enumerable: true,
  15350. get: function () {
  15351. return _util.VerbosityLevel;
  15352. }
  15353. }));
  15354. Object.defineProperty(exports, "XfaLayer", ({
  15355. enumerable: true,
  15356. get: function () {
  15357. return _xfa_layer.XfaLayer;
  15358. }
  15359. }));
  15360. Object.defineProperty(exports, "build", ({
  15361. enumerable: true,
  15362. get: function () {
  15363. return _api.build;
  15364. }
  15365. }));
  15366. Object.defineProperty(exports, "createPromiseCapability", ({
  15367. enumerable: true,
  15368. get: function () {
  15369. return _util.createPromiseCapability;
  15370. }
  15371. }));
  15372. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  15373. enumerable: true,
  15374. get: function () {
  15375. return _util.createValidAbsoluteUrl;
  15376. }
  15377. }));
  15378. Object.defineProperty(exports, "getDocument", ({
  15379. enumerable: true,
  15380. get: function () {
  15381. return _api.getDocument;
  15382. }
  15383. }));
  15384. Object.defineProperty(exports, "getFilenameFromUrl", ({
  15385. enumerable: true,
  15386. get: function () {
  15387. return _display_utils.getFilenameFromUrl;
  15388. }
  15389. }));
  15390. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  15391. enumerable: true,
  15392. get: function () {
  15393. return _display_utils.getPdfFilenameFromUrl;
  15394. }
  15395. }));
  15396. Object.defineProperty(exports, "getXfaPageViewport", ({
  15397. enumerable: true,
  15398. get: function () {
  15399. return _display_utils.getXfaPageViewport;
  15400. }
  15401. }));
  15402. Object.defineProperty(exports, "isPdfFile", ({
  15403. enumerable: true,
  15404. get: function () {
  15405. return _display_utils.isPdfFile;
  15406. }
  15407. }));
  15408. Object.defineProperty(exports, "loadScript", ({
  15409. enumerable: true,
  15410. get: function () {
  15411. return _display_utils.loadScript;
  15412. }
  15413. }));
  15414. Object.defineProperty(exports, "renderTextLayer", ({
  15415. enumerable: true,
  15416. get: function () {
  15417. return _text_layer.renderTextLayer;
  15418. }
  15419. }));
  15420. Object.defineProperty(exports, "shadow", ({
  15421. enumerable: true,
  15422. get: function () {
  15423. return _util.shadow;
  15424. }
  15425. }));
  15426. Object.defineProperty(exports, "version", ({
  15427. enumerable: true,
  15428. get: function () {
  15429. return _api.version;
  15430. }
  15431. }));
  15432. var _util = __w_pdfjs_require__(1);
  15433. var _api = __w_pdfjs_require__(2);
  15434. var _display_utils = __w_pdfjs_require__(6);
  15435. var _annotation_editor_layer = __w_pdfjs_require__(21);
  15436. var _tools = __w_pdfjs_require__(5);
  15437. var _annotation_layer = __w_pdfjs_require__(26);
  15438. var _worker_options = __w_pdfjs_require__(14);
  15439. var _is_node = __w_pdfjs_require__(12);
  15440. var _text_layer = __w_pdfjs_require__(29);
  15441. var _svg = __w_pdfjs_require__(30);
  15442. var _xfa_layer = __w_pdfjs_require__(28);
  15443. const pdfjsVersion = '3.0.279';
  15444. const pdfjsBuild = 'd0823066c';
  15445. {
  15446. if (_is_node.isNodeJS) {
  15447. const {
  15448. PDFNodeStream
  15449. } = __w_pdfjs_require__(31);
  15450. (0, _api.setPDFNetworkStreamFactory)(params => {
  15451. return new PDFNodeStream(params);
  15452. });
  15453. } else {
  15454. const {
  15455. PDFNetworkStream
  15456. } = __w_pdfjs_require__(34);
  15457. const {
  15458. PDFFetchStream
  15459. } = __w_pdfjs_require__(35);
  15460. (0, _api.setPDFNetworkStreamFactory)(params => {
  15461. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  15462. return new PDFFetchStream(params);
  15463. }
  15464. return new PDFNetworkStream(params);
  15465. });
  15466. }
  15467. }
  15468. })();
  15469. /******/ return __webpack_exports__;
  15470. /******/ })()
  15471. ;
  15472. });
  15473. //# sourceMappingURL=pdf.js.map