pdf.js 491 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864
  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.BASELINE_FACTOR = 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.getModificationDate = getModificationDate;
  49. exports.getVerbosityLevel = getVerbosityLevel;
  50. exports.info = info;
  51. exports.isArrayBuffer = isArrayBuffer;
  52. exports.isArrayEqual = isArrayEqual;
  53. exports.objectFromMap = objectFromMap;
  54. exports.objectSize = objectSize;
  55. exports.setVerbosityLevel = setVerbosityLevel;
  56. exports.shadow = shadow;
  57. exports.string32 = string32;
  58. exports.stringToBytes = stringToBytes;
  59. exports.stringToPDFString = stringToPDFString;
  60. exports.stringToUTF8String = stringToUTF8String;
  61. exports.unreachable = unreachable;
  62. exports.utf8StringToString = utf8StringToString;
  63. exports.warn = warn;
  64. ;
  65. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  66. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  67. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  68. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  69. const LINE_FACTOR = 1.35;
  70. exports.LINE_FACTOR = LINE_FACTOR;
  71. const LINE_DESCENT_FACTOR = 0.35;
  72. exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
  73. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  74. exports.BASELINE_FACTOR = BASELINE_FACTOR;
  75. const RenderingIntentFlag = {
  76. ANY: 0x01,
  77. DISPLAY: 0x02,
  78. PRINT: 0x04,
  79. SAVE: 0x08,
  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, nonSerializable = false) {
  492. Object.defineProperty(obj, prop, {
  493. value,
  494. enumerable: !nonSerializable,
  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. static get platform() {
  659. if (typeof navigator === "undefined") {
  660. return shadow(this, "platform", {
  661. isWin: false,
  662. isMac: false
  663. });
  664. }
  665. return shadow(this, "platform", {
  666. isWin: navigator.platform.includes("Win"),
  667. isMac: navigator.platform.includes("Mac")
  668. });
  669. }
  670. }
  671. exports.FeatureTest = FeatureTest;
  672. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  673. class Util {
  674. static makeHexColor(r, g, b) {
  675. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  676. }
  677. static scaleMinMax(transform, minMax) {
  678. let temp;
  679. if (transform[0]) {
  680. if (transform[0] < 0) {
  681. temp = minMax[0];
  682. minMax[0] = minMax[1];
  683. minMax[1] = temp;
  684. }
  685. minMax[0] *= transform[0];
  686. minMax[1] *= transform[0];
  687. if (transform[3] < 0) {
  688. temp = minMax[2];
  689. minMax[2] = minMax[3];
  690. minMax[3] = temp;
  691. }
  692. minMax[2] *= transform[3];
  693. minMax[3] *= transform[3];
  694. } else {
  695. temp = minMax[0];
  696. minMax[0] = minMax[2];
  697. minMax[2] = temp;
  698. temp = minMax[1];
  699. minMax[1] = minMax[3];
  700. minMax[3] = temp;
  701. if (transform[1] < 0) {
  702. temp = minMax[2];
  703. minMax[2] = minMax[3];
  704. minMax[3] = temp;
  705. }
  706. minMax[2] *= transform[1];
  707. minMax[3] *= transform[1];
  708. if (transform[2] < 0) {
  709. temp = minMax[0];
  710. minMax[0] = minMax[1];
  711. minMax[1] = temp;
  712. }
  713. minMax[0] *= transform[2];
  714. minMax[1] *= transform[2];
  715. }
  716. minMax[0] += transform[4];
  717. minMax[1] += transform[4];
  718. minMax[2] += transform[5];
  719. minMax[3] += transform[5];
  720. }
  721. static transform(m1, m2) {
  722. 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]];
  723. }
  724. static applyTransform(p, m) {
  725. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  726. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  727. return [xt, yt];
  728. }
  729. static applyInverseTransform(p, m) {
  730. const d = m[0] * m[3] - m[1] * m[2];
  731. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  732. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  733. return [xt, yt];
  734. }
  735. static getAxialAlignedBoundingBox(r, m) {
  736. const p1 = Util.applyTransform(r, m);
  737. const p2 = Util.applyTransform(r.slice(2, 4), m);
  738. const p3 = Util.applyTransform([r[0], r[3]], m);
  739. const p4 = Util.applyTransform([r[2], r[1]], m);
  740. 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])];
  741. }
  742. static inverseTransform(m) {
  743. const d = m[0] * m[3] - m[1] * m[2];
  744. 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];
  745. }
  746. static singularValueDecompose2dScale(m) {
  747. const transpose = [m[0], m[2], m[1], m[3]];
  748. const a = m[0] * transpose[0] + m[1] * transpose[2];
  749. const b = m[0] * transpose[1] + m[1] * transpose[3];
  750. const c = m[2] * transpose[0] + m[3] * transpose[2];
  751. const d = m[2] * transpose[1] + m[3] * transpose[3];
  752. const first = (a + d) / 2;
  753. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  754. const sx = first + second || 1;
  755. const sy = first - second || 1;
  756. return [Math.sqrt(sx), Math.sqrt(sy)];
  757. }
  758. static normalizeRect(rect) {
  759. const r = rect.slice(0);
  760. if (rect[0] > rect[2]) {
  761. r[0] = rect[2];
  762. r[2] = rect[0];
  763. }
  764. if (rect[1] > rect[3]) {
  765. r[1] = rect[3];
  766. r[3] = rect[1];
  767. }
  768. return r;
  769. }
  770. static intersect(rect1, rect2) {
  771. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  772. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  773. if (xLow > xHigh) {
  774. return null;
  775. }
  776. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  777. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  778. if (yLow > yHigh) {
  779. return null;
  780. }
  781. return [xLow, yLow, xHigh, yHigh];
  782. }
  783. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  784. const tvalues = [],
  785. bounds = [[], []];
  786. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  787. for (let i = 0; i < 2; ++i) {
  788. if (i === 0) {
  789. b = 6 * x0 - 12 * x1 + 6 * x2;
  790. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  791. c = 3 * x1 - 3 * x0;
  792. } else {
  793. b = 6 * y0 - 12 * y1 + 6 * y2;
  794. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  795. c = 3 * y1 - 3 * y0;
  796. }
  797. if (Math.abs(a) < 1e-12) {
  798. if (Math.abs(b) < 1e-12) {
  799. continue;
  800. }
  801. t = -c / b;
  802. if (0 < t && t < 1) {
  803. tvalues.push(t);
  804. }
  805. continue;
  806. }
  807. b2ac = b * b - 4 * c * a;
  808. sqrtb2ac = Math.sqrt(b2ac);
  809. if (b2ac < 0) {
  810. continue;
  811. }
  812. t1 = (-b + sqrtb2ac) / (2 * a);
  813. if (0 < t1 && t1 < 1) {
  814. tvalues.push(t1);
  815. }
  816. t2 = (-b - sqrtb2ac) / (2 * a);
  817. if (0 < t2 && t2 < 1) {
  818. tvalues.push(t2);
  819. }
  820. }
  821. let j = tvalues.length,
  822. mt;
  823. const jlen = j;
  824. while (j--) {
  825. t = tvalues[j];
  826. mt = 1 - t;
  827. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  828. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  829. }
  830. bounds[0][jlen] = x0;
  831. bounds[1][jlen] = y0;
  832. bounds[0][jlen + 1] = x3;
  833. bounds[1][jlen + 1] = y3;
  834. bounds[0].length = bounds[1].length = jlen + 2;
  835. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  836. }
  837. }
  838. exports.Util = Util;
  839. 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];
  840. function stringToPDFString(str) {
  841. if (str[0] >= "\xEF") {
  842. let encoding;
  843. if (str[0] === "\xFE" && str[1] === "\xFF") {
  844. encoding = "utf-16be";
  845. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  846. encoding = "utf-16le";
  847. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  848. encoding = "utf-8";
  849. }
  850. if (encoding) {
  851. try {
  852. const decoder = new TextDecoder(encoding, {
  853. fatal: true
  854. });
  855. const buffer = stringToBytes(str);
  856. return decoder.decode(buffer);
  857. } catch (ex) {
  858. warn(`stringToPDFString: "${ex}".`);
  859. }
  860. }
  861. }
  862. const strBuf = [];
  863. for (let i = 0, ii = str.length; i < ii; i++) {
  864. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  865. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  866. }
  867. return strBuf.join("");
  868. }
  869. function stringToUTF8String(str) {
  870. return decodeURIComponent(escape(str));
  871. }
  872. function utf8StringToString(str) {
  873. return unescape(encodeURIComponent(str));
  874. }
  875. function isArrayBuffer(v) {
  876. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  877. }
  878. function isArrayEqual(arr1, arr2) {
  879. if (arr1.length !== arr2.length) {
  880. return false;
  881. }
  882. for (let i = 0, ii = arr1.length; i < ii; i++) {
  883. if (arr1[i] !== arr2[i]) {
  884. return false;
  885. }
  886. }
  887. return true;
  888. }
  889. function getModificationDate(date = new Date()) {
  890. 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")];
  891. return buffer.join("");
  892. }
  893. function createPromiseCapability() {
  894. const capability = Object.create(null);
  895. let isSettled = false;
  896. Object.defineProperty(capability, "settled", {
  897. get() {
  898. return isSettled;
  899. }
  900. });
  901. capability.promise = new Promise(function (resolve, reject) {
  902. capability.resolve = function (data) {
  903. isSettled = true;
  904. resolve(data);
  905. };
  906. capability.reject = function (reason) {
  907. isSettled = true;
  908. reject(reason);
  909. };
  910. });
  911. return capability;
  912. }
  913. /***/ }),
  914. /* 2 */
  915. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  916. Object.defineProperty(exports, "__esModule", ({
  917. value: true
  918. }));
  919. 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;
  920. exports.getDocument = getDocument;
  921. exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
  922. exports.version = void 0;
  923. var _util = __w_pdfjs_require__(1);
  924. var _annotation_storage = __w_pdfjs_require__(3);
  925. var _display_utils = __w_pdfjs_require__(6);
  926. var _font_loader = __w_pdfjs_require__(9);
  927. var _canvas = __w_pdfjs_require__(11);
  928. var _worker_options = __w_pdfjs_require__(14);
  929. var _is_node = __w_pdfjs_require__(10);
  930. var _message_handler = __w_pdfjs_require__(15);
  931. var _metadata = __w_pdfjs_require__(16);
  932. var _optional_content_config = __w_pdfjs_require__(17);
  933. var _transport_stream = __w_pdfjs_require__(18);
  934. var _xfa_text = __w_pdfjs_require__(19);
  935. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  936. const RENDERING_CANCELLED_TIMEOUT = 100;
  937. let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
  938. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  939. let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
  940. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  941. let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
  942. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  943. if (_is_node.isNodeJS) {
  944. const {
  945. NodeCanvasFactory,
  946. NodeCMapReaderFactory,
  947. NodeStandardFontDataFactory
  948. } = __w_pdfjs_require__(20);
  949. exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  950. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  951. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
  952. }
  953. let createPDFNetworkStream;
  954. function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
  955. createPDFNetworkStream = pdfNetworkStreamFactory;
  956. }
  957. function getDocument(src) {
  958. const task = new PDFDocumentLoadingTask();
  959. let source;
  960. if (typeof src === "string" || src instanceof URL) {
  961. source = {
  962. url: src
  963. };
  964. } else if ((0, _util.isArrayBuffer)(src)) {
  965. source = {
  966. data: src
  967. };
  968. } else if (src instanceof PDFDataRangeTransport) {
  969. source = {
  970. range: src
  971. };
  972. } else {
  973. if (typeof src !== "object") {
  974. throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
  975. }
  976. if (!src.url && !src.data && !src.range) {
  977. throw new Error("Invalid parameter object: need either .data, .range or .url");
  978. }
  979. source = src;
  980. }
  981. const params = Object.create(null);
  982. let rangeTransport = null,
  983. worker = null;
  984. for (const key in source) {
  985. const value = source[key];
  986. switch (key) {
  987. case "url":
  988. if (typeof window !== "undefined") {
  989. try {
  990. params[key] = new URL(value, window.location).href;
  991. continue;
  992. } catch (ex) {
  993. (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
  994. }
  995. } else if (typeof value === "string" || value instanceof URL) {
  996. params[key] = value.toString();
  997. continue;
  998. }
  999. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1000. case "range":
  1001. rangeTransport = value;
  1002. continue;
  1003. case "worker":
  1004. worker = value;
  1005. continue;
  1006. case "data":
  1007. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
  1008. params[key] = new Uint8Array(value);
  1009. } else if (value instanceof Uint8Array) {
  1010. break;
  1011. } else if (typeof value === "string") {
  1012. params[key] = (0, _util.stringToBytes)(value);
  1013. } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
  1014. params[key] = new Uint8Array(value);
  1015. } else if ((0, _util.isArrayBuffer)(value)) {
  1016. params[key] = new Uint8Array(value);
  1017. } else {
  1018. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  1019. }
  1020. continue;
  1021. }
  1022. params[key] = value;
  1023. }
  1024. params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
  1025. params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
  1026. params.ignoreErrors = params.stopAtErrors !== true;
  1027. params.fontExtraProperties = params.fontExtraProperties === true;
  1028. params.pdfBug = params.pdfBug === true;
  1029. params.enableXfa = params.enableXfa === true;
  1030. if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
  1031. params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
  1032. }
  1033. if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
  1034. params.docBaseUrl = null;
  1035. }
  1036. if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
  1037. params.maxImageSize = -1;
  1038. }
  1039. if (typeof params.cMapUrl !== "string") {
  1040. params.cMapUrl = null;
  1041. }
  1042. if (typeof params.standardFontDataUrl !== "string") {
  1043. params.standardFontDataUrl = null;
  1044. }
  1045. if (typeof params.useWorkerFetch !== "boolean") {
  1046. params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
  1047. }
  1048. if (typeof params.isEvalSupported !== "boolean") {
  1049. params.isEvalSupported = true;
  1050. }
  1051. if (typeof params.isOffscreenCanvasSupported !== "boolean") {
  1052. params.isOffscreenCanvasSupported = !_is_node.isNodeJS;
  1053. }
  1054. if (typeof params.disableFontFace !== "boolean") {
  1055. params.disableFontFace = _is_node.isNodeJS;
  1056. }
  1057. if (typeof params.useSystemFonts !== "boolean") {
  1058. params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
  1059. }
  1060. if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
  1061. params.ownerDocument = globalThis.document;
  1062. }
  1063. if (typeof params.disableRange !== "boolean") {
  1064. params.disableRange = false;
  1065. }
  1066. if (typeof params.disableStream !== "boolean") {
  1067. params.disableStream = false;
  1068. }
  1069. if (typeof params.disableAutoFetch !== "boolean") {
  1070. params.disableAutoFetch = false;
  1071. }
  1072. (0, _util.setVerbosityLevel)(params.verbosity);
  1073. if (!worker) {
  1074. const workerParams = {
  1075. verbosity: params.verbosity,
  1076. port: _worker_options.GlobalWorkerOptions.workerPort
  1077. };
  1078. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  1079. task._worker = worker;
  1080. }
  1081. const docId = task.docId;
  1082. worker.promise.then(function () {
  1083. if (task.destroyed) {
  1084. throw new Error("Loading aborted");
  1085. }
  1086. const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
  1087. const networkStreamPromise = new Promise(function (resolve) {
  1088. let networkStream;
  1089. if (rangeTransport) {
  1090. networkStream = new _transport_stream.PDFDataTransportStream({
  1091. length: params.length,
  1092. initialData: params.initialData,
  1093. progressiveDone: params.progressiveDone,
  1094. contentDispositionFilename: params.contentDispositionFilename,
  1095. disableRange: params.disableRange,
  1096. disableStream: params.disableStream
  1097. }, rangeTransport);
  1098. } else if (!params.data) {
  1099. networkStream = createPDFNetworkStream({
  1100. url: params.url,
  1101. length: params.length,
  1102. httpHeaders: params.httpHeaders,
  1103. withCredentials: params.withCredentials,
  1104. rangeChunkSize: params.rangeChunkSize,
  1105. disableRange: params.disableRange,
  1106. disableStream: params.disableStream
  1107. });
  1108. }
  1109. resolve(networkStream);
  1110. });
  1111. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1112. if (task.destroyed) {
  1113. throw new Error("Loading aborted");
  1114. }
  1115. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1116. const transport = new WorkerTransport(messageHandler, task, networkStream, params);
  1117. task._transport = transport;
  1118. messageHandler.send("Ready", null);
  1119. });
  1120. }).catch(task._capability.reject);
  1121. return task;
  1122. }
  1123. async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  1124. if (worker.destroyed) {
  1125. throw new Error("Worker was destroyed");
  1126. }
  1127. if (pdfDataRangeTransport) {
  1128. source.length = pdfDataRangeTransport.length;
  1129. source.initialData = pdfDataRangeTransport.initialData;
  1130. source.progressiveDone = pdfDataRangeTransport.progressiveDone;
  1131. source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
  1132. }
  1133. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
  1134. docId,
  1135. apiVersion: '3.2.141',
  1136. data: source.data,
  1137. password: source.password,
  1138. disableAutoFetch: source.disableAutoFetch,
  1139. rangeChunkSize: source.rangeChunkSize,
  1140. length: source.length,
  1141. docBaseUrl: source.docBaseUrl,
  1142. enableXfa: source.enableXfa,
  1143. evaluatorOptions: {
  1144. maxImageSize: source.maxImageSize,
  1145. disableFontFace: source.disableFontFace,
  1146. ignoreErrors: source.ignoreErrors,
  1147. isEvalSupported: source.isEvalSupported,
  1148. isOffscreenCanvasSupported: source.isOffscreenCanvasSupported,
  1149. fontExtraProperties: source.fontExtraProperties,
  1150. useSystemFonts: source.useSystemFonts,
  1151. cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
  1152. standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
  1153. }
  1154. });
  1155. if (source.data) {
  1156. source.data = null;
  1157. }
  1158. if (worker.destroyed) {
  1159. throw new Error("Worker was destroyed");
  1160. }
  1161. return workerId;
  1162. }
  1163. class PDFDocumentLoadingTask {
  1164. static #docId = 0;
  1165. #onUnsupportedFeature = null;
  1166. constructor() {
  1167. this._capability = (0, _util.createPromiseCapability)();
  1168. this._transport = null;
  1169. this._worker = null;
  1170. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1171. this.destroyed = false;
  1172. this.onPassword = null;
  1173. this.onProgress = null;
  1174. }
  1175. get onUnsupportedFeature() {
  1176. return this.#onUnsupportedFeature;
  1177. }
  1178. set onUnsupportedFeature(callback) {
  1179. (0, _display_utils.deprecated)("The PDFDocumentLoadingTask onUnsupportedFeature property will be removed in the future.");
  1180. this.#onUnsupportedFeature = callback;
  1181. }
  1182. get promise() {
  1183. return this._capability.promise;
  1184. }
  1185. async destroy() {
  1186. this.destroyed = true;
  1187. await this._transport?.destroy();
  1188. this._transport = null;
  1189. if (this._worker) {
  1190. this._worker.destroy();
  1191. this._worker = null;
  1192. }
  1193. }
  1194. }
  1195. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1196. class PDFDataRangeTransport {
  1197. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1198. this.length = length;
  1199. this.initialData = initialData;
  1200. this.progressiveDone = progressiveDone;
  1201. this.contentDispositionFilename = contentDispositionFilename;
  1202. this._rangeListeners = [];
  1203. this._progressListeners = [];
  1204. this._progressiveReadListeners = [];
  1205. this._progressiveDoneListeners = [];
  1206. this._readyCapability = (0, _util.createPromiseCapability)();
  1207. }
  1208. addRangeListener(listener) {
  1209. this._rangeListeners.push(listener);
  1210. }
  1211. addProgressListener(listener) {
  1212. this._progressListeners.push(listener);
  1213. }
  1214. addProgressiveReadListener(listener) {
  1215. this._progressiveReadListeners.push(listener);
  1216. }
  1217. addProgressiveDoneListener(listener) {
  1218. this._progressiveDoneListeners.push(listener);
  1219. }
  1220. onDataRange(begin, chunk) {
  1221. for (const listener of this._rangeListeners) {
  1222. listener(begin, chunk);
  1223. }
  1224. }
  1225. onDataProgress(loaded, total) {
  1226. this._readyCapability.promise.then(() => {
  1227. for (const listener of this._progressListeners) {
  1228. listener(loaded, total);
  1229. }
  1230. });
  1231. }
  1232. onDataProgressiveRead(chunk) {
  1233. this._readyCapability.promise.then(() => {
  1234. for (const listener of this._progressiveReadListeners) {
  1235. listener(chunk);
  1236. }
  1237. });
  1238. }
  1239. onDataProgressiveDone() {
  1240. this._readyCapability.promise.then(() => {
  1241. for (const listener of this._progressiveDoneListeners) {
  1242. listener();
  1243. }
  1244. });
  1245. }
  1246. transportReady() {
  1247. this._readyCapability.resolve();
  1248. }
  1249. requestDataRange(begin, end) {
  1250. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1251. }
  1252. abort() {}
  1253. }
  1254. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1255. class PDFDocumentProxy {
  1256. constructor(pdfInfo, transport) {
  1257. this._pdfInfo = pdfInfo;
  1258. this._transport = transport;
  1259. }
  1260. get annotationStorage() {
  1261. return this._transport.annotationStorage;
  1262. }
  1263. get numPages() {
  1264. return this._pdfInfo.numPages;
  1265. }
  1266. get fingerprints() {
  1267. return this._pdfInfo.fingerprints;
  1268. }
  1269. get stats() {
  1270. (0, _display_utils.deprecated)("The PDFDocumentProxy stats property will be removed in the future.");
  1271. return this._transport.stats;
  1272. }
  1273. get isPureXfa() {
  1274. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1275. }
  1276. get allXfaHtml() {
  1277. return this._transport._htmlForXfa;
  1278. }
  1279. getPage(pageNumber) {
  1280. return this._transport.getPage(pageNumber);
  1281. }
  1282. getPageIndex(ref) {
  1283. return this._transport.getPageIndex(ref);
  1284. }
  1285. getDestinations() {
  1286. return this._transport.getDestinations();
  1287. }
  1288. getDestination(id) {
  1289. return this._transport.getDestination(id);
  1290. }
  1291. getPageLabels() {
  1292. return this._transport.getPageLabels();
  1293. }
  1294. getPageLayout() {
  1295. return this._transport.getPageLayout();
  1296. }
  1297. getPageMode() {
  1298. return this._transport.getPageMode();
  1299. }
  1300. getViewerPreferences() {
  1301. return this._transport.getViewerPreferences();
  1302. }
  1303. getOpenAction() {
  1304. return this._transport.getOpenAction();
  1305. }
  1306. getAttachments() {
  1307. return this._transport.getAttachments();
  1308. }
  1309. getJavaScript() {
  1310. return this._transport.getJavaScript();
  1311. }
  1312. getJSActions() {
  1313. return this._transport.getDocJSActions();
  1314. }
  1315. getOutline() {
  1316. return this._transport.getOutline();
  1317. }
  1318. getOptionalContentConfig() {
  1319. return this._transport.getOptionalContentConfig();
  1320. }
  1321. getPermissions() {
  1322. return this._transport.getPermissions();
  1323. }
  1324. getMetadata() {
  1325. return this._transport.getMetadata();
  1326. }
  1327. getMarkInfo() {
  1328. return this._transport.getMarkInfo();
  1329. }
  1330. getData() {
  1331. return this._transport.getData();
  1332. }
  1333. saveDocument() {
  1334. return this._transport.saveDocument();
  1335. }
  1336. getDownloadInfo() {
  1337. return this._transport.downloadInfoCapability.promise;
  1338. }
  1339. cleanup(keepLoadedFonts = false) {
  1340. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1341. }
  1342. destroy() {
  1343. return this.loadingTask.destroy();
  1344. }
  1345. get loadingParams() {
  1346. return this._transport.loadingParams;
  1347. }
  1348. get loadingTask() {
  1349. return this._transport.loadingTask;
  1350. }
  1351. getFieldObjects() {
  1352. return this._transport.getFieldObjects();
  1353. }
  1354. hasJSActions() {
  1355. return this._transport.hasJSActions();
  1356. }
  1357. getCalculationOrderIds() {
  1358. return this._transport.getCalculationOrderIds();
  1359. }
  1360. }
  1361. exports.PDFDocumentProxy = PDFDocumentProxy;
  1362. class PDFPageProxy {
  1363. constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
  1364. this._pageIndex = pageIndex;
  1365. this._pageInfo = pageInfo;
  1366. this._ownerDocument = ownerDocument;
  1367. this._transport = transport;
  1368. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1369. this._pdfBug = pdfBug;
  1370. this.commonObjs = transport.commonObjs;
  1371. this.objs = new PDFObjects();
  1372. this._bitmaps = new Set();
  1373. this.cleanupAfterRender = false;
  1374. this.pendingCleanup = false;
  1375. this._intentStates = new Map();
  1376. this.destroyed = false;
  1377. }
  1378. get pageNumber() {
  1379. return this._pageIndex + 1;
  1380. }
  1381. get rotate() {
  1382. return this._pageInfo.rotate;
  1383. }
  1384. get ref() {
  1385. return this._pageInfo.ref;
  1386. }
  1387. get userUnit() {
  1388. return this._pageInfo.userUnit;
  1389. }
  1390. get view() {
  1391. return this._pageInfo.view;
  1392. }
  1393. getViewport({
  1394. scale,
  1395. rotation = this.rotate,
  1396. offsetX = 0,
  1397. offsetY = 0,
  1398. dontFlip = false
  1399. } = {}) {
  1400. return new _display_utils.PageViewport({
  1401. viewBox: this.view,
  1402. scale,
  1403. rotation,
  1404. offsetX,
  1405. offsetY,
  1406. dontFlip
  1407. });
  1408. }
  1409. getAnnotations({
  1410. intent = "display"
  1411. } = {}) {
  1412. const intentArgs = this._transport.getRenderingIntent(intent);
  1413. return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1414. }
  1415. getJSActions() {
  1416. return this._transport.getPageJSActions(this._pageIndex);
  1417. }
  1418. get isPureXfa() {
  1419. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1420. }
  1421. async getXfa() {
  1422. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1423. }
  1424. render({
  1425. canvasContext,
  1426. viewport,
  1427. intent = "display",
  1428. annotationMode = _util.AnnotationMode.ENABLE,
  1429. transform = null,
  1430. canvasFactory = null,
  1431. background = null,
  1432. optionalContentConfigPromise = null,
  1433. annotationCanvasMap = null,
  1434. pageColors = null,
  1435. printAnnotationStorage = null
  1436. }) {
  1437. this._stats?.time("Overall");
  1438. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  1439. this.pendingCleanup = false;
  1440. if (!optionalContentConfigPromise) {
  1441. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1442. }
  1443. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1444. if (!intentState) {
  1445. intentState = Object.create(null);
  1446. this._intentStates.set(intentArgs.cacheKey, intentState);
  1447. }
  1448. if (intentState.streamReaderCancelTimeout) {
  1449. clearTimeout(intentState.streamReaderCancelTimeout);
  1450. intentState.streamReaderCancelTimeout = null;
  1451. }
  1452. const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
  1453. ownerDocument: this._ownerDocument
  1454. });
  1455. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1456. if (!intentState.displayReadyCapability) {
  1457. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1458. intentState.operatorList = {
  1459. fnArray: [],
  1460. argsArray: [],
  1461. lastChunk: false,
  1462. separateAnnots: null
  1463. };
  1464. this._stats?.time("Page Request");
  1465. this._pumpOperatorList(intentArgs);
  1466. }
  1467. const complete = error => {
  1468. intentState.renderTasks.delete(internalRenderTask);
  1469. if (this.cleanupAfterRender || intentPrint) {
  1470. this.pendingCleanup = true;
  1471. }
  1472. this._tryCleanup();
  1473. if (error) {
  1474. internalRenderTask.capability.reject(error);
  1475. this._abortOperatorList({
  1476. intentState,
  1477. reason: error instanceof Error ? error : new Error(error)
  1478. });
  1479. } else {
  1480. internalRenderTask.capability.resolve();
  1481. }
  1482. this._stats?.timeEnd("Rendering");
  1483. this._stats?.timeEnd("Overall");
  1484. };
  1485. const internalRenderTask = new InternalRenderTask({
  1486. callback: complete,
  1487. params: {
  1488. canvasContext,
  1489. viewport,
  1490. transform,
  1491. background
  1492. },
  1493. objs: this.objs,
  1494. commonObjs: this.commonObjs,
  1495. annotationCanvasMap,
  1496. operatorList: intentState.operatorList,
  1497. pageIndex: this._pageIndex,
  1498. canvasFactory: canvasFactoryInstance,
  1499. useRequestAnimationFrame: !intentPrint,
  1500. pdfBug: this._pdfBug,
  1501. pageColors
  1502. });
  1503. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  1504. const renderTask = internalRenderTask.task;
  1505. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1506. if (this.pendingCleanup) {
  1507. complete();
  1508. return;
  1509. }
  1510. this._stats?.time("Rendering");
  1511. internalRenderTask.initializeGraphics({
  1512. transparency,
  1513. optionalContentConfig
  1514. });
  1515. internalRenderTask.operatorListChanged();
  1516. }).catch(complete);
  1517. return renderTask;
  1518. }
  1519. getOperatorList({
  1520. intent = "display",
  1521. annotationMode = _util.AnnotationMode.ENABLE,
  1522. printAnnotationStorage = null
  1523. } = {}) {
  1524. function operatorListChanged() {
  1525. if (intentState.operatorList.lastChunk) {
  1526. intentState.opListReadCapability.resolve(intentState.operatorList);
  1527. intentState.renderTasks.delete(opListTask);
  1528. }
  1529. }
  1530. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  1531. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1532. if (!intentState) {
  1533. intentState = Object.create(null);
  1534. this._intentStates.set(intentArgs.cacheKey, intentState);
  1535. }
  1536. let opListTask;
  1537. if (!intentState.opListReadCapability) {
  1538. opListTask = Object.create(null);
  1539. opListTask.operatorListChanged = operatorListChanged;
  1540. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1541. (intentState.renderTasks ||= new Set()).add(opListTask);
  1542. intentState.operatorList = {
  1543. fnArray: [],
  1544. argsArray: [],
  1545. lastChunk: false,
  1546. separateAnnots: null
  1547. };
  1548. this._stats?.time("Page Request");
  1549. this._pumpOperatorList(intentArgs);
  1550. }
  1551. return intentState.opListReadCapability.promise;
  1552. }
  1553. streamTextContent({
  1554. disableCombineTextItems = false,
  1555. includeMarkedContent = false
  1556. } = {}) {
  1557. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1558. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1559. pageIndex: this._pageIndex,
  1560. combineTextItems: disableCombineTextItems !== true,
  1561. includeMarkedContent: includeMarkedContent === true
  1562. }, {
  1563. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1564. size(textContent) {
  1565. return textContent.items.length;
  1566. }
  1567. });
  1568. }
  1569. getTextContent(params = {}) {
  1570. if (this._transport._htmlForXfa) {
  1571. return this.getXfa().then(xfa => {
  1572. return _xfa_text.XfaText.textContent(xfa);
  1573. });
  1574. }
  1575. const readableStream = this.streamTextContent(params);
  1576. return new Promise(function (resolve, reject) {
  1577. function pump() {
  1578. reader.read().then(function ({
  1579. value,
  1580. done
  1581. }) {
  1582. if (done) {
  1583. resolve(textContent);
  1584. return;
  1585. }
  1586. Object.assign(textContent.styles, value.styles);
  1587. textContent.items.push(...value.items);
  1588. pump();
  1589. }, reject);
  1590. }
  1591. const reader = readableStream.getReader();
  1592. const textContent = {
  1593. items: [],
  1594. styles: Object.create(null)
  1595. };
  1596. pump();
  1597. });
  1598. }
  1599. getStructTree() {
  1600. return this._transport.getStructTree(this._pageIndex);
  1601. }
  1602. _destroy() {
  1603. this.destroyed = true;
  1604. const waitOn = [];
  1605. for (const intentState of this._intentStates.values()) {
  1606. this._abortOperatorList({
  1607. intentState,
  1608. reason: new Error("Page was destroyed."),
  1609. force: true
  1610. });
  1611. if (intentState.opListReadCapability) {
  1612. continue;
  1613. }
  1614. for (const internalRenderTask of intentState.renderTasks) {
  1615. waitOn.push(internalRenderTask.completed);
  1616. internalRenderTask.cancel();
  1617. }
  1618. }
  1619. this.objs.clear();
  1620. for (const bitmap of this._bitmaps) {
  1621. bitmap.close();
  1622. }
  1623. this._bitmaps.clear();
  1624. this.pendingCleanup = false;
  1625. return Promise.all(waitOn);
  1626. }
  1627. cleanup(resetStats = false) {
  1628. this.pendingCleanup = true;
  1629. return this._tryCleanup(resetStats);
  1630. }
  1631. _tryCleanup(resetStats = false) {
  1632. if (!this.pendingCleanup) {
  1633. return false;
  1634. }
  1635. for (const {
  1636. renderTasks,
  1637. operatorList
  1638. } of this._intentStates.values()) {
  1639. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  1640. return false;
  1641. }
  1642. }
  1643. this._intentStates.clear();
  1644. this.objs.clear();
  1645. if (resetStats && this._stats) {
  1646. this._stats = new _display_utils.StatTimer();
  1647. }
  1648. for (const bitmap of this._bitmaps) {
  1649. bitmap.close();
  1650. }
  1651. this._bitmaps.clear();
  1652. this.pendingCleanup = false;
  1653. return true;
  1654. }
  1655. _startRenderPage(transparency, cacheKey) {
  1656. const intentState = this._intentStates.get(cacheKey);
  1657. if (!intentState) {
  1658. return;
  1659. }
  1660. this._stats?.timeEnd("Page Request");
  1661. intentState.displayReadyCapability?.resolve(transparency);
  1662. }
  1663. _renderPageChunk(operatorListChunk, intentState) {
  1664. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  1665. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  1666. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  1667. }
  1668. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  1669. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  1670. for (const internalRenderTask of intentState.renderTasks) {
  1671. internalRenderTask.operatorListChanged();
  1672. }
  1673. if (operatorListChunk.lastChunk) {
  1674. this._tryCleanup();
  1675. }
  1676. }
  1677. _pumpOperatorList({
  1678. renderingIntent,
  1679. cacheKey,
  1680. annotationStorageMap
  1681. }) {
  1682. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  1683. pageIndex: this._pageIndex,
  1684. intent: renderingIntent,
  1685. cacheKey,
  1686. annotationStorage: annotationStorageMap
  1687. });
  1688. const reader = readableStream.getReader();
  1689. const intentState = this._intentStates.get(cacheKey);
  1690. intentState.streamReader = reader;
  1691. const pump = () => {
  1692. reader.read().then(({
  1693. value,
  1694. done
  1695. }) => {
  1696. if (done) {
  1697. intentState.streamReader = null;
  1698. return;
  1699. }
  1700. if (this._transport.destroyed) {
  1701. return;
  1702. }
  1703. this._renderPageChunk(value, intentState);
  1704. pump();
  1705. }, reason => {
  1706. intentState.streamReader = null;
  1707. if (this._transport.destroyed) {
  1708. return;
  1709. }
  1710. if (intentState.operatorList) {
  1711. intentState.operatorList.lastChunk = true;
  1712. for (const internalRenderTask of intentState.renderTasks) {
  1713. internalRenderTask.operatorListChanged();
  1714. }
  1715. this._tryCleanup();
  1716. }
  1717. if (intentState.displayReadyCapability) {
  1718. intentState.displayReadyCapability.reject(reason);
  1719. } else if (intentState.opListReadCapability) {
  1720. intentState.opListReadCapability.reject(reason);
  1721. } else {
  1722. throw reason;
  1723. }
  1724. });
  1725. };
  1726. pump();
  1727. }
  1728. _abortOperatorList({
  1729. intentState,
  1730. reason,
  1731. force = false
  1732. }) {
  1733. if (!intentState.streamReader) {
  1734. return;
  1735. }
  1736. if (intentState.streamReaderCancelTimeout) {
  1737. clearTimeout(intentState.streamReaderCancelTimeout);
  1738. intentState.streamReaderCancelTimeout = null;
  1739. }
  1740. if (!force) {
  1741. if (intentState.renderTasks.size > 0) {
  1742. return;
  1743. }
  1744. if (reason instanceof _display_utils.RenderingCancelledException) {
  1745. let delay = RENDERING_CANCELLED_TIMEOUT;
  1746. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  1747. delay += reason.extraDelay;
  1748. }
  1749. intentState.streamReaderCancelTimeout = setTimeout(() => {
  1750. intentState.streamReaderCancelTimeout = null;
  1751. this._abortOperatorList({
  1752. intentState,
  1753. reason,
  1754. force: true
  1755. });
  1756. }, delay);
  1757. return;
  1758. }
  1759. }
  1760. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  1761. intentState.streamReader = null;
  1762. if (this._transport.destroyed) {
  1763. return;
  1764. }
  1765. for (const [curCacheKey, curIntentState] of this._intentStates) {
  1766. if (curIntentState === intentState) {
  1767. this._intentStates.delete(curCacheKey);
  1768. break;
  1769. }
  1770. }
  1771. this.cleanup();
  1772. }
  1773. get stats() {
  1774. return this._stats;
  1775. }
  1776. }
  1777. exports.PDFPageProxy = PDFPageProxy;
  1778. class LoopbackPort {
  1779. #listeners = [];
  1780. #deferred = Promise.resolve();
  1781. postMessage(obj, transfers) {
  1782. const event = {
  1783. data: structuredClone(obj, transfers)
  1784. };
  1785. this.#deferred.then(() => {
  1786. for (const listener of this.#listeners) {
  1787. listener.call(this, event);
  1788. }
  1789. });
  1790. }
  1791. addEventListener(name, listener) {
  1792. this.#listeners.push(listener);
  1793. }
  1794. removeEventListener(name, listener) {
  1795. const i = this.#listeners.indexOf(listener);
  1796. this.#listeners.splice(i, 1);
  1797. }
  1798. terminate() {
  1799. this.#listeners.length = 0;
  1800. }
  1801. }
  1802. exports.LoopbackPort = LoopbackPort;
  1803. const PDFWorkerUtil = {
  1804. isWorkerDisabled: false,
  1805. fallbackWorkerSrc: null,
  1806. fakeWorkerId: 0
  1807. };
  1808. exports.PDFWorkerUtil = PDFWorkerUtil;
  1809. {
  1810. if (_is_node.isNodeJS && typeof require === "function") {
  1811. PDFWorkerUtil.isWorkerDisabled = true;
  1812. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  1813. } else if (typeof document === "object") {
  1814. const pdfjsFilePath = document?.currentScript?.src;
  1815. if (pdfjsFilePath) {
  1816. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  1817. }
  1818. }
  1819. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  1820. let base;
  1821. try {
  1822. base = new URL(baseUrl);
  1823. if (!base.origin || base.origin === "null") {
  1824. return false;
  1825. }
  1826. } catch (e) {
  1827. return false;
  1828. }
  1829. const other = new URL(otherUrl, base);
  1830. return base.origin === other.origin;
  1831. };
  1832. PDFWorkerUtil.createCDNWrapper = function (url) {
  1833. const wrapper = `importScripts("${url}");`;
  1834. return URL.createObjectURL(new Blob([wrapper]));
  1835. };
  1836. }
  1837. class PDFWorker {
  1838. static #workerPorts = new WeakMap();
  1839. constructor({
  1840. name = null,
  1841. port = null,
  1842. verbosity = (0, _util.getVerbosityLevel)()
  1843. } = {}) {
  1844. if (port && PDFWorker.#workerPorts.has(port)) {
  1845. throw new Error("Cannot use more than one PDFWorker per port.");
  1846. }
  1847. this.name = name;
  1848. this.destroyed = false;
  1849. this.verbosity = verbosity;
  1850. this._readyCapability = (0, _util.createPromiseCapability)();
  1851. this._port = null;
  1852. this._webWorker = null;
  1853. this._messageHandler = null;
  1854. if (port) {
  1855. PDFWorker.#workerPorts.set(port, this);
  1856. this._initializeFromPort(port);
  1857. return;
  1858. }
  1859. this._initialize();
  1860. }
  1861. get promise() {
  1862. return this._readyCapability.promise;
  1863. }
  1864. get port() {
  1865. return this._port;
  1866. }
  1867. get messageHandler() {
  1868. return this._messageHandler;
  1869. }
  1870. _initializeFromPort(port) {
  1871. this._port = port;
  1872. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  1873. this._messageHandler.on("ready", function () {});
  1874. this._readyCapability.resolve();
  1875. this._messageHandler.send("configure", {
  1876. verbosity: this.verbosity
  1877. });
  1878. }
  1879. _initialize() {
  1880. if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  1881. let {
  1882. workerSrc
  1883. } = PDFWorker;
  1884. try {
  1885. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  1886. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  1887. }
  1888. const worker = new Worker(workerSrc);
  1889. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  1890. const terminateEarly = () => {
  1891. worker.removeEventListener("error", onWorkerError);
  1892. messageHandler.destroy();
  1893. worker.terminate();
  1894. if (this.destroyed) {
  1895. this._readyCapability.reject(new Error("Worker was destroyed"));
  1896. } else {
  1897. this._setupFakeWorker();
  1898. }
  1899. };
  1900. const onWorkerError = () => {
  1901. if (!this._webWorker) {
  1902. terminateEarly();
  1903. }
  1904. };
  1905. worker.addEventListener("error", onWorkerError);
  1906. messageHandler.on("test", data => {
  1907. worker.removeEventListener("error", onWorkerError);
  1908. if (this.destroyed) {
  1909. terminateEarly();
  1910. return;
  1911. }
  1912. if (data) {
  1913. this._messageHandler = messageHandler;
  1914. this._port = worker;
  1915. this._webWorker = worker;
  1916. this._readyCapability.resolve();
  1917. messageHandler.send("configure", {
  1918. verbosity: this.verbosity
  1919. });
  1920. } else {
  1921. this._setupFakeWorker();
  1922. messageHandler.destroy();
  1923. worker.terminate();
  1924. }
  1925. });
  1926. messageHandler.on("ready", data => {
  1927. worker.removeEventListener("error", onWorkerError);
  1928. if (this.destroyed) {
  1929. terminateEarly();
  1930. return;
  1931. }
  1932. try {
  1933. sendTest();
  1934. } catch (e) {
  1935. this._setupFakeWorker();
  1936. }
  1937. });
  1938. const sendTest = () => {
  1939. const testObj = new Uint8Array();
  1940. messageHandler.send("test", testObj, [testObj.buffer]);
  1941. };
  1942. sendTest();
  1943. return;
  1944. } catch (e) {
  1945. (0, _util.info)("The worker has been disabled.");
  1946. }
  1947. }
  1948. this._setupFakeWorker();
  1949. }
  1950. _setupFakeWorker() {
  1951. if (!PDFWorkerUtil.isWorkerDisabled) {
  1952. (0, _util.warn)("Setting up fake worker.");
  1953. PDFWorkerUtil.isWorkerDisabled = true;
  1954. }
  1955. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  1956. if (this.destroyed) {
  1957. this._readyCapability.reject(new Error("Worker was destroyed"));
  1958. return;
  1959. }
  1960. const port = new LoopbackPort();
  1961. this._port = port;
  1962. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  1963. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  1964. WorkerMessageHandler.setup(workerHandler, port);
  1965. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  1966. this._messageHandler = messageHandler;
  1967. this._readyCapability.resolve();
  1968. messageHandler.send("configure", {
  1969. verbosity: this.verbosity
  1970. });
  1971. }).catch(reason => {
  1972. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  1973. });
  1974. }
  1975. destroy() {
  1976. this.destroyed = true;
  1977. if (this._webWorker) {
  1978. this._webWorker.terminate();
  1979. this._webWorker = null;
  1980. }
  1981. PDFWorker.#workerPorts.delete(this._port);
  1982. this._port = null;
  1983. if (this._messageHandler) {
  1984. this._messageHandler.destroy();
  1985. this._messageHandler = null;
  1986. }
  1987. }
  1988. static fromPort(params) {
  1989. if (!params?.port) {
  1990. throw new Error("PDFWorker.fromPort - invalid method signature.");
  1991. }
  1992. if (this.#workerPorts.has(params.port)) {
  1993. return this.#workerPorts.get(params.port);
  1994. }
  1995. return new PDFWorker(params);
  1996. }
  1997. static get workerSrc() {
  1998. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  1999. return _worker_options.GlobalWorkerOptions.workerSrc;
  2000. }
  2001. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  2002. if (!_is_node.isNodeJS) {
  2003. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  2004. }
  2005. return PDFWorkerUtil.fallbackWorkerSrc;
  2006. }
  2007. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  2008. }
  2009. static get _mainThreadWorkerMessageHandler() {
  2010. try {
  2011. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  2012. } catch (ex) {
  2013. return null;
  2014. }
  2015. }
  2016. static get _setupFakeWorkerGlobal() {
  2017. const loader = async () => {
  2018. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  2019. if (mainWorkerMessageHandler) {
  2020. return mainWorkerMessageHandler;
  2021. }
  2022. if (_is_node.isNodeJS && typeof require === "function") {
  2023. const worker = eval("require")(this.workerSrc);
  2024. return worker.WorkerMessageHandler;
  2025. }
  2026. await (0, _display_utils.loadScript)(this.workerSrc);
  2027. return window.pdfjsWorker.WorkerMessageHandler;
  2028. };
  2029. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  2030. }
  2031. }
  2032. exports.PDFWorker = PDFWorker;
  2033. class WorkerTransport {
  2034. #docStats = null;
  2035. #pageCache = new Map();
  2036. #pagePromises = new Map();
  2037. #metadataPromise = null;
  2038. constructor(messageHandler, loadingTask, networkStream, params) {
  2039. this.messageHandler = messageHandler;
  2040. this.loadingTask = loadingTask;
  2041. this.commonObjs = new PDFObjects();
  2042. this.fontLoader = new _font_loader.FontLoader({
  2043. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2044. ownerDocument: params.ownerDocument,
  2045. styleElement: params.styleElement
  2046. });
  2047. this._params = params;
  2048. if (!params.useWorkerFetch) {
  2049. this.CMapReaderFactory = new params.CMapReaderFactory({
  2050. baseUrl: params.cMapUrl,
  2051. isCompressed: params.cMapPacked
  2052. });
  2053. this.StandardFontDataFactory = new params.StandardFontDataFactory({
  2054. baseUrl: params.standardFontDataUrl
  2055. });
  2056. }
  2057. this.destroyed = false;
  2058. this.destroyCapability = null;
  2059. this._passwordCapability = null;
  2060. this._networkStream = networkStream;
  2061. this._fullReader = null;
  2062. this._lastProgress = null;
  2063. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  2064. this.setupMessageHandler();
  2065. }
  2066. get annotationStorage() {
  2067. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  2068. }
  2069. get stats() {
  2070. return this.#docStats;
  2071. }
  2072. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  2073. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  2074. let annotationMap = null;
  2075. switch (intent) {
  2076. case "any":
  2077. renderingIntent = _util.RenderingIntentFlag.ANY;
  2078. break;
  2079. case "display":
  2080. break;
  2081. case "print":
  2082. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2083. break;
  2084. default:
  2085. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2086. }
  2087. switch (annotationMode) {
  2088. case _util.AnnotationMode.DISABLE:
  2089. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2090. break;
  2091. case _util.AnnotationMode.ENABLE:
  2092. break;
  2093. case _util.AnnotationMode.ENABLE_FORMS:
  2094. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2095. break;
  2096. case _util.AnnotationMode.ENABLE_STORAGE:
  2097. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2098. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2099. annotationMap = annotationStorage.serializable;
  2100. break;
  2101. default:
  2102. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2103. }
  2104. if (isOpList) {
  2105. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2106. }
  2107. return {
  2108. renderingIntent,
  2109. cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
  2110. annotationStorageMap: annotationMap
  2111. };
  2112. }
  2113. destroy() {
  2114. if (this.destroyCapability) {
  2115. return this.destroyCapability.promise;
  2116. }
  2117. this.destroyed = true;
  2118. this.destroyCapability = (0, _util.createPromiseCapability)();
  2119. if (this._passwordCapability) {
  2120. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2121. }
  2122. const waitOn = [];
  2123. for (const page of this.#pageCache.values()) {
  2124. waitOn.push(page._destroy());
  2125. }
  2126. this.#pageCache.clear();
  2127. this.#pagePromises.clear();
  2128. if (this.hasOwnProperty("annotationStorage")) {
  2129. this.annotationStorage.resetModified();
  2130. }
  2131. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2132. waitOn.push(terminated);
  2133. Promise.all(waitOn).then(() => {
  2134. this.commonObjs.clear();
  2135. this.fontLoader.clear();
  2136. this.#metadataPromise = null;
  2137. this._getFieldObjectsPromise = null;
  2138. this._hasJSActionsPromise = null;
  2139. if (this._networkStream) {
  2140. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2141. }
  2142. if (this.messageHandler) {
  2143. this.messageHandler.destroy();
  2144. this.messageHandler = null;
  2145. }
  2146. this.destroyCapability.resolve();
  2147. }, this.destroyCapability.reject);
  2148. return this.destroyCapability.promise;
  2149. }
  2150. setupMessageHandler() {
  2151. const {
  2152. messageHandler,
  2153. loadingTask
  2154. } = this;
  2155. messageHandler.on("GetReader", (data, sink) => {
  2156. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2157. this._fullReader = this._networkStream.getFullReader();
  2158. this._fullReader.onProgress = evt => {
  2159. this._lastProgress = {
  2160. loaded: evt.loaded,
  2161. total: evt.total
  2162. };
  2163. };
  2164. sink.onPull = () => {
  2165. this._fullReader.read().then(function ({
  2166. value,
  2167. done
  2168. }) {
  2169. if (done) {
  2170. sink.close();
  2171. return;
  2172. }
  2173. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
  2174. sink.enqueue(new Uint8Array(value), 1, [value]);
  2175. }).catch(reason => {
  2176. sink.error(reason);
  2177. });
  2178. };
  2179. sink.onCancel = reason => {
  2180. this._fullReader.cancel(reason);
  2181. sink.ready.catch(readyReason => {
  2182. if (this.destroyed) {
  2183. return;
  2184. }
  2185. throw readyReason;
  2186. });
  2187. };
  2188. });
  2189. messageHandler.on("ReaderHeadersReady", data => {
  2190. const headersCapability = (0, _util.createPromiseCapability)();
  2191. const fullReader = this._fullReader;
  2192. fullReader.headersReady.then(() => {
  2193. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2194. if (this._lastProgress) {
  2195. loadingTask.onProgress?.(this._lastProgress);
  2196. }
  2197. fullReader.onProgress = evt => {
  2198. loadingTask.onProgress?.({
  2199. loaded: evt.loaded,
  2200. total: evt.total
  2201. });
  2202. };
  2203. }
  2204. headersCapability.resolve({
  2205. isStreamingSupported: fullReader.isStreamingSupported,
  2206. isRangeSupported: fullReader.isRangeSupported,
  2207. contentLength: fullReader.contentLength
  2208. });
  2209. }, headersCapability.reject);
  2210. return headersCapability.promise;
  2211. });
  2212. messageHandler.on("GetRangeReader", (data, sink) => {
  2213. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2214. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2215. if (!rangeReader) {
  2216. sink.close();
  2217. return;
  2218. }
  2219. sink.onPull = () => {
  2220. rangeReader.read().then(function ({
  2221. value,
  2222. done
  2223. }) {
  2224. if (done) {
  2225. sink.close();
  2226. return;
  2227. }
  2228. (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
  2229. sink.enqueue(new Uint8Array(value), 1, [value]);
  2230. }).catch(reason => {
  2231. sink.error(reason);
  2232. });
  2233. };
  2234. sink.onCancel = reason => {
  2235. rangeReader.cancel(reason);
  2236. sink.ready.catch(readyReason => {
  2237. if (this.destroyed) {
  2238. return;
  2239. }
  2240. throw readyReason;
  2241. });
  2242. };
  2243. });
  2244. messageHandler.on("GetDoc", ({
  2245. pdfInfo
  2246. }) => {
  2247. this._numPages = pdfInfo.numPages;
  2248. this._htmlForXfa = pdfInfo.htmlForXfa;
  2249. delete pdfInfo.htmlForXfa;
  2250. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2251. });
  2252. messageHandler.on("DocException", function (ex) {
  2253. let reason;
  2254. switch (ex.name) {
  2255. case "PasswordException":
  2256. reason = new _util.PasswordException(ex.message, ex.code);
  2257. break;
  2258. case "InvalidPDFException":
  2259. reason = new _util.InvalidPDFException(ex.message);
  2260. break;
  2261. case "MissingPDFException":
  2262. reason = new _util.MissingPDFException(ex.message);
  2263. break;
  2264. case "UnexpectedResponseException":
  2265. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2266. break;
  2267. case "UnknownErrorException":
  2268. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2269. break;
  2270. default:
  2271. (0, _util.unreachable)("DocException - expected a valid Error.");
  2272. }
  2273. loadingTask._capability.reject(reason);
  2274. });
  2275. messageHandler.on("PasswordRequest", exception => {
  2276. this._passwordCapability = (0, _util.createPromiseCapability)();
  2277. if (loadingTask.onPassword) {
  2278. const updatePassword = password => {
  2279. if (password instanceof Error) {
  2280. this._passwordCapability.reject(password);
  2281. } else {
  2282. this._passwordCapability.resolve({
  2283. password
  2284. });
  2285. }
  2286. };
  2287. try {
  2288. loadingTask.onPassword(updatePassword, exception.code);
  2289. } catch (ex) {
  2290. this._passwordCapability.reject(ex);
  2291. }
  2292. } else {
  2293. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2294. }
  2295. return this._passwordCapability.promise;
  2296. });
  2297. messageHandler.on("DataLoaded", data => {
  2298. loadingTask.onProgress?.({
  2299. loaded: data.length,
  2300. total: data.length
  2301. });
  2302. this.downloadInfoCapability.resolve(data);
  2303. });
  2304. messageHandler.on("StartRenderPage", data => {
  2305. if (this.destroyed) {
  2306. return;
  2307. }
  2308. const page = this.#pageCache.get(data.pageIndex);
  2309. page._startRenderPage(data.transparency, data.cacheKey);
  2310. });
  2311. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2312. if (this.destroyed) {
  2313. return;
  2314. }
  2315. if (this.commonObjs.has(id)) {
  2316. return;
  2317. }
  2318. switch (type) {
  2319. case "Font":
  2320. const params = this._params;
  2321. if ("error" in exportedData) {
  2322. const exportedError = exportedData.error;
  2323. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2324. this.commonObjs.resolve(id, exportedError);
  2325. break;
  2326. }
  2327. let fontRegistry = null;
  2328. if (params.pdfBug && globalThis.FontInspector?.enabled) {
  2329. fontRegistry = {
  2330. registerFont(font, url) {
  2331. globalThis.FontInspector.fontAdded(font, url);
  2332. }
  2333. };
  2334. }
  2335. const font = new _font_loader.FontFaceObject(exportedData, {
  2336. isEvalSupported: params.isEvalSupported,
  2337. disableFontFace: params.disableFontFace,
  2338. ignoreErrors: params.ignoreErrors,
  2339. onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
  2340. fontRegistry
  2341. });
  2342. this.fontLoader.bind(font).catch(reason => {
  2343. return messageHandler.sendWithPromise("FontFallback", {
  2344. id
  2345. });
  2346. }).finally(() => {
  2347. if (!params.fontExtraProperties && font.data) {
  2348. font.data = null;
  2349. }
  2350. this.commonObjs.resolve(id, font);
  2351. });
  2352. break;
  2353. case "FontPath":
  2354. case "Image":
  2355. this.commonObjs.resolve(id, exportedData);
  2356. break;
  2357. default:
  2358. throw new Error(`Got unknown common object type ${type}`);
  2359. }
  2360. });
  2361. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  2362. if (this.destroyed) {
  2363. return;
  2364. }
  2365. const pageProxy = this.#pageCache.get(pageIndex);
  2366. if (pageProxy.objs.has(id)) {
  2367. return;
  2368. }
  2369. switch (type) {
  2370. case "Image":
  2371. pageProxy.objs.resolve(id, imageData);
  2372. const MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2373. if (imageData) {
  2374. let length;
  2375. if (imageData.bitmap) {
  2376. const {
  2377. bitmap,
  2378. width,
  2379. height
  2380. } = imageData;
  2381. length = width * height * 4;
  2382. pageProxy._bitmaps.add(bitmap);
  2383. } else {
  2384. length = imageData.data?.length || 0;
  2385. }
  2386. if (length > MAX_IMAGE_SIZE_TO_STORE) {
  2387. pageProxy.cleanupAfterRender = true;
  2388. }
  2389. }
  2390. break;
  2391. case "Pattern":
  2392. pageProxy.objs.resolve(id, imageData);
  2393. break;
  2394. default:
  2395. throw new Error(`Got unknown object type ${type}`);
  2396. }
  2397. });
  2398. messageHandler.on("DocProgress", data => {
  2399. if (this.destroyed) {
  2400. return;
  2401. }
  2402. loadingTask.onProgress?.({
  2403. loaded: data.loaded,
  2404. total: data.total
  2405. });
  2406. });
  2407. messageHandler.on("DocStats", data => {
  2408. if (this.destroyed) {
  2409. return;
  2410. }
  2411. this.#docStats = Object.freeze({
  2412. streamTypes: Object.freeze(data.streamTypes),
  2413. fontTypes: Object.freeze(data.fontTypes)
  2414. });
  2415. });
  2416. messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
  2417. messageHandler.on("FetchBuiltInCMap", data => {
  2418. if (this.destroyed) {
  2419. return Promise.reject(new Error("Worker was destroyed."));
  2420. }
  2421. if (!this.CMapReaderFactory) {
  2422. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2423. }
  2424. return this.CMapReaderFactory.fetch(data);
  2425. });
  2426. messageHandler.on("FetchStandardFontData", data => {
  2427. if (this.destroyed) {
  2428. return Promise.reject(new Error("Worker was destroyed."));
  2429. }
  2430. if (!this.StandardFontDataFactory) {
  2431. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2432. }
  2433. return this.StandardFontDataFactory.fetch(data);
  2434. });
  2435. }
  2436. _onUnsupportedFeature({
  2437. featureId
  2438. }) {
  2439. if (this.destroyed) {
  2440. return;
  2441. }
  2442. this.loadingTask.onUnsupportedFeature?.(featureId);
  2443. }
  2444. getData() {
  2445. return this.messageHandler.sendWithPromise("GetData", null);
  2446. }
  2447. saveDocument() {
  2448. if (this.annotationStorage.size <= 0) {
  2449. (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  2450. }
  2451. return this.messageHandler.sendWithPromise("SaveDocument", {
  2452. isPureXfa: !!this._htmlForXfa,
  2453. numPages: this._numPages,
  2454. annotationStorage: this.annotationStorage.serializable,
  2455. filename: this._fullReader?.filename ?? null
  2456. }).finally(() => {
  2457. this.annotationStorage.resetModified();
  2458. });
  2459. }
  2460. getPage(pageNumber) {
  2461. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2462. return Promise.reject(new Error("Invalid page request."));
  2463. }
  2464. const pageIndex = pageNumber - 1,
  2465. cachedPromise = this.#pagePromises.get(pageIndex);
  2466. if (cachedPromise) {
  2467. return cachedPromise;
  2468. }
  2469. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2470. pageIndex
  2471. }).then(pageInfo => {
  2472. if (this.destroyed) {
  2473. throw new Error("Transport destroyed");
  2474. }
  2475. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
  2476. this.#pageCache.set(pageIndex, page);
  2477. return page;
  2478. });
  2479. this.#pagePromises.set(pageIndex, promise);
  2480. return promise;
  2481. }
  2482. getPageIndex(ref) {
  2483. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  2484. return Promise.reject(new Error("Invalid pageIndex request."));
  2485. }
  2486. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2487. num: ref.num,
  2488. gen: ref.gen
  2489. });
  2490. }
  2491. getAnnotations(pageIndex, intent) {
  2492. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2493. pageIndex,
  2494. intent
  2495. });
  2496. }
  2497. getFieldObjects() {
  2498. return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
  2499. }
  2500. hasJSActions() {
  2501. return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
  2502. }
  2503. getCalculationOrderIds() {
  2504. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2505. }
  2506. getDestinations() {
  2507. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2508. }
  2509. getDestination(id) {
  2510. if (typeof id !== "string") {
  2511. return Promise.reject(new Error("Invalid destination request."));
  2512. }
  2513. return this.messageHandler.sendWithPromise("GetDestination", {
  2514. id
  2515. });
  2516. }
  2517. getPageLabels() {
  2518. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2519. }
  2520. getPageLayout() {
  2521. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2522. }
  2523. getPageMode() {
  2524. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2525. }
  2526. getViewerPreferences() {
  2527. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2528. }
  2529. getOpenAction() {
  2530. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2531. }
  2532. getAttachments() {
  2533. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2534. }
  2535. getJavaScript() {
  2536. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2537. }
  2538. getDocJSActions() {
  2539. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2540. }
  2541. getPageJSActions(pageIndex) {
  2542. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2543. pageIndex
  2544. });
  2545. }
  2546. getStructTree(pageIndex) {
  2547. return this.messageHandler.sendWithPromise("GetStructTree", {
  2548. pageIndex
  2549. });
  2550. }
  2551. getOutline() {
  2552. return this.messageHandler.sendWithPromise("GetOutline", null);
  2553. }
  2554. getOptionalContentConfig() {
  2555. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2556. return new _optional_content_config.OptionalContentConfig(results);
  2557. });
  2558. }
  2559. getPermissions() {
  2560. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2561. }
  2562. getMetadata() {
  2563. return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
  2564. return {
  2565. info: results[0],
  2566. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2567. contentDispositionFilename: this._fullReader?.filename ?? null,
  2568. contentLength: this._fullReader?.contentLength ?? null
  2569. };
  2570. });
  2571. }
  2572. getMarkInfo() {
  2573. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2574. }
  2575. async startCleanup(keepLoadedFonts = false) {
  2576. if (this.destroyed) {
  2577. return;
  2578. }
  2579. await this.messageHandler.sendWithPromise("Cleanup", null);
  2580. for (const page of this.#pageCache.values()) {
  2581. const cleanupSuccessful = page.cleanup();
  2582. if (!cleanupSuccessful) {
  2583. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  2584. }
  2585. }
  2586. this.commonObjs.clear();
  2587. if (!keepLoadedFonts) {
  2588. this.fontLoader.clear();
  2589. }
  2590. this.#metadataPromise = null;
  2591. this._getFieldObjectsPromise = null;
  2592. this._hasJSActionsPromise = null;
  2593. }
  2594. get loadingParams() {
  2595. const params = this._params;
  2596. return (0, _util.shadow)(this, "loadingParams", {
  2597. disableAutoFetch: params.disableAutoFetch,
  2598. enableXfa: params.enableXfa
  2599. });
  2600. }
  2601. }
  2602. class PDFObjects {
  2603. #objs = Object.create(null);
  2604. #ensureObj(objId) {
  2605. const obj = this.#objs[objId];
  2606. if (obj) {
  2607. return obj;
  2608. }
  2609. return this.#objs[objId] = {
  2610. capability: (0, _util.createPromiseCapability)(),
  2611. data: null
  2612. };
  2613. }
  2614. get(objId, callback = null) {
  2615. if (callback) {
  2616. const obj = this.#ensureObj(objId);
  2617. obj.capability.promise.then(() => callback(obj.data));
  2618. return null;
  2619. }
  2620. const obj = this.#objs[objId];
  2621. if (!obj?.capability.settled) {
  2622. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2623. }
  2624. return obj.data;
  2625. }
  2626. has(objId) {
  2627. const obj = this.#objs[objId];
  2628. return obj?.capability.settled || false;
  2629. }
  2630. resolve(objId, data = null) {
  2631. const obj = this.#ensureObj(objId);
  2632. obj.data = data;
  2633. obj.capability.resolve();
  2634. }
  2635. clear() {
  2636. this.#objs = Object.create(null);
  2637. }
  2638. }
  2639. class RenderTask {
  2640. #internalRenderTask = null;
  2641. constructor(internalRenderTask) {
  2642. this.#internalRenderTask = internalRenderTask;
  2643. this.onContinue = null;
  2644. }
  2645. get promise() {
  2646. return this.#internalRenderTask.capability.promise;
  2647. }
  2648. cancel(extraDelay = 0) {
  2649. this.#internalRenderTask.cancel(null, extraDelay);
  2650. }
  2651. get separateAnnots() {
  2652. const {
  2653. separateAnnots
  2654. } = this.#internalRenderTask.operatorList;
  2655. if (!separateAnnots) {
  2656. return false;
  2657. }
  2658. const {
  2659. annotationCanvasMap
  2660. } = this.#internalRenderTask;
  2661. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  2662. }
  2663. }
  2664. exports.RenderTask = RenderTask;
  2665. class InternalRenderTask {
  2666. static #canvasInUse = new WeakSet();
  2667. constructor({
  2668. callback,
  2669. params,
  2670. objs,
  2671. commonObjs,
  2672. annotationCanvasMap,
  2673. operatorList,
  2674. pageIndex,
  2675. canvasFactory,
  2676. useRequestAnimationFrame = false,
  2677. pdfBug = false,
  2678. pageColors = null
  2679. }) {
  2680. this.callback = callback;
  2681. this.params = params;
  2682. this.objs = objs;
  2683. this.commonObjs = commonObjs;
  2684. this.annotationCanvasMap = annotationCanvasMap;
  2685. this.operatorListIdx = null;
  2686. this.operatorList = operatorList;
  2687. this._pageIndex = pageIndex;
  2688. this.canvasFactory = canvasFactory;
  2689. this._pdfBug = pdfBug;
  2690. this.pageColors = pageColors;
  2691. this.running = false;
  2692. this.graphicsReadyCallback = null;
  2693. this.graphicsReady = false;
  2694. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  2695. this.cancelled = false;
  2696. this.capability = (0, _util.createPromiseCapability)();
  2697. this.task = new RenderTask(this);
  2698. this._cancelBound = this.cancel.bind(this);
  2699. this._continueBound = this._continue.bind(this);
  2700. this._scheduleNextBound = this._scheduleNext.bind(this);
  2701. this._nextBound = this._next.bind(this);
  2702. this._canvas = params.canvasContext.canvas;
  2703. }
  2704. get completed() {
  2705. return this.capability.promise.catch(function () {});
  2706. }
  2707. initializeGraphics({
  2708. transparency = false,
  2709. optionalContentConfig
  2710. }) {
  2711. if (this.cancelled) {
  2712. return;
  2713. }
  2714. if (this._canvas) {
  2715. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  2716. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  2717. }
  2718. InternalRenderTask.#canvasInUse.add(this._canvas);
  2719. }
  2720. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  2721. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  2722. this.stepper.init(this.operatorList);
  2723. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2724. }
  2725. const {
  2726. canvasContext,
  2727. viewport,
  2728. transform,
  2729. background
  2730. } = this.params;
  2731. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, {
  2732. optionalContentConfig
  2733. }, 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, extraDelay = 0) {
  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", extraDelay));
  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.2.141';
  2804. exports.version = version;
  2805. const build = '35ca6ab31';
  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. #modified = false;
  2819. #storage = new Map();
  2820. constructor() {
  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. _uiManager = null;
  2953. #zIndex = AnnotationEditor._zIndex++;
  2954. static _colorManager = new _tools.ColorManager();
  2955. static _zIndex = 1;
  2956. constructor(parameters) {
  2957. if (this.constructor === AnnotationEditor) {
  2958. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  2959. }
  2960. this.parent = parameters.parent;
  2961. this.id = parameters.id;
  2962. this.width = this.height = null;
  2963. this.pageIndex = parameters.parent.pageIndex;
  2964. this.name = parameters.name;
  2965. this.div = null;
  2966. this._uiManager = parameters.uiManager;
  2967. const {
  2968. rotation,
  2969. rawDims: {
  2970. pageWidth,
  2971. pageHeight,
  2972. pageX,
  2973. pageY
  2974. }
  2975. } = this.parent.viewport;
  2976. this.rotation = rotation;
  2977. this.pageDimensions = [pageWidth, pageHeight];
  2978. this.pageTranslation = [pageX, pageY];
  2979. const [width, height] = this.parentDimensions;
  2980. this.x = parameters.x / width;
  2981. this.y = parameters.y / height;
  2982. this.isAttachedToDOM = false;
  2983. }
  2984. static get _defaultLineColor() {
  2985. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  2986. }
  2987. addCommands(params) {
  2988. this._uiManager.addCommands(params);
  2989. }
  2990. get currentLayer() {
  2991. return this._uiManager.currentLayer;
  2992. }
  2993. setInBackground() {
  2994. this.div.style.zIndex = 0;
  2995. }
  2996. setInForeground() {
  2997. this.div.style.zIndex = this.#zIndex;
  2998. }
  2999. setParent(parent) {
  3000. if (parent !== null) {
  3001. this.pageIndex = parent.pageIndex;
  3002. this.pageDimensions = parent.pageDimensions;
  3003. }
  3004. this.parent = parent;
  3005. }
  3006. focusin(event) {
  3007. if (!this.#hasBeenSelected) {
  3008. this.parent.setSelected(this);
  3009. } else {
  3010. this.#hasBeenSelected = false;
  3011. }
  3012. }
  3013. focusout(event) {
  3014. if (!this.isAttachedToDOM) {
  3015. return;
  3016. }
  3017. const target = event.relatedTarget;
  3018. if (target?.closest(`#${this.id}`)) {
  3019. return;
  3020. }
  3021. event.preventDefault();
  3022. if (!this.parent?.isMultipleSelection) {
  3023. this.commitOrRemove();
  3024. }
  3025. }
  3026. commitOrRemove() {
  3027. if (this.isEmpty()) {
  3028. this.remove();
  3029. } else {
  3030. this.commit();
  3031. }
  3032. }
  3033. commit() {
  3034. this.addToAnnotationStorage();
  3035. }
  3036. addToAnnotationStorage() {
  3037. this._uiManager.addToAnnotationStorage(this);
  3038. }
  3039. dragstart(event) {
  3040. const rect = this.parent.div.getBoundingClientRect();
  3041. this.startX = event.clientX - rect.x;
  3042. this.startY = event.clientY - rect.y;
  3043. event.dataTransfer.setData("text/plain", this.id);
  3044. event.dataTransfer.effectAllowed = "move";
  3045. }
  3046. setAt(x, y, tx, ty) {
  3047. const [width, height] = this.parentDimensions;
  3048. [tx, ty] = this.screenToPageTranslation(tx, ty);
  3049. this.x = (x + tx) / width;
  3050. this.y = (y + ty) / height;
  3051. this.div.style.left = `${100 * this.x}%`;
  3052. this.div.style.top = `${100 * this.y}%`;
  3053. }
  3054. translate(x, y) {
  3055. const [width, height] = this.parentDimensions;
  3056. [x, y] = this.screenToPageTranslation(x, y);
  3057. this.x += x / width;
  3058. this.y += y / height;
  3059. this.div.style.left = `${100 * this.x}%`;
  3060. this.div.style.top = `${100 * this.y}%`;
  3061. }
  3062. screenToPageTranslation(x, y) {
  3063. switch (this.parentRotation) {
  3064. case 90:
  3065. return [y, -x];
  3066. case 180:
  3067. return [-x, -y];
  3068. case 270:
  3069. return [-y, x];
  3070. default:
  3071. return [x, y];
  3072. }
  3073. }
  3074. get parentScale() {
  3075. return this._uiManager.viewParameters.realScale;
  3076. }
  3077. get parentRotation() {
  3078. return this._uiManager.viewParameters.rotation;
  3079. }
  3080. get parentDimensions() {
  3081. const {
  3082. realScale
  3083. } = this._uiManager.viewParameters;
  3084. const [pageWidth, pageHeight] = this.pageDimensions;
  3085. return [pageWidth * realScale, pageHeight * realScale];
  3086. }
  3087. setDims(width, height) {
  3088. const [parentWidth, parentHeight] = this.parentDimensions;
  3089. this.div.style.width = `${100 * width / parentWidth}%`;
  3090. this.div.style.height = `${100 * height / parentHeight}%`;
  3091. }
  3092. fixDims() {
  3093. const {
  3094. style
  3095. } = this.div;
  3096. const {
  3097. height,
  3098. width
  3099. } = style;
  3100. const widthPercent = width.endsWith("%");
  3101. const heightPercent = height.endsWith("%");
  3102. if (widthPercent && heightPercent) {
  3103. return;
  3104. }
  3105. const [parentWidth, parentHeight] = this.parentDimensions;
  3106. if (!widthPercent) {
  3107. style.width = `${100 * parseFloat(width) / parentWidth}%`;
  3108. }
  3109. if (!heightPercent) {
  3110. style.height = `${100 * parseFloat(height) / parentHeight}%`;
  3111. }
  3112. }
  3113. getInitialTranslation() {
  3114. return [0, 0];
  3115. }
  3116. render() {
  3117. this.div = document.createElement("div");
  3118. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3119. this.div.className = this.name;
  3120. this.div.setAttribute("id", this.id);
  3121. this.div.setAttribute("tabIndex", 0);
  3122. this.setInForeground();
  3123. this.div.addEventListener("focusin", this.#boundFocusin);
  3124. this.div.addEventListener("focusout", this.#boundFocusout);
  3125. const [tx, ty] = this.getInitialTranslation();
  3126. this.translate(tx, ty);
  3127. (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
  3128. return this.div;
  3129. }
  3130. pointerdown(event) {
  3131. const {
  3132. isMac
  3133. } = _util.FeatureTest.platform;
  3134. if (event.button !== 0 || event.ctrlKey && isMac) {
  3135. event.preventDefault();
  3136. return;
  3137. }
  3138. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3139. this.parent.toggleSelected(this);
  3140. } else {
  3141. this.parent.setSelected(this);
  3142. }
  3143. this.#hasBeenSelected = true;
  3144. }
  3145. getRect(tx, ty) {
  3146. const scale = this.parentScale;
  3147. const [pageWidth, pageHeight] = this.pageDimensions;
  3148. const [pageX, pageY] = this.pageTranslation;
  3149. const shiftX = tx / scale;
  3150. const shiftY = ty / scale;
  3151. const x = this.x * pageWidth;
  3152. const y = this.y * pageHeight;
  3153. const width = this.width * pageWidth;
  3154. const height = this.height * pageHeight;
  3155. switch (this.rotation) {
  3156. case 0:
  3157. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  3158. case 90:
  3159. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  3160. case 180:
  3161. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  3162. case 270:
  3163. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  3164. default:
  3165. throw new Error("Invalid rotation");
  3166. }
  3167. }
  3168. getRectInCurrentCoords(rect, pageHeight) {
  3169. const [x1, y1, x2, y2] = rect;
  3170. const width = x2 - x1;
  3171. const height = y2 - y1;
  3172. switch (this.rotation) {
  3173. case 0:
  3174. return [x1, pageHeight - y2, width, height];
  3175. case 90:
  3176. return [x1, pageHeight - y1, height, width];
  3177. case 180:
  3178. return [x2, pageHeight - y1, width, height];
  3179. case 270:
  3180. return [x2, pageHeight - y2, height, width];
  3181. default:
  3182. throw new Error("Invalid rotation");
  3183. }
  3184. }
  3185. onceAdded() {}
  3186. isEmpty() {
  3187. return false;
  3188. }
  3189. enableEditMode() {
  3190. this.#isInEditMode = true;
  3191. }
  3192. disableEditMode() {
  3193. this.#isInEditMode = false;
  3194. }
  3195. isInEditMode() {
  3196. return this.#isInEditMode;
  3197. }
  3198. shouldGetKeyboardEvents() {
  3199. return false;
  3200. }
  3201. needsToBeRebuilt() {
  3202. return this.div && !this.isAttachedToDOM;
  3203. }
  3204. rebuild() {
  3205. this.div?.addEventListener("focusin", this.#boundFocusin);
  3206. }
  3207. serialize() {
  3208. (0, _util.unreachable)("An editor must be serializable");
  3209. }
  3210. static deserialize(data, parent, uiManager) {
  3211. const editor = new this.prototype.constructor({
  3212. parent,
  3213. id: parent.getNextId(),
  3214. uiManager
  3215. });
  3216. editor.rotation = data.rotation;
  3217. const [pageWidth, pageHeight] = editor.pageDimensions;
  3218. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3219. editor.x = x / pageWidth;
  3220. editor.y = y / pageHeight;
  3221. editor.width = width / pageWidth;
  3222. editor.height = height / pageHeight;
  3223. return editor;
  3224. }
  3225. remove() {
  3226. this.div.removeEventListener("focusin", this.#boundFocusin);
  3227. this.div.removeEventListener("focusout", this.#boundFocusout);
  3228. if (!this.isEmpty()) {
  3229. this.commit();
  3230. }
  3231. this.parent.remove(this);
  3232. }
  3233. select() {
  3234. this.div?.classList.add("selectedEditor");
  3235. }
  3236. unselect() {
  3237. this.div?.classList.remove("selectedEditor");
  3238. }
  3239. updateParams(type, value) {}
  3240. disableEditing() {}
  3241. enableEditing() {}
  3242. get propertiesToUpdate() {
  3243. return {};
  3244. }
  3245. get contentDiv() {
  3246. return this.div;
  3247. }
  3248. get isEditing() {
  3249. return this.#isEditing;
  3250. }
  3251. set isEditing(value) {
  3252. this.#isEditing = value;
  3253. if (value) {
  3254. this.parent.setSelected(this);
  3255. this.parent.setActiveEditor(this);
  3256. } else {
  3257. this.parent.setActiveEditor(null);
  3258. }
  3259. }
  3260. }
  3261. exports.AnnotationEditor = AnnotationEditor;
  3262. /***/ }),
  3263. /* 5 */
  3264. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3265. Object.defineProperty(exports, "__esModule", ({
  3266. value: true
  3267. }));
  3268. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3269. exports.bindEvents = bindEvents;
  3270. exports.opacityToHex = opacityToHex;
  3271. var _util = __w_pdfjs_require__(1);
  3272. var _display_utils = __w_pdfjs_require__(6);
  3273. function bindEvents(obj, element, names) {
  3274. for (const name of names) {
  3275. element.addEventListener(name, obj[name].bind(obj));
  3276. }
  3277. }
  3278. function opacityToHex(opacity) {
  3279. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3280. }
  3281. class IdManager {
  3282. #id = 0;
  3283. getId() {
  3284. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3285. }
  3286. }
  3287. class CommandManager {
  3288. #commands = [];
  3289. #locked = false;
  3290. #maxSize;
  3291. #position = -1;
  3292. constructor(maxSize = 128) {
  3293. this.#maxSize = maxSize;
  3294. }
  3295. add({
  3296. cmd,
  3297. undo,
  3298. mustExec,
  3299. type = NaN,
  3300. overwriteIfSameType = false,
  3301. keepUndo = false
  3302. }) {
  3303. if (mustExec) {
  3304. cmd();
  3305. }
  3306. if (this.#locked) {
  3307. return;
  3308. }
  3309. const save = {
  3310. cmd,
  3311. undo,
  3312. type
  3313. };
  3314. if (this.#position === -1) {
  3315. if (this.#commands.length > 0) {
  3316. this.#commands.length = 0;
  3317. }
  3318. this.#position = 0;
  3319. this.#commands.push(save);
  3320. return;
  3321. }
  3322. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3323. if (keepUndo) {
  3324. save.undo = this.#commands[this.#position].undo;
  3325. }
  3326. this.#commands[this.#position] = save;
  3327. return;
  3328. }
  3329. const next = this.#position + 1;
  3330. if (next === this.#maxSize) {
  3331. this.#commands.splice(0, 1);
  3332. } else {
  3333. this.#position = next;
  3334. if (next < this.#commands.length) {
  3335. this.#commands.splice(next);
  3336. }
  3337. }
  3338. this.#commands.push(save);
  3339. }
  3340. undo() {
  3341. if (this.#position === -1) {
  3342. return;
  3343. }
  3344. this.#locked = true;
  3345. this.#commands[this.#position].undo();
  3346. this.#locked = false;
  3347. this.#position -= 1;
  3348. }
  3349. redo() {
  3350. if (this.#position < this.#commands.length - 1) {
  3351. this.#position += 1;
  3352. this.#locked = true;
  3353. this.#commands[this.#position].cmd();
  3354. this.#locked = false;
  3355. }
  3356. }
  3357. hasSomethingToUndo() {
  3358. return this.#position !== -1;
  3359. }
  3360. hasSomethingToRedo() {
  3361. return this.#position < this.#commands.length - 1;
  3362. }
  3363. destroy() {
  3364. this.#commands = null;
  3365. }
  3366. }
  3367. exports.CommandManager = CommandManager;
  3368. class KeyboardManager {
  3369. constructor(callbacks) {
  3370. this.buffer = [];
  3371. this.callbacks = new Map();
  3372. this.allKeys = new Set();
  3373. const {
  3374. isMac
  3375. } = _util.FeatureTest.platform;
  3376. for (const [keys, callback] of callbacks) {
  3377. for (const key of keys) {
  3378. const isMacKey = key.startsWith("mac+");
  3379. if (isMac && isMacKey) {
  3380. this.callbacks.set(key.slice(4), callback);
  3381. this.allKeys.add(key.split("+").at(-1));
  3382. } else if (!isMac && !isMacKey) {
  3383. this.callbacks.set(key, callback);
  3384. this.allKeys.add(key.split("+").at(-1));
  3385. }
  3386. }
  3387. }
  3388. }
  3389. #serialize(event) {
  3390. if (event.altKey) {
  3391. this.buffer.push("alt");
  3392. }
  3393. if (event.ctrlKey) {
  3394. this.buffer.push("ctrl");
  3395. }
  3396. if (event.metaKey) {
  3397. this.buffer.push("meta");
  3398. }
  3399. if (event.shiftKey) {
  3400. this.buffer.push("shift");
  3401. }
  3402. this.buffer.push(event.key);
  3403. const str = this.buffer.join("+");
  3404. this.buffer.length = 0;
  3405. return str;
  3406. }
  3407. exec(self, event) {
  3408. if (!this.allKeys.has(event.key)) {
  3409. return;
  3410. }
  3411. const callback = this.callbacks.get(this.#serialize(event));
  3412. if (!callback) {
  3413. return;
  3414. }
  3415. callback.bind(self)();
  3416. event.stopPropagation();
  3417. event.preventDefault();
  3418. }
  3419. }
  3420. exports.KeyboardManager = KeyboardManager;
  3421. class ColorManager {
  3422. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  3423. get _colors() {
  3424. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  3425. (0, _display_utils.getColorValues)(colors);
  3426. return (0, _util.shadow)(this, "_colors", colors);
  3427. }
  3428. convert(color) {
  3429. const rgb = (0, _display_utils.getRGB)(color);
  3430. if (!window.matchMedia("(forced-colors: active)").matches) {
  3431. return rgb;
  3432. }
  3433. for (const [name, RGB] of this._colors) {
  3434. if (RGB.every((x, i) => x === rgb[i])) {
  3435. return ColorManager._colorsMapping.get(name);
  3436. }
  3437. }
  3438. return rgb;
  3439. }
  3440. getHexCode(name) {
  3441. const rgb = this._colors.get(name);
  3442. if (!rgb) {
  3443. return name;
  3444. }
  3445. return _util.Util.makeHexColor(...rgb);
  3446. }
  3447. }
  3448. exports.ColorManager = ColorManager;
  3449. class AnnotationEditorUIManager {
  3450. #activeEditor = null;
  3451. #allEditors = new Map();
  3452. #allLayers = new Map();
  3453. #annotationStorage = null;
  3454. #commandManager = new CommandManager();
  3455. #currentPageIndex = 0;
  3456. #editorTypes = null;
  3457. #editorsToRescale = new Set();
  3458. #eventBus = null;
  3459. #idManager = new IdManager();
  3460. #isEnabled = false;
  3461. #mode = _util.AnnotationEditorType.NONE;
  3462. #selectedEditors = new Set();
  3463. #boundCopy = this.copy.bind(this);
  3464. #boundCut = this.cut.bind(this);
  3465. #boundPaste = this.paste.bind(this);
  3466. #boundKeydown = this.keydown.bind(this);
  3467. #boundOnEditingAction = this.onEditingAction.bind(this);
  3468. #boundOnPageChanging = this.onPageChanging.bind(this);
  3469. #boundOnScaleChanging = this.onScaleChanging.bind(this);
  3470. #boundOnRotationChanging = this.onRotationChanging.bind(this);
  3471. #previousStates = {
  3472. isEditing: false,
  3473. isEmpty: true,
  3474. hasSomethingToUndo: false,
  3475. hasSomethingToRedo: false,
  3476. hasSelectedEditor: false
  3477. };
  3478. #container = null;
  3479. 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]]);
  3480. constructor(container, eventBus, annotationStorage) {
  3481. this.#container = container;
  3482. this.#eventBus = eventBus;
  3483. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  3484. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  3485. this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
  3486. this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
  3487. this.#annotationStorage = annotationStorage;
  3488. this.viewParameters = {
  3489. realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
  3490. rotation: 0
  3491. };
  3492. }
  3493. destroy() {
  3494. this.#removeKeyboardManager();
  3495. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  3496. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  3497. this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
  3498. this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
  3499. for (const layer of this.#allLayers.values()) {
  3500. layer.destroy();
  3501. }
  3502. this.#allLayers.clear();
  3503. this.#allEditors.clear();
  3504. this.#editorsToRescale.clear();
  3505. this.#activeEditor = null;
  3506. this.#selectedEditors.clear();
  3507. this.#commandManager.destroy();
  3508. }
  3509. onPageChanging({
  3510. pageNumber
  3511. }) {
  3512. this.#currentPageIndex = pageNumber - 1;
  3513. }
  3514. focusMainContainer() {
  3515. this.#container.focus();
  3516. }
  3517. addShouldRescale(editor) {
  3518. this.#editorsToRescale.add(editor);
  3519. }
  3520. removeShouldRescale(editor) {
  3521. this.#editorsToRescale.delete(editor);
  3522. }
  3523. onScaleChanging({
  3524. scale
  3525. }) {
  3526. this.commitOrRemove();
  3527. this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
  3528. for (const editor of this.#editorsToRescale) {
  3529. editor.onScaleChanging();
  3530. }
  3531. }
  3532. onRotationChanging({
  3533. pagesRotation
  3534. }) {
  3535. this.commitOrRemove();
  3536. this.viewParameters.rotation = pagesRotation;
  3537. }
  3538. addToAnnotationStorage(editor) {
  3539. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  3540. this.#annotationStorage.setValue(editor.id, editor);
  3541. }
  3542. }
  3543. #addKeyboardManager() {
  3544. this.#container.addEventListener("keydown", this.#boundKeydown);
  3545. }
  3546. #removeKeyboardManager() {
  3547. this.#container.removeEventListener("keydown", this.#boundKeydown);
  3548. }
  3549. #addCopyPasteListeners() {
  3550. document.addEventListener("copy", this.#boundCopy);
  3551. document.addEventListener("cut", this.#boundCut);
  3552. document.addEventListener("paste", this.#boundPaste);
  3553. }
  3554. #removeCopyPasteListeners() {
  3555. document.removeEventListener("copy", this.#boundCopy);
  3556. document.removeEventListener("cut", this.#boundCut);
  3557. document.removeEventListener("paste", this.#boundPaste);
  3558. }
  3559. copy(event) {
  3560. event.preventDefault();
  3561. if (this.#activeEditor) {
  3562. this.#activeEditor.commitOrRemove();
  3563. }
  3564. if (!this.hasSelection) {
  3565. return;
  3566. }
  3567. const editors = [];
  3568. for (const editor of this.#selectedEditors) {
  3569. if (!editor.isEmpty()) {
  3570. editors.push(editor.serialize());
  3571. }
  3572. }
  3573. if (editors.length === 0) {
  3574. return;
  3575. }
  3576. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  3577. }
  3578. cut(event) {
  3579. this.copy(event);
  3580. this.delete();
  3581. }
  3582. paste(event) {
  3583. event.preventDefault();
  3584. let data = event.clipboardData.getData("application/pdfjs");
  3585. if (!data) {
  3586. return;
  3587. }
  3588. try {
  3589. data = JSON.parse(data);
  3590. } catch (ex) {
  3591. (0, _util.warn)(`paste: "${ex.message}".`);
  3592. return;
  3593. }
  3594. if (!Array.isArray(data)) {
  3595. return;
  3596. }
  3597. this.unselectAll();
  3598. const layer = this.#allLayers.get(this.#currentPageIndex);
  3599. try {
  3600. const newEditors = [];
  3601. for (const editor of data) {
  3602. const deserializedEditor = layer.deserialize(editor);
  3603. if (!deserializedEditor) {
  3604. return;
  3605. }
  3606. newEditors.push(deserializedEditor);
  3607. }
  3608. const cmd = () => {
  3609. for (const editor of newEditors) {
  3610. this.#addEditorToLayer(editor);
  3611. }
  3612. this.#selectEditors(newEditors);
  3613. };
  3614. const undo = () => {
  3615. for (const editor of newEditors) {
  3616. editor.remove();
  3617. }
  3618. };
  3619. this.addCommands({
  3620. cmd,
  3621. undo,
  3622. mustExec: true
  3623. });
  3624. } catch (ex) {
  3625. (0, _util.warn)(`paste: "${ex.message}".`);
  3626. }
  3627. }
  3628. keydown(event) {
  3629. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  3630. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  3631. }
  3632. }
  3633. onEditingAction(details) {
  3634. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  3635. this[details.name]();
  3636. }
  3637. }
  3638. #dispatchUpdateStates(details) {
  3639. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  3640. if (hasChanged) {
  3641. this.#eventBus.dispatch("annotationeditorstateschanged", {
  3642. source: this,
  3643. details: Object.assign(this.#previousStates, details)
  3644. });
  3645. }
  3646. }
  3647. #dispatchUpdateUI(details) {
  3648. this.#eventBus.dispatch("annotationeditorparamschanged", {
  3649. source: this,
  3650. details
  3651. });
  3652. }
  3653. setEditingState(isEditing) {
  3654. if (isEditing) {
  3655. this.#addKeyboardManager();
  3656. this.#addCopyPasteListeners();
  3657. this.#dispatchUpdateStates({
  3658. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  3659. isEmpty: this.#isEmpty(),
  3660. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3661. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3662. hasSelectedEditor: false
  3663. });
  3664. } else {
  3665. this.#removeKeyboardManager();
  3666. this.#removeCopyPasteListeners();
  3667. this.#dispatchUpdateStates({
  3668. isEditing: false
  3669. });
  3670. }
  3671. }
  3672. registerEditorTypes(types) {
  3673. if (this.#editorTypes) {
  3674. return;
  3675. }
  3676. this.#editorTypes = types;
  3677. for (const editorType of this.#editorTypes) {
  3678. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  3679. }
  3680. }
  3681. getId() {
  3682. return this.#idManager.getId();
  3683. }
  3684. get currentLayer() {
  3685. return this.#allLayers.get(this.#currentPageIndex);
  3686. }
  3687. get currentPageIndex() {
  3688. return this.#currentPageIndex;
  3689. }
  3690. addLayer(layer) {
  3691. this.#allLayers.set(layer.pageIndex, layer);
  3692. if (this.#isEnabled) {
  3693. layer.enable();
  3694. } else {
  3695. layer.disable();
  3696. }
  3697. }
  3698. removeLayer(layer) {
  3699. this.#allLayers.delete(layer.pageIndex);
  3700. }
  3701. updateMode(mode) {
  3702. this.#mode = mode;
  3703. if (mode === _util.AnnotationEditorType.NONE) {
  3704. this.setEditingState(false);
  3705. this.#disableAll();
  3706. } else {
  3707. this.setEditingState(true);
  3708. this.#enableAll();
  3709. for (const layer of this.#allLayers.values()) {
  3710. layer.updateMode(mode);
  3711. }
  3712. }
  3713. }
  3714. updateToolbar(mode) {
  3715. if (mode === this.#mode) {
  3716. return;
  3717. }
  3718. this.#eventBus.dispatch("switchannotationeditormode", {
  3719. source: this,
  3720. mode
  3721. });
  3722. }
  3723. updateParams(type, value) {
  3724. if (!this.#editorTypes) {
  3725. return;
  3726. }
  3727. for (const editor of this.#selectedEditors) {
  3728. editor.updateParams(type, value);
  3729. }
  3730. for (const editorType of this.#editorTypes) {
  3731. editorType.updateDefaultParams(type, value);
  3732. }
  3733. }
  3734. #enableAll() {
  3735. if (!this.#isEnabled) {
  3736. this.#isEnabled = true;
  3737. for (const layer of this.#allLayers.values()) {
  3738. layer.enable();
  3739. }
  3740. }
  3741. }
  3742. #disableAll() {
  3743. this.unselectAll();
  3744. if (this.#isEnabled) {
  3745. this.#isEnabled = false;
  3746. for (const layer of this.#allLayers.values()) {
  3747. layer.disable();
  3748. }
  3749. }
  3750. }
  3751. getEditors(pageIndex) {
  3752. const editors = [];
  3753. for (const editor of this.#allEditors.values()) {
  3754. if (editor.pageIndex === pageIndex) {
  3755. editors.push(editor);
  3756. }
  3757. }
  3758. return editors;
  3759. }
  3760. getEditor(id) {
  3761. return this.#allEditors.get(id);
  3762. }
  3763. addEditor(editor) {
  3764. this.#allEditors.set(editor.id, editor);
  3765. }
  3766. removeEditor(editor) {
  3767. this.#allEditors.delete(editor.id);
  3768. this.unselect(editor);
  3769. this.#annotationStorage?.remove(editor.id);
  3770. }
  3771. #addEditorToLayer(editor) {
  3772. const layer = this.#allLayers.get(editor.pageIndex);
  3773. if (layer) {
  3774. layer.addOrRebuild(editor);
  3775. } else {
  3776. this.addEditor(editor);
  3777. }
  3778. }
  3779. setActiveEditor(editor) {
  3780. if (this.#activeEditor === editor) {
  3781. return;
  3782. }
  3783. this.#activeEditor = editor;
  3784. if (editor) {
  3785. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3786. }
  3787. }
  3788. toggleSelected(editor) {
  3789. if (this.#selectedEditors.has(editor)) {
  3790. this.#selectedEditors.delete(editor);
  3791. editor.unselect();
  3792. this.#dispatchUpdateStates({
  3793. hasSelectedEditor: this.hasSelection
  3794. });
  3795. return;
  3796. }
  3797. this.#selectedEditors.add(editor);
  3798. editor.select();
  3799. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3800. this.#dispatchUpdateStates({
  3801. hasSelectedEditor: true
  3802. });
  3803. }
  3804. setSelected(editor) {
  3805. for (const ed of this.#selectedEditors) {
  3806. if (ed !== editor) {
  3807. ed.unselect();
  3808. }
  3809. }
  3810. this.#selectedEditors.clear();
  3811. this.#selectedEditors.add(editor);
  3812. editor.select();
  3813. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3814. this.#dispatchUpdateStates({
  3815. hasSelectedEditor: true
  3816. });
  3817. }
  3818. isSelected(editor) {
  3819. return this.#selectedEditors.has(editor);
  3820. }
  3821. unselect(editor) {
  3822. editor.unselect();
  3823. this.#selectedEditors.delete(editor);
  3824. this.#dispatchUpdateStates({
  3825. hasSelectedEditor: this.hasSelection
  3826. });
  3827. }
  3828. get hasSelection() {
  3829. return this.#selectedEditors.size !== 0;
  3830. }
  3831. undo() {
  3832. this.#commandManager.undo();
  3833. this.#dispatchUpdateStates({
  3834. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3835. hasSomethingToRedo: true,
  3836. isEmpty: this.#isEmpty()
  3837. });
  3838. }
  3839. redo() {
  3840. this.#commandManager.redo();
  3841. this.#dispatchUpdateStates({
  3842. hasSomethingToUndo: true,
  3843. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3844. isEmpty: this.#isEmpty()
  3845. });
  3846. }
  3847. addCommands(params) {
  3848. this.#commandManager.add(params);
  3849. this.#dispatchUpdateStates({
  3850. hasSomethingToUndo: true,
  3851. hasSomethingToRedo: false,
  3852. isEmpty: this.#isEmpty()
  3853. });
  3854. }
  3855. #isEmpty() {
  3856. if (this.#allEditors.size === 0) {
  3857. return true;
  3858. }
  3859. if (this.#allEditors.size === 1) {
  3860. for (const editor of this.#allEditors.values()) {
  3861. return editor.isEmpty();
  3862. }
  3863. }
  3864. return false;
  3865. }
  3866. delete() {
  3867. this.commitOrRemove();
  3868. if (!this.hasSelection) {
  3869. return;
  3870. }
  3871. const editors = [...this.#selectedEditors];
  3872. const cmd = () => {
  3873. for (const editor of editors) {
  3874. editor.remove();
  3875. }
  3876. };
  3877. const undo = () => {
  3878. for (const editor of editors) {
  3879. this.#addEditorToLayer(editor);
  3880. }
  3881. };
  3882. this.addCommands({
  3883. cmd,
  3884. undo,
  3885. mustExec: true
  3886. });
  3887. }
  3888. commitOrRemove() {
  3889. this.#activeEditor?.commitOrRemove();
  3890. }
  3891. #selectEditors(editors) {
  3892. this.#selectedEditors.clear();
  3893. for (const editor of editors) {
  3894. if (editor.isEmpty()) {
  3895. continue;
  3896. }
  3897. this.#selectedEditors.add(editor);
  3898. editor.select();
  3899. }
  3900. this.#dispatchUpdateStates({
  3901. hasSelectedEditor: true
  3902. });
  3903. }
  3904. selectAll() {
  3905. for (const editor of this.#selectedEditors) {
  3906. editor.commit();
  3907. }
  3908. this.#selectEditors(this.#allEditors.values());
  3909. }
  3910. unselectAll() {
  3911. if (this.#activeEditor) {
  3912. this.#activeEditor.commitOrRemove();
  3913. return;
  3914. }
  3915. if (this.#selectedEditors.size === 0) {
  3916. return;
  3917. }
  3918. for (const editor of this.#selectedEditors) {
  3919. editor.unselect();
  3920. }
  3921. this.#selectedEditors.clear();
  3922. this.#dispatchUpdateStates({
  3923. hasSelectedEditor: false
  3924. });
  3925. }
  3926. isActive(editor) {
  3927. return this.#activeEditor === editor;
  3928. }
  3929. getActive() {
  3930. return this.#activeEditor;
  3931. }
  3932. getMode() {
  3933. return this.#mode;
  3934. }
  3935. }
  3936. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  3937. /***/ }),
  3938. /* 6 */
  3939. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3940. Object.defineProperty(exports, "__esModule", ({
  3941. value: true
  3942. }));
  3943. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  3944. exports.deprecated = deprecated;
  3945. exports.getColorValues = getColorValues;
  3946. exports.getCurrentTransform = getCurrentTransform;
  3947. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  3948. exports.getFilenameFromUrl = getFilenameFromUrl;
  3949. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  3950. exports.getRGB = getRGB;
  3951. exports.getXfaPageViewport = getXfaPageViewport;
  3952. exports.isDataScheme = isDataScheme;
  3953. exports.isPdfFile = isPdfFile;
  3954. exports.isValidFetchUrl = isValidFetchUrl;
  3955. exports.loadScript = loadScript;
  3956. exports.setLayerDimensions = setLayerDimensions;
  3957. var _base_factory = __w_pdfjs_require__(7);
  3958. var _util = __w_pdfjs_require__(1);
  3959. const SVG_NS = "http://www.w3.org/2000/svg";
  3960. const AnnotationPrefix = "pdfjs_internal_id_";
  3961. exports.AnnotationPrefix = AnnotationPrefix;
  3962. class PixelsPerInch {
  3963. static CSS = 96.0;
  3964. static PDF = 72.0;
  3965. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  3966. }
  3967. exports.PixelsPerInch = PixelsPerInch;
  3968. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  3969. constructor({
  3970. ownerDocument = globalThis.document
  3971. } = {}) {
  3972. super();
  3973. this._document = ownerDocument;
  3974. }
  3975. _createCanvas(width, height) {
  3976. const canvas = this._document.createElement("canvas");
  3977. canvas.width = width;
  3978. canvas.height = height;
  3979. return canvas;
  3980. }
  3981. }
  3982. exports.DOMCanvasFactory = DOMCanvasFactory;
  3983. async function fetchData(url, asTypedArray = false) {
  3984. if (isValidFetchUrl(url, document.baseURI)) {
  3985. const response = await fetch(url);
  3986. if (!response.ok) {
  3987. throw new Error(response.statusText);
  3988. }
  3989. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  3990. }
  3991. return new Promise((resolve, reject) => {
  3992. const request = new XMLHttpRequest();
  3993. request.open("GET", url, true);
  3994. if (asTypedArray) {
  3995. request.responseType = "arraybuffer";
  3996. }
  3997. request.onreadystatechange = () => {
  3998. if (request.readyState !== XMLHttpRequest.DONE) {
  3999. return;
  4000. }
  4001. if (request.status === 200 || request.status === 0) {
  4002. let data;
  4003. if (asTypedArray && request.response) {
  4004. data = new Uint8Array(request.response);
  4005. } else if (!asTypedArray && request.responseText) {
  4006. data = (0, _util.stringToBytes)(request.responseText);
  4007. }
  4008. if (data) {
  4009. resolve(data);
  4010. return;
  4011. }
  4012. }
  4013. reject(new Error(request.statusText));
  4014. };
  4015. request.send(null);
  4016. });
  4017. }
  4018. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  4019. _fetchData(url, compressionType) {
  4020. return fetchData(url, this.isCompressed).then(data => {
  4021. return {
  4022. cMapData: data,
  4023. compressionType
  4024. };
  4025. });
  4026. }
  4027. }
  4028. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  4029. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  4030. _fetchData(url) {
  4031. return fetchData(url, true);
  4032. }
  4033. }
  4034. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  4035. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  4036. _createSVG(type) {
  4037. return document.createElementNS(SVG_NS, type);
  4038. }
  4039. }
  4040. exports.DOMSVGFactory = DOMSVGFactory;
  4041. class PageViewport {
  4042. constructor({
  4043. viewBox,
  4044. scale,
  4045. rotation,
  4046. offsetX = 0,
  4047. offsetY = 0,
  4048. dontFlip = false
  4049. }) {
  4050. this.viewBox = viewBox;
  4051. this.scale = scale;
  4052. this.rotation = rotation;
  4053. this.offsetX = offsetX;
  4054. this.offsetY = offsetY;
  4055. const centerX = (viewBox[2] + viewBox[0]) / 2;
  4056. const centerY = (viewBox[3] + viewBox[1]) / 2;
  4057. let rotateA, rotateB, rotateC, rotateD;
  4058. rotation %= 360;
  4059. if (rotation < 0) {
  4060. rotation += 360;
  4061. }
  4062. switch (rotation) {
  4063. case 180:
  4064. rotateA = -1;
  4065. rotateB = 0;
  4066. rotateC = 0;
  4067. rotateD = 1;
  4068. break;
  4069. case 90:
  4070. rotateA = 0;
  4071. rotateB = 1;
  4072. rotateC = 1;
  4073. rotateD = 0;
  4074. break;
  4075. case 270:
  4076. rotateA = 0;
  4077. rotateB = -1;
  4078. rotateC = -1;
  4079. rotateD = 0;
  4080. break;
  4081. case 0:
  4082. rotateA = 1;
  4083. rotateB = 0;
  4084. rotateC = 0;
  4085. rotateD = -1;
  4086. break;
  4087. default:
  4088. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  4089. }
  4090. if (dontFlip) {
  4091. rotateC = -rotateC;
  4092. rotateD = -rotateD;
  4093. }
  4094. let offsetCanvasX, offsetCanvasY;
  4095. let width, height;
  4096. if (rotateA === 0) {
  4097. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  4098. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  4099. width = (viewBox[3] - viewBox[1]) * scale;
  4100. height = (viewBox[2] - viewBox[0]) * scale;
  4101. } else {
  4102. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  4103. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  4104. width = (viewBox[2] - viewBox[0]) * scale;
  4105. height = (viewBox[3] - viewBox[1]) * scale;
  4106. }
  4107. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4108. this.width = width;
  4109. this.height = height;
  4110. }
  4111. get rawDims() {
  4112. const {
  4113. viewBox
  4114. } = this;
  4115. return (0, _util.shadow)(this, "rawDims", {
  4116. pageWidth: viewBox[2] - viewBox[0],
  4117. pageHeight: viewBox[3] - viewBox[1],
  4118. pageX: viewBox[0],
  4119. pageY: viewBox[1]
  4120. });
  4121. }
  4122. clone({
  4123. scale = this.scale,
  4124. rotation = this.rotation,
  4125. offsetX = this.offsetX,
  4126. offsetY = this.offsetY,
  4127. dontFlip = false
  4128. } = {}) {
  4129. return new PageViewport({
  4130. viewBox: this.viewBox.slice(),
  4131. scale,
  4132. rotation,
  4133. offsetX,
  4134. offsetY,
  4135. dontFlip
  4136. });
  4137. }
  4138. convertToViewportPoint(x, y) {
  4139. return _util.Util.applyTransform([x, y], this.transform);
  4140. }
  4141. convertToViewportRectangle(rect) {
  4142. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  4143. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  4144. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  4145. }
  4146. convertToPdfPoint(x, y) {
  4147. return _util.Util.applyInverseTransform([x, y], this.transform);
  4148. }
  4149. }
  4150. exports.PageViewport = PageViewport;
  4151. class RenderingCancelledException extends _util.BaseException {
  4152. constructor(msg, type, extraDelay = 0) {
  4153. super(msg, "RenderingCancelledException");
  4154. this.type = type;
  4155. this.extraDelay = extraDelay;
  4156. }
  4157. }
  4158. exports.RenderingCancelledException = RenderingCancelledException;
  4159. function isDataScheme(url) {
  4160. const ii = url.length;
  4161. let i = 0;
  4162. while (i < ii && url[i].trim() === "") {
  4163. i++;
  4164. }
  4165. return url.substring(i, i + 5).toLowerCase() === "data:";
  4166. }
  4167. function isPdfFile(filename) {
  4168. return typeof filename === "string" && /\.pdf$/i.test(filename);
  4169. }
  4170. function getFilenameFromUrl(url, onlyStripPath = false) {
  4171. if (!onlyStripPath) {
  4172. [url] = url.split(/[#?]/, 1);
  4173. }
  4174. return url.substring(url.lastIndexOf("/") + 1);
  4175. }
  4176. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  4177. if (typeof url !== "string") {
  4178. return defaultFilename;
  4179. }
  4180. if (isDataScheme(url)) {
  4181. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  4182. return defaultFilename;
  4183. }
  4184. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  4185. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  4186. const splitURI = reURI.exec(url);
  4187. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  4188. if (suggestedFilename) {
  4189. suggestedFilename = suggestedFilename[0];
  4190. if (suggestedFilename.includes("%")) {
  4191. try {
  4192. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  4193. } catch (ex) {}
  4194. }
  4195. }
  4196. return suggestedFilename || defaultFilename;
  4197. }
  4198. class StatTimer {
  4199. started = Object.create(null);
  4200. times = [];
  4201. time(name) {
  4202. if (name in this.started) {
  4203. (0, _util.warn)(`Timer is already running for ${name}`);
  4204. }
  4205. this.started[name] = Date.now();
  4206. }
  4207. timeEnd(name) {
  4208. if (!(name in this.started)) {
  4209. (0, _util.warn)(`Timer has not been started for ${name}`);
  4210. }
  4211. this.times.push({
  4212. name,
  4213. start: this.started[name],
  4214. end: Date.now()
  4215. });
  4216. delete this.started[name];
  4217. }
  4218. toString() {
  4219. const outBuf = [];
  4220. let longest = 0;
  4221. for (const {
  4222. name
  4223. } of this.times) {
  4224. longest = Math.max(name.length, longest);
  4225. }
  4226. for (const {
  4227. name,
  4228. start,
  4229. end
  4230. } of this.times) {
  4231. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  4232. }
  4233. return outBuf.join("");
  4234. }
  4235. }
  4236. exports.StatTimer = StatTimer;
  4237. function isValidFetchUrl(url, baseUrl) {
  4238. try {
  4239. const {
  4240. protocol
  4241. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  4242. return protocol === "http:" || protocol === "https:";
  4243. } catch (ex) {
  4244. return false;
  4245. }
  4246. }
  4247. function loadScript(src, removeScriptElement = false) {
  4248. return new Promise((resolve, reject) => {
  4249. const script = document.createElement("script");
  4250. script.src = src;
  4251. script.onload = function (evt) {
  4252. if (removeScriptElement) {
  4253. script.remove();
  4254. }
  4255. resolve(evt);
  4256. };
  4257. script.onerror = function () {
  4258. reject(new Error(`Cannot load script at: ${script.src}`));
  4259. };
  4260. (document.head || document.documentElement).append(script);
  4261. });
  4262. }
  4263. function deprecated(details) {
  4264. console.log("Deprecated API usage: " + details);
  4265. }
  4266. let pdfDateStringRegex;
  4267. class PDFDateString {
  4268. static toDateObject(input) {
  4269. if (!input || typeof input !== "string") {
  4270. return null;
  4271. }
  4272. if (!pdfDateStringRegex) {
  4273. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  4274. }
  4275. const matches = pdfDateStringRegex.exec(input);
  4276. if (!matches) {
  4277. return null;
  4278. }
  4279. const year = parseInt(matches[1], 10);
  4280. let month = parseInt(matches[2], 10);
  4281. month = month >= 1 && month <= 12 ? month - 1 : 0;
  4282. let day = parseInt(matches[3], 10);
  4283. day = day >= 1 && day <= 31 ? day : 1;
  4284. let hour = parseInt(matches[4], 10);
  4285. hour = hour >= 0 && hour <= 23 ? hour : 0;
  4286. let minute = parseInt(matches[5], 10);
  4287. minute = minute >= 0 && minute <= 59 ? minute : 0;
  4288. let second = parseInt(matches[6], 10);
  4289. second = second >= 0 && second <= 59 ? second : 0;
  4290. const universalTimeRelation = matches[7] || "Z";
  4291. let offsetHour = parseInt(matches[8], 10);
  4292. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  4293. let offsetMinute = parseInt(matches[9], 10) || 0;
  4294. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  4295. if (universalTimeRelation === "-") {
  4296. hour += offsetHour;
  4297. minute += offsetMinute;
  4298. } else if (universalTimeRelation === "+") {
  4299. hour -= offsetHour;
  4300. minute -= offsetMinute;
  4301. }
  4302. return new Date(Date.UTC(year, month, day, hour, minute, second));
  4303. }
  4304. }
  4305. exports.PDFDateString = PDFDateString;
  4306. function getXfaPageViewport(xfaPage, {
  4307. scale = 1,
  4308. rotation = 0
  4309. }) {
  4310. const {
  4311. width,
  4312. height
  4313. } = xfaPage.attributes.style;
  4314. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  4315. return new PageViewport({
  4316. viewBox,
  4317. scale,
  4318. rotation
  4319. });
  4320. }
  4321. function getRGB(color) {
  4322. if (color.startsWith("#")) {
  4323. const colorRGB = parseInt(color.slice(1), 16);
  4324. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  4325. }
  4326. if (color.startsWith("rgb(")) {
  4327. return color.slice(4, -1).split(",").map(x => parseInt(x));
  4328. }
  4329. if (color.startsWith("rgba(")) {
  4330. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  4331. }
  4332. (0, _util.warn)(`Not a valid color format: "${color}"`);
  4333. return [0, 0, 0];
  4334. }
  4335. function getColorValues(colors) {
  4336. const span = document.createElement("span");
  4337. span.style.visibility = "hidden";
  4338. document.body.append(span);
  4339. for (const name of colors.keys()) {
  4340. span.style.color = name;
  4341. const computedColor = window.getComputedStyle(span).color;
  4342. colors.set(name, getRGB(computedColor));
  4343. }
  4344. span.remove();
  4345. }
  4346. function getCurrentTransform(ctx) {
  4347. const {
  4348. a,
  4349. b,
  4350. c,
  4351. d,
  4352. e,
  4353. f
  4354. } = ctx.getTransform();
  4355. return [a, b, c, d, e, f];
  4356. }
  4357. function getCurrentTransformInverse(ctx) {
  4358. const {
  4359. a,
  4360. b,
  4361. c,
  4362. d,
  4363. e,
  4364. f
  4365. } = ctx.getTransform().invertSelf();
  4366. return [a, b, c, d, e, f];
  4367. }
  4368. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  4369. if (viewport instanceof PageViewport) {
  4370. const {
  4371. pageWidth,
  4372. pageHeight
  4373. } = viewport.rawDims;
  4374. const {
  4375. style
  4376. } = div;
  4377. const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
  4378. const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
  4379. if (!mustFlip || viewport.rotation % 180 === 0) {
  4380. style.width = widthStr;
  4381. style.height = heightStr;
  4382. } else {
  4383. style.width = heightStr;
  4384. style.height = widthStr;
  4385. }
  4386. }
  4387. if (mustRotate) {
  4388. div.setAttribute("data-main-rotation", viewport.rotation);
  4389. }
  4390. }
  4391. /***/ }),
  4392. /* 7 */
  4393. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4394. Object.defineProperty(exports, "__esModule", ({
  4395. value: true
  4396. }));
  4397. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  4398. var _util = __w_pdfjs_require__(1);
  4399. class BaseCanvasFactory {
  4400. constructor() {
  4401. if (this.constructor === BaseCanvasFactory) {
  4402. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  4403. }
  4404. }
  4405. create(width, height) {
  4406. if (width <= 0 || height <= 0) {
  4407. throw new Error("Invalid canvas size");
  4408. }
  4409. const canvas = this._createCanvas(width, height);
  4410. return {
  4411. canvas,
  4412. context: canvas.getContext("2d")
  4413. };
  4414. }
  4415. reset(canvasAndContext, width, height) {
  4416. if (!canvasAndContext.canvas) {
  4417. throw new Error("Canvas is not specified");
  4418. }
  4419. if (width <= 0 || height <= 0) {
  4420. throw new Error("Invalid canvas size");
  4421. }
  4422. canvasAndContext.canvas.width = width;
  4423. canvasAndContext.canvas.height = height;
  4424. }
  4425. destroy(canvasAndContext) {
  4426. if (!canvasAndContext.canvas) {
  4427. throw new Error("Canvas is not specified");
  4428. }
  4429. canvasAndContext.canvas.width = 0;
  4430. canvasAndContext.canvas.height = 0;
  4431. canvasAndContext.canvas = null;
  4432. canvasAndContext.context = null;
  4433. }
  4434. _createCanvas(width, height) {
  4435. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  4436. }
  4437. }
  4438. exports.BaseCanvasFactory = BaseCanvasFactory;
  4439. class BaseCMapReaderFactory {
  4440. constructor({
  4441. baseUrl = null,
  4442. isCompressed = false
  4443. }) {
  4444. if (this.constructor === BaseCMapReaderFactory) {
  4445. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  4446. }
  4447. this.baseUrl = baseUrl;
  4448. this.isCompressed = isCompressed;
  4449. }
  4450. async fetch({
  4451. name
  4452. }) {
  4453. if (!this.baseUrl) {
  4454. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  4455. }
  4456. if (!name) {
  4457. throw new Error("CMap name must be specified.");
  4458. }
  4459. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  4460. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  4461. return this._fetchData(url, compressionType).catch(reason => {
  4462. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  4463. });
  4464. }
  4465. _fetchData(url, compressionType) {
  4466. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4467. }
  4468. }
  4469. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  4470. class BaseStandardFontDataFactory {
  4471. constructor({
  4472. baseUrl = null
  4473. }) {
  4474. if (this.constructor === BaseStandardFontDataFactory) {
  4475. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  4476. }
  4477. this.baseUrl = baseUrl;
  4478. }
  4479. async fetch({
  4480. filename
  4481. }) {
  4482. if (!this.baseUrl) {
  4483. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  4484. }
  4485. if (!filename) {
  4486. throw new Error("Font filename must be specified.");
  4487. }
  4488. const url = `${this.baseUrl}${filename}`;
  4489. return this._fetchData(url).catch(reason => {
  4490. throw new Error(`Unable to load font data at: ${url}`);
  4491. });
  4492. }
  4493. _fetchData(url) {
  4494. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4495. }
  4496. }
  4497. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  4498. class BaseSVGFactory {
  4499. constructor() {
  4500. if (this.constructor === BaseSVGFactory) {
  4501. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  4502. }
  4503. }
  4504. create(width, height, skipDimensions = false) {
  4505. if (width <= 0 || height <= 0) {
  4506. throw new Error("Invalid SVG dimensions");
  4507. }
  4508. const svg = this._createSVG("svg:svg");
  4509. svg.setAttribute("version", "1.1");
  4510. if (!skipDimensions) {
  4511. svg.setAttribute("width", `${width}px`);
  4512. svg.setAttribute("height", `${height}px`);
  4513. }
  4514. svg.setAttribute("preserveAspectRatio", "none");
  4515. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  4516. return svg;
  4517. }
  4518. createElement(type) {
  4519. if (typeof type !== "string") {
  4520. throw new Error("Invalid SVG element type");
  4521. }
  4522. return this._createSVG(type);
  4523. }
  4524. _createSVG(type) {
  4525. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  4526. }
  4527. }
  4528. exports.BaseSVGFactory = BaseSVGFactory;
  4529. /***/ }),
  4530. /* 8 */
  4531. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4532. Object.defineProperty(exports, "__esModule", ({
  4533. value: true
  4534. }));
  4535. exports.MurmurHash3_64 = void 0;
  4536. var _util = __w_pdfjs_require__(1);
  4537. const SEED = 0xc3d2e1f0;
  4538. const MASK_HIGH = 0xffff0000;
  4539. const MASK_LOW = 0xffff;
  4540. class MurmurHash3_64 {
  4541. constructor(seed) {
  4542. this.h1 = seed ? seed & 0xffffffff : SEED;
  4543. this.h2 = seed ? seed & 0xffffffff : SEED;
  4544. }
  4545. update(input) {
  4546. let data, length;
  4547. if (typeof input === "string") {
  4548. data = new Uint8Array(input.length * 2);
  4549. length = 0;
  4550. for (let i = 0, ii = input.length; i < ii; i++) {
  4551. const code = input.charCodeAt(i);
  4552. if (code <= 0xff) {
  4553. data[length++] = code;
  4554. } else {
  4555. data[length++] = code >>> 8;
  4556. data[length++] = code & 0xff;
  4557. }
  4558. }
  4559. } else if ((0, _util.isArrayBuffer)(input)) {
  4560. data = input.slice();
  4561. length = data.byteLength;
  4562. } else {
  4563. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  4564. }
  4565. const blockCounts = length >> 2;
  4566. const tailLength = length - blockCounts * 4;
  4567. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4568. let k1 = 0,
  4569. k2 = 0;
  4570. let h1 = this.h1,
  4571. h2 = this.h2;
  4572. const C1 = 0xcc9e2d51,
  4573. C2 = 0x1b873593;
  4574. const C1_LOW = C1 & MASK_LOW,
  4575. C2_LOW = C2 & MASK_LOW;
  4576. for (let i = 0; i < blockCounts; i++) {
  4577. if (i & 1) {
  4578. k1 = dataUint32[i];
  4579. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4580. k1 = k1 << 15 | k1 >>> 17;
  4581. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4582. h1 ^= k1;
  4583. h1 = h1 << 13 | h1 >>> 19;
  4584. h1 = h1 * 5 + 0xe6546b64;
  4585. } else {
  4586. k2 = dataUint32[i];
  4587. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4588. k2 = k2 << 15 | k2 >>> 17;
  4589. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4590. h2 ^= k2;
  4591. h2 = h2 << 13 | h2 >>> 19;
  4592. h2 = h2 * 5 + 0xe6546b64;
  4593. }
  4594. }
  4595. k1 = 0;
  4596. switch (tailLength) {
  4597. case 3:
  4598. k1 ^= data[blockCounts * 4 + 2] << 16;
  4599. case 2:
  4600. k1 ^= data[blockCounts * 4 + 1] << 8;
  4601. case 1:
  4602. k1 ^= data[blockCounts * 4];
  4603. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4604. k1 = k1 << 15 | k1 >>> 17;
  4605. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4606. if (blockCounts & 1) {
  4607. h1 ^= k1;
  4608. } else {
  4609. h2 ^= k1;
  4610. }
  4611. }
  4612. this.h1 = h1;
  4613. this.h2 = h2;
  4614. }
  4615. hexdigest() {
  4616. let h1 = this.h1,
  4617. h2 = this.h2;
  4618. h1 ^= h2 >>> 1;
  4619. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4620. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4621. h1 ^= h2 >>> 1;
  4622. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4623. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4624. h1 ^= h2 >>> 1;
  4625. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  4626. }
  4627. }
  4628. exports.MurmurHash3_64 = MurmurHash3_64;
  4629. /***/ }),
  4630. /* 9 */
  4631. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4632. Object.defineProperty(exports, "__esModule", ({
  4633. value: true
  4634. }));
  4635. exports.FontLoader = exports.FontFaceObject = void 0;
  4636. var _util = __w_pdfjs_require__(1);
  4637. var _is_node = __w_pdfjs_require__(10);
  4638. class FontLoader {
  4639. constructor({
  4640. onUnsupportedFeature,
  4641. ownerDocument = globalThis.document,
  4642. styleElement = null
  4643. }) {
  4644. this._onUnsupportedFeature = onUnsupportedFeature;
  4645. this._document = ownerDocument;
  4646. this.nativeFontFaces = [];
  4647. this.styleElement = null;
  4648. this.loadingRequests = [];
  4649. this.loadTestFontId = 0;
  4650. }
  4651. addNativeFontFace(nativeFontFace) {
  4652. this.nativeFontFaces.push(nativeFontFace);
  4653. this._document.fonts.add(nativeFontFace);
  4654. }
  4655. insertRule(rule) {
  4656. if (!this.styleElement) {
  4657. this.styleElement = this._document.createElement("style");
  4658. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  4659. }
  4660. const styleSheet = this.styleElement.sheet;
  4661. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4662. }
  4663. clear() {
  4664. for (const nativeFontFace of this.nativeFontFaces) {
  4665. this._document.fonts.delete(nativeFontFace);
  4666. }
  4667. this.nativeFontFaces.length = 0;
  4668. if (this.styleElement) {
  4669. this.styleElement.remove();
  4670. this.styleElement = null;
  4671. }
  4672. }
  4673. async bind(font) {
  4674. if (font.attached || font.missingFile) {
  4675. return;
  4676. }
  4677. font.attached = true;
  4678. if (this.isFontLoadingAPISupported) {
  4679. const nativeFontFace = font.createNativeFontFace();
  4680. if (nativeFontFace) {
  4681. this.addNativeFontFace(nativeFontFace);
  4682. try {
  4683. await nativeFontFace.loaded;
  4684. } catch (ex) {
  4685. this._onUnsupportedFeature({
  4686. featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
  4687. });
  4688. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  4689. font.disableFontFace = true;
  4690. throw ex;
  4691. }
  4692. }
  4693. return;
  4694. }
  4695. const rule = font.createFontFaceRule();
  4696. if (rule) {
  4697. this.insertRule(rule);
  4698. if (this.isSyncFontLoadingSupported) {
  4699. return;
  4700. }
  4701. await new Promise(resolve => {
  4702. const request = this._queueLoadingCallback(resolve);
  4703. this._prepareFontLoadEvent(font, request);
  4704. });
  4705. }
  4706. }
  4707. get isFontLoadingAPISupported() {
  4708. const hasFonts = !!this._document?.fonts;
  4709. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  4710. }
  4711. get isSyncFontLoadingSupported() {
  4712. let supported = false;
  4713. if (_is_node.isNodeJS) {
  4714. supported = true;
  4715. } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  4716. supported = true;
  4717. }
  4718. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  4719. }
  4720. _queueLoadingCallback(callback) {
  4721. function completeRequest() {
  4722. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  4723. request.done = true;
  4724. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  4725. const otherRequest = loadingRequests.shift();
  4726. setTimeout(otherRequest.callback, 0);
  4727. }
  4728. }
  4729. const {
  4730. loadingRequests
  4731. } = this;
  4732. const request = {
  4733. done: false,
  4734. complete: completeRequest,
  4735. callback
  4736. };
  4737. loadingRequests.push(request);
  4738. return request;
  4739. }
  4740. get _loadTestFont() {
  4741. 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==");
  4742. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  4743. }
  4744. _prepareFontLoadEvent(font, request) {
  4745. function int32(data, offset) {
  4746. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  4747. }
  4748. function spliceString(s, offset, remove, insert) {
  4749. const chunk1 = s.substring(0, offset);
  4750. const chunk2 = s.substring(offset + remove);
  4751. return chunk1 + insert + chunk2;
  4752. }
  4753. let i, ii;
  4754. const canvas = this._document.createElement("canvas");
  4755. canvas.width = 1;
  4756. canvas.height = 1;
  4757. const ctx = canvas.getContext("2d");
  4758. let called = 0;
  4759. function isFontReady(name, callback) {
  4760. if (++called > 30) {
  4761. (0, _util.warn)("Load test font never loaded.");
  4762. callback();
  4763. return;
  4764. }
  4765. ctx.font = "30px " + name;
  4766. ctx.fillText(".", 0, 20);
  4767. const imageData = ctx.getImageData(0, 0, 1, 1);
  4768. if (imageData.data[3] > 0) {
  4769. callback();
  4770. return;
  4771. }
  4772. setTimeout(isFontReady.bind(null, name, callback));
  4773. }
  4774. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  4775. let data = this._loadTestFont;
  4776. const COMMENT_OFFSET = 976;
  4777. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  4778. const CFF_CHECKSUM_OFFSET = 16;
  4779. const XXXX_VALUE = 0x58585858;
  4780. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  4781. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  4782. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  4783. }
  4784. if (i < loadTestFontId.length) {
  4785. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  4786. }
  4787. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  4788. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  4789. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  4790. this.insertRule(rule);
  4791. const div = this._document.createElement("div");
  4792. div.style.visibility = "hidden";
  4793. div.style.width = div.style.height = "10px";
  4794. div.style.position = "absolute";
  4795. div.style.top = div.style.left = "0px";
  4796. for (const name of [font.loadedName, loadTestFontId]) {
  4797. const span = this._document.createElement("span");
  4798. span.textContent = "Hi";
  4799. span.style.fontFamily = name;
  4800. div.append(span);
  4801. }
  4802. this._document.body.append(div);
  4803. isFontReady(loadTestFontId, () => {
  4804. div.remove();
  4805. request.complete();
  4806. });
  4807. }
  4808. }
  4809. exports.FontLoader = FontLoader;
  4810. class FontFaceObject {
  4811. constructor(translatedData, {
  4812. isEvalSupported = true,
  4813. disableFontFace = false,
  4814. ignoreErrors = false,
  4815. onUnsupportedFeature,
  4816. fontRegistry = null
  4817. }) {
  4818. this.compiledGlyphs = Object.create(null);
  4819. for (const i in translatedData) {
  4820. this[i] = translatedData[i];
  4821. }
  4822. this.isEvalSupported = isEvalSupported !== false;
  4823. this.disableFontFace = disableFontFace === true;
  4824. this.ignoreErrors = ignoreErrors === true;
  4825. this._onUnsupportedFeature = onUnsupportedFeature;
  4826. this.fontRegistry = fontRegistry;
  4827. }
  4828. createNativeFontFace() {
  4829. if (!this.data || this.disableFontFace) {
  4830. return null;
  4831. }
  4832. let nativeFontFace;
  4833. if (!this.cssFontInfo) {
  4834. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  4835. } else {
  4836. const css = {
  4837. weight: this.cssFontInfo.fontWeight
  4838. };
  4839. if (this.cssFontInfo.italicAngle) {
  4840. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  4841. }
  4842. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  4843. }
  4844. this.fontRegistry?.registerFont(this);
  4845. return nativeFontFace;
  4846. }
  4847. createFontFaceRule() {
  4848. if (!this.data || this.disableFontFace) {
  4849. return null;
  4850. }
  4851. const data = (0, _util.bytesToString)(this.data);
  4852. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  4853. let rule;
  4854. if (!this.cssFontInfo) {
  4855. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  4856. } else {
  4857. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  4858. if (this.cssFontInfo.italicAngle) {
  4859. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  4860. }
  4861. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  4862. }
  4863. this.fontRegistry?.registerFont(this, url);
  4864. return rule;
  4865. }
  4866. getPathGenerator(objs, character) {
  4867. if (this.compiledGlyphs[character] !== undefined) {
  4868. return this.compiledGlyphs[character];
  4869. }
  4870. let cmds;
  4871. try {
  4872. cmds = objs.get(this.loadedName + "_path_" + character);
  4873. } catch (ex) {
  4874. if (!this.ignoreErrors) {
  4875. throw ex;
  4876. }
  4877. this._onUnsupportedFeature({
  4878. featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
  4879. });
  4880. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  4881. return this.compiledGlyphs[character] = function (c, size) {};
  4882. }
  4883. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  4884. const jsBuf = [];
  4885. for (const current of cmds) {
  4886. const args = current.args !== undefined ? current.args.join(",") : "";
  4887. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  4888. }
  4889. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  4890. }
  4891. return this.compiledGlyphs[character] = function (c, size) {
  4892. for (const current of cmds) {
  4893. if (current.cmd === "scale") {
  4894. current.args = [size, -size];
  4895. }
  4896. c[current.cmd].apply(c, current.args);
  4897. }
  4898. };
  4899. }
  4900. }
  4901. exports.FontFaceObject = FontFaceObject;
  4902. /***/ }),
  4903. /* 10 */
  4904. /***/ ((__unused_webpack_module, exports) => {
  4905. Object.defineProperty(exports, "__esModule", ({
  4906. value: true
  4907. }));
  4908. exports.isNodeJS = void 0;
  4909. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  4910. exports.isNodeJS = isNodeJS;
  4911. /***/ }),
  4912. /* 11 */
  4913. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4914. Object.defineProperty(exports, "__esModule", ({
  4915. value: true
  4916. }));
  4917. exports.CanvasGraphics = void 0;
  4918. var _util = __w_pdfjs_require__(1);
  4919. var _display_utils = __w_pdfjs_require__(6);
  4920. var _pattern_helper = __w_pdfjs_require__(12);
  4921. var _image_utils = __w_pdfjs_require__(13);
  4922. var _is_node = __w_pdfjs_require__(10);
  4923. const MIN_FONT_SIZE = 16;
  4924. const MAX_FONT_SIZE = 100;
  4925. const MAX_GROUP_SIZE = 4096;
  4926. const EXECUTION_TIME = 15;
  4927. const EXECUTION_STEPS = 10;
  4928. const MAX_SIZE_TO_COMPILE = _is_node.isNodeJS && typeof Path2D === "undefined" ? -1 : 1000;
  4929. const FULL_CHUNK_HEIGHT = 16;
  4930. function mirrorContextOperations(ctx, destCtx) {
  4931. if (ctx._removeMirroring) {
  4932. throw new Error("Context is already forwarding operations.");
  4933. }
  4934. ctx.__originalSave = ctx.save;
  4935. ctx.__originalRestore = ctx.restore;
  4936. ctx.__originalRotate = ctx.rotate;
  4937. ctx.__originalScale = ctx.scale;
  4938. ctx.__originalTranslate = ctx.translate;
  4939. ctx.__originalTransform = ctx.transform;
  4940. ctx.__originalSetTransform = ctx.setTransform;
  4941. ctx.__originalResetTransform = ctx.resetTransform;
  4942. ctx.__originalClip = ctx.clip;
  4943. ctx.__originalMoveTo = ctx.moveTo;
  4944. ctx.__originalLineTo = ctx.lineTo;
  4945. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  4946. ctx.__originalRect = ctx.rect;
  4947. ctx.__originalClosePath = ctx.closePath;
  4948. ctx.__originalBeginPath = ctx.beginPath;
  4949. ctx._removeMirroring = () => {
  4950. ctx.save = ctx.__originalSave;
  4951. ctx.restore = ctx.__originalRestore;
  4952. ctx.rotate = ctx.__originalRotate;
  4953. ctx.scale = ctx.__originalScale;
  4954. ctx.translate = ctx.__originalTranslate;
  4955. ctx.transform = ctx.__originalTransform;
  4956. ctx.setTransform = ctx.__originalSetTransform;
  4957. ctx.resetTransform = ctx.__originalResetTransform;
  4958. ctx.clip = ctx.__originalClip;
  4959. ctx.moveTo = ctx.__originalMoveTo;
  4960. ctx.lineTo = ctx.__originalLineTo;
  4961. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  4962. ctx.rect = ctx.__originalRect;
  4963. ctx.closePath = ctx.__originalClosePath;
  4964. ctx.beginPath = ctx.__originalBeginPath;
  4965. delete ctx._removeMirroring;
  4966. };
  4967. ctx.save = function ctxSave() {
  4968. destCtx.save();
  4969. this.__originalSave();
  4970. };
  4971. ctx.restore = function ctxRestore() {
  4972. destCtx.restore();
  4973. this.__originalRestore();
  4974. };
  4975. ctx.translate = function ctxTranslate(x, y) {
  4976. destCtx.translate(x, y);
  4977. this.__originalTranslate(x, y);
  4978. };
  4979. ctx.scale = function ctxScale(x, y) {
  4980. destCtx.scale(x, y);
  4981. this.__originalScale(x, y);
  4982. };
  4983. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4984. destCtx.transform(a, b, c, d, e, f);
  4985. this.__originalTransform(a, b, c, d, e, f);
  4986. };
  4987. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4988. destCtx.setTransform(a, b, c, d, e, f);
  4989. this.__originalSetTransform(a, b, c, d, e, f);
  4990. };
  4991. ctx.resetTransform = function ctxResetTransform() {
  4992. destCtx.resetTransform();
  4993. this.__originalResetTransform();
  4994. };
  4995. ctx.rotate = function ctxRotate(angle) {
  4996. destCtx.rotate(angle);
  4997. this.__originalRotate(angle);
  4998. };
  4999. ctx.clip = function ctxRotate(rule) {
  5000. destCtx.clip(rule);
  5001. this.__originalClip(rule);
  5002. };
  5003. ctx.moveTo = function (x, y) {
  5004. destCtx.moveTo(x, y);
  5005. this.__originalMoveTo(x, y);
  5006. };
  5007. ctx.lineTo = function (x, y) {
  5008. destCtx.lineTo(x, y);
  5009. this.__originalLineTo(x, y);
  5010. };
  5011. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  5012. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  5013. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  5014. };
  5015. ctx.rect = function (x, y, width, height) {
  5016. destCtx.rect(x, y, width, height);
  5017. this.__originalRect(x, y, width, height);
  5018. };
  5019. ctx.closePath = function () {
  5020. destCtx.closePath();
  5021. this.__originalClosePath();
  5022. };
  5023. ctx.beginPath = function () {
  5024. destCtx.beginPath();
  5025. this.__originalBeginPath();
  5026. };
  5027. }
  5028. class CachedCanvases {
  5029. constructor(canvasFactory) {
  5030. this.canvasFactory = canvasFactory;
  5031. this.cache = Object.create(null);
  5032. }
  5033. getCanvas(id, width, height) {
  5034. let canvasEntry;
  5035. if (this.cache[id] !== undefined) {
  5036. canvasEntry = this.cache[id];
  5037. this.canvasFactory.reset(canvasEntry, width, height);
  5038. } else {
  5039. canvasEntry = this.canvasFactory.create(width, height);
  5040. this.cache[id] = canvasEntry;
  5041. }
  5042. return canvasEntry;
  5043. }
  5044. delete(id) {
  5045. delete this.cache[id];
  5046. }
  5047. clear() {
  5048. for (const id in this.cache) {
  5049. const canvasEntry = this.cache[id];
  5050. this.canvasFactory.destroy(canvasEntry);
  5051. delete this.cache[id];
  5052. }
  5053. }
  5054. }
  5055. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  5056. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  5057. if (b === 0 && c === 0) {
  5058. const tlX = destX * a + tx;
  5059. const rTlX = Math.round(tlX);
  5060. const tlY = destY * d + ty;
  5061. const rTlY = Math.round(tlY);
  5062. const brX = (destX + destW) * a + tx;
  5063. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5064. const brY = (destY + destH) * d + ty;
  5065. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5066. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  5067. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  5068. ctx.setTransform(a, b, c, d, tx, ty);
  5069. return [rWidth, rHeight];
  5070. }
  5071. if (a === 0 && d === 0) {
  5072. const tlX = destY * c + tx;
  5073. const rTlX = Math.round(tlX);
  5074. const tlY = destX * b + ty;
  5075. const rTlY = Math.round(tlY);
  5076. const brX = (destY + destH) * c + tx;
  5077. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5078. const brY = (destX + destW) * b + ty;
  5079. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5080. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  5081. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  5082. ctx.setTransform(a, b, c, d, tx, ty);
  5083. return [rHeight, rWidth];
  5084. }
  5085. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  5086. const scaleX = Math.hypot(a, b);
  5087. const scaleY = Math.hypot(c, d);
  5088. return [scaleX * destW, scaleY * destH];
  5089. }
  5090. function compileType3Glyph(imgData) {
  5091. const {
  5092. width,
  5093. height
  5094. } = imgData;
  5095. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  5096. return null;
  5097. }
  5098. const POINT_TO_PROCESS_LIMIT = 1000;
  5099. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  5100. const width1 = width + 1;
  5101. let points = new Uint8Array(width1 * (height + 1));
  5102. let i, j, j0;
  5103. const lineSize = width + 7 & ~7;
  5104. let data = new Uint8Array(lineSize * height),
  5105. pos = 0;
  5106. for (const elem of imgData.data) {
  5107. let mask = 128;
  5108. while (mask > 0) {
  5109. data[pos++] = elem & mask ? 0 : 255;
  5110. mask >>= 1;
  5111. }
  5112. }
  5113. let count = 0;
  5114. pos = 0;
  5115. if (data[pos] !== 0) {
  5116. points[0] = 1;
  5117. ++count;
  5118. }
  5119. for (j = 1; j < width; j++) {
  5120. if (data[pos] !== data[pos + 1]) {
  5121. points[j] = data[pos] ? 2 : 1;
  5122. ++count;
  5123. }
  5124. pos++;
  5125. }
  5126. if (data[pos] !== 0) {
  5127. points[j] = 2;
  5128. ++count;
  5129. }
  5130. for (i = 1; i < height; i++) {
  5131. pos = i * lineSize;
  5132. j0 = i * width1;
  5133. if (data[pos - lineSize] !== data[pos]) {
  5134. points[j0] = data[pos] ? 1 : 8;
  5135. ++count;
  5136. }
  5137. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5138. for (j = 1; j < width; j++) {
  5139. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  5140. if (POINT_TYPES[sum]) {
  5141. points[j0 + j] = POINT_TYPES[sum];
  5142. ++count;
  5143. }
  5144. pos++;
  5145. }
  5146. if (data[pos - lineSize] !== data[pos]) {
  5147. points[j0 + j] = data[pos] ? 2 : 4;
  5148. ++count;
  5149. }
  5150. if (count > POINT_TO_PROCESS_LIMIT) {
  5151. return null;
  5152. }
  5153. }
  5154. pos = lineSize * (height - 1);
  5155. j0 = i * width1;
  5156. if (data[pos] !== 0) {
  5157. points[j0] = 8;
  5158. ++count;
  5159. }
  5160. for (j = 1; j < width; j++) {
  5161. if (data[pos] !== data[pos + 1]) {
  5162. points[j0 + j] = data[pos] ? 4 : 8;
  5163. ++count;
  5164. }
  5165. pos++;
  5166. }
  5167. if (data[pos] !== 0) {
  5168. points[j0 + j] = 4;
  5169. ++count;
  5170. }
  5171. if (count > POINT_TO_PROCESS_LIMIT) {
  5172. return null;
  5173. }
  5174. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5175. const path = new Path2D();
  5176. for (i = 0; count && i <= height; i++) {
  5177. let p = i * width1;
  5178. const end = p + width;
  5179. while (p < end && !points[p]) {
  5180. p++;
  5181. }
  5182. if (p === end) {
  5183. continue;
  5184. }
  5185. path.moveTo(p % width1, i);
  5186. const p0 = p;
  5187. let type = points[p];
  5188. do {
  5189. const step = steps[type];
  5190. do {
  5191. p += step;
  5192. } while (!points[p]);
  5193. const pp = points[p];
  5194. if (pp !== 5 && pp !== 10) {
  5195. type = pp;
  5196. points[p] = 0;
  5197. } else {
  5198. type = pp & 0x33 * type >> 4;
  5199. points[p] &= type >> 2 | type << 2;
  5200. }
  5201. path.lineTo(p % width1, p / width1 | 0);
  5202. if (!points[p]) {
  5203. --count;
  5204. }
  5205. } while (p0 !== p);
  5206. --i;
  5207. }
  5208. data = null;
  5209. points = null;
  5210. const drawOutline = function (c) {
  5211. c.save();
  5212. c.scale(1 / width, -1 / height);
  5213. c.translate(0, -height);
  5214. c.fill(path);
  5215. c.beginPath();
  5216. c.restore();
  5217. };
  5218. return drawOutline;
  5219. }
  5220. class CanvasExtraState {
  5221. constructor(width, height) {
  5222. this.alphaIsShape = false;
  5223. this.fontSize = 0;
  5224. this.fontSizeScale = 1;
  5225. this.textMatrix = _util.IDENTITY_MATRIX;
  5226. this.textMatrixScale = 1;
  5227. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  5228. this.leading = 0;
  5229. this.x = 0;
  5230. this.y = 0;
  5231. this.lineX = 0;
  5232. this.lineY = 0;
  5233. this.charSpacing = 0;
  5234. this.wordSpacing = 0;
  5235. this.textHScale = 1;
  5236. this.textRenderingMode = _util.TextRenderingMode.FILL;
  5237. this.textRise = 0;
  5238. this.fillColor = "#000000";
  5239. this.strokeColor = "#000000";
  5240. this.patternFill = false;
  5241. this.fillAlpha = 1;
  5242. this.strokeAlpha = 1;
  5243. this.lineWidth = 1;
  5244. this.activeSMask = null;
  5245. this.transferMaps = null;
  5246. this.startNewPathAndClipBox([0, 0, width, height]);
  5247. }
  5248. clone() {
  5249. const clone = Object.create(this);
  5250. clone.clipBox = this.clipBox.slice();
  5251. return clone;
  5252. }
  5253. setCurrentPoint(x, y) {
  5254. this.x = x;
  5255. this.y = y;
  5256. }
  5257. updatePathMinMax(transform, x, y) {
  5258. [x, y] = _util.Util.applyTransform([x, y], transform);
  5259. this.minX = Math.min(this.minX, x);
  5260. this.minY = Math.min(this.minY, y);
  5261. this.maxX = Math.max(this.maxX, x);
  5262. this.maxY = Math.max(this.maxY, y);
  5263. }
  5264. updateRectMinMax(transform, rect) {
  5265. const p1 = _util.Util.applyTransform(rect, transform);
  5266. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  5267. this.minX = Math.min(this.minX, p1[0], p2[0]);
  5268. this.minY = Math.min(this.minY, p1[1], p2[1]);
  5269. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  5270. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  5271. }
  5272. updateScalingPathMinMax(transform, minMax) {
  5273. _util.Util.scaleMinMax(transform, minMax);
  5274. this.minX = Math.min(this.minX, minMax[0]);
  5275. this.maxX = Math.max(this.maxX, minMax[1]);
  5276. this.minY = Math.min(this.minY, minMax[2]);
  5277. this.maxY = Math.max(this.maxY, minMax[3]);
  5278. }
  5279. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  5280. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  5281. if (minMax) {
  5282. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  5283. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  5284. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  5285. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  5286. return;
  5287. }
  5288. this.updateRectMinMax(transform, box);
  5289. }
  5290. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5291. const box = [this.minX, this.minY, this.maxX, this.maxY];
  5292. if (pathType === _pattern_helper.PathType.STROKE) {
  5293. if (!transform) {
  5294. (0, _util.unreachable)("Stroke bounding box must include transform.");
  5295. }
  5296. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5297. const xStrokePad = scale[0] * this.lineWidth / 2;
  5298. const yStrokePad = scale[1] * this.lineWidth / 2;
  5299. box[0] -= xStrokePad;
  5300. box[1] -= yStrokePad;
  5301. box[2] += xStrokePad;
  5302. box[3] += yStrokePad;
  5303. }
  5304. return box;
  5305. }
  5306. updateClipFromPath() {
  5307. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  5308. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  5309. }
  5310. isEmptyClip() {
  5311. return this.minX === Infinity;
  5312. }
  5313. startNewPathAndClipBox(box) {
  5314. this.clipBox = box;
  5315. this.minX = Infinity;
  5316. this.minY = Infinity;
  5317. this.maxX = 0;
  5318. this.maxY = 0;
  5319. }
  5320. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5321. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  5322. }
  5323. }
  5324. function putBinaryImageData(ctx, imgData, transferMaps = null) {
  5325. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  5326. ctx.putImageData(imgData, 0, 0);
  5327. return;
  5328. }
  5329. const height = imgData.height,
  5330. width = imgData.width;
  5331. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5332. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5333. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5334. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5335. let srcPos = 0,
  5336. destPos;
  5337. const src = imgData.data;
  5338. const dest = chunkImgData.data;
  5339. let i, j, thisChunkHeight, elemsInThisChunk;
  5340. let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  5341. if (transferMaps) {
  5342. switch (transferMaps.length) {
  5343. case 1:
  5344. transferMapRed = transferMaps[0];
  5345. transferMapGreen = transferMaps[0];
  5346. transferMapBlue = transferMaps[0];
  5347. transferMapGray = transferMaps[0];
  5348. break;
  5349. case 4:
  5350. transferMapRed = transferMaps[0];
  5351. transferMapGreen = transferMaps[1];
  5352. transferMapBlue = transferMaps[2];
  5353. transferMapGray = transferMaps[3];
  5354. break;
  5355. }
  5356. }
  5357. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  5358. const srcLength = src.byteLength;
  5359. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  5360. const dest32DataLength = dest32.length;
  5361. const fullSrcDiff = width + 7 >> 3;
  5362. let white = 0xffffffff;
  5363. let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  5364. if (transferMapGray) {
  5365. if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
  5366. [white, black] = [black, white];
  5367. }
  5368. }
  5369. for (i = 0; i < totalChunks; i++) {
  5370. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5371. destPos = 0;
  5372. for (j = 0; j < thisChunkHeight; j++) {
  5373. const srcDiff = srcLength - srcPos;
  5374. let k = 0;
  5375. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  5376. const kEndUnrolled = kEnd & ~7;
  5377. let mask = 0;
  5378. let srcByte = 0;
  5379. for (; k < kEndUnrolled; k += 8) {
  5380. srcByte = src[srcPos++];
  5381. dest32[destPos++] = srcByte & 128 ? white : black;
  5382. dest32[destPos++] = srcByte & 64 ? white : black;
  5383. dest32[destPos++] = srcByte & 32 ? white : black;
  5384. dest32[destPos++] = srcByte & 16 ? white : black;
  5385. dest32[destPos++] = srcByte & 8 ? white : black;
  5386. dest32[destPos++] = srcByte & 4 ? white : black;
  5387. dest32[destPos++] = srcByte & 2 ? white : black;
  5388. dest32[destPos++] = srcByte & 1 ? white : black;
  5389. }
  5390. for (; k < kEnd; k++) {
  5391. if (mask === 0) {
  5392. srcByte = src[srcPos++];
  5393. mask = 128;
  5394. }
  5395. dest32[destPos++] = srcByte & mask ? white : black;
  5396. mask >>= 1;
  5397. }
  5398. }
  5399. while (destPos < dest32DataLength) {
  5400. dest32[destPos++] = 0;
  5401. }
  5402. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5403. }
  5404. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  5405. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5406. j = 0;
  5407. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5408. for (i = 0; i < fullChunks; i++) {
  5409. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5410. srcPos += elemsInThisChunk;
  5411. if (hasTransferMaps) {
  5412. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5413. if (transferMapRed) {
  5414. dest[k + 0] = transferMapRed[dest[k + 0]];
  5415. }
  5416. if (transferMapGreen) {
  5417. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5418. }
  5419. if (transferMapBlue) {
  5420. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5421. }
  5422. }
  5423. }
  5424. ctx.putImageData(chunkImgData, 0, j);
  5425. j += FULL_CHUNK_HEIGHT;
  5426. }
  5427. if (i < totalChunks) {
  5428. elemsInThisChunk = width * partialChunkHeight * 4;
  5429. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5430. if (hasTransferMaps) {
  5431. for (let k = 0; k < elemsInThisChunk; k += 4) {
  5432. if (transferMapRed) {
  5433. dest[k + 0] = transferMapRed[dest[k + 0]];
  5434. }
  5435. if (transferMapGreen) {
  5436. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5437. }
  5438. if (transferMapBlue) {
  5439. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5440. }
  5441. }
  5442. }
  5443. ctx.putImageData(chunkImgData, 0, j);
  5444. }
  5445. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  5446. const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
  5447. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5448. elemsInThisChunk = width * thisChunkHeight;
  5449. for (i = 0; i < totalChunks; i++) {
  5450. if (i >= fullChunks) {
  5451. thisChunkHeight = partialChunkHeight;
  5452. elemsInThisChunk = width * thisChunkHeight;
  5453. }
  5454. destPos = 0;
  5455. for (j = elemsInThisChunk; j--;) {
  5456. dest[destPos++] = src[srcPos++];
  5457. dest[destPos++] = src[srcPos++];
  5458. dest[destPos++] = src[srcPos++];
  5459. dest[destPos++] = 255;
  5460. }
  5461. if (hasTransferMaps) {
  5462. for (let k = 0; k < destPos; k += 4) {
  5463. if (transferMapRed) {
  5464. dest[k + 0] = transferMapRed[dest[k + 0]];
  5465. }
  5466. if (transferMapGreen) {
  5467. dest[k + 1] = transferMapGreen[dest[k + 1]];
  5468. }
  5469. if (transferMapBlue) {
  5470. dest[k + 2] = transferMapBlue[dest[k + 2]];
  5471. }
  5472. }
  5473. }
  5474. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5475. }
  5476. } else {
  5477. throw new Error(`bad image kind: ${imgData.kind}`);
  5478. }
  5479. }
  5480. function putBinaryImageMask(ctx, imgData) {
  5481. if (imgData.bitmap) {
  5482. ctx.drawImage(imgData.bitmap, 0, 0);
  5483. return;
  5484. }
  5485. const height = imgData.height,
  5486. width = imgData.width;
  5487. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5488. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5489. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5490. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5491. let srcPos = 0;
  5492. const src = imgData.data;
  5493. const dest = chunkImgData.data;
  5494. for (let i = 0; i < totalChunks; i++) {
  5495. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5496. ({
  5497. srcPos
  5498. } = (0, _image_utils.applyMaskImageData)({
  5499. src,
  5500. srcPos,
  5501. dest,
  5502. width,
  5503. height: thisChunkHeight
  5504. }));
  5505. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5506. }
  5507. }
  5508. function copyCtxState(sourceCtx, destCtx) {
  5509. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  5510. for (const property of properties) {
  5511. if (sourceCtx[property] !== undefined) {
  5512. destCtx[property] = sourceCtx[property];
  5513. }
  5514. }
  5515. if (sourceCtx.setLineDash !== undefined) {
  5516. destCtx.setLineDash(sourceCtx.getLineDash());
  5517. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5518. }
  5519. }
  5520. function resetCtxToDefault(ctx, foregroundColor) {
  5521. ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  5522. ctx.fillRule = "nonzero";
  5523. ctx.globalAlpha = 1;
  5524. ctx.lineWidth = 1;
  5525. ctx.lineCap = "butt";
  5526. ctx.lineJoin = "miter";
  5527. ctx.miterLimit = 10;
  5528. ctx.globalCompositeOperation = "source-over";
  5529. ctx.font = "10px sans-serif";
  5530. if (ctx.setLineDash !== undefined) {
  5531. ctx.setLineDash([]);
  5532. ctx.lineDashOffset = 0;
  5533. }
  5534. }
  5535. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5536. const length = bytes.length;
  5537. for (let i = 3; i < length; i += 4) {
  5538. const alpha = bytes[i];
  5539. if (alpha === 0) {
  5540. bytes[i - 3] = r0;
  5541. bytes[i - 2] = g0;
  5542. bytes[i - 1] = b0;
  5543. } else if (alpha < 255) {
  5544. const alpha_ = 255 - alpha;
  5545. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  5546. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  5547. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  5548. }
  5549. }
  5550. }
  5551. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5552. const length = maskData.length;
  5553. const scale = 1 / 255;
  5554. for (let i = 3; i < length; i += 4) {
  5555. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5556. layerData[i] = layerData[i] * alpha * scale | 0;
  5557. }
  5558. }
  5559. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5560. const length = maskData.length;
  5561. for (let i = 3; i < length; i += 4) {
  5562. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  5563. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  5564. }
  5565. }
  5566. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  5567. const hasBackdrop = !!backdrop;
  5568. const r0 = hasBackdrop ? backdrop[0] : 0;
  5569. const g0 = hasBackdrop ? backdrop[1] : 0;
  5570. const b0 = hasBackdrop ? backdrop[2] : 0;
  5571. let composeFn;
  5572. if (subtype === "Luminosity") {
  5573. composeFn = composeSMaskLuminosity;
  5574. } else {
  5575. composeFn = composeSMaskAlpha;
  5576. }
  5577. const PIXELS_TO_PROCESS = 1048576;
  5578. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5579. for (let row = 0; row < height; row += chunkSize) {
  5580. const chunkHeight = Math.min(chunkSize, height - row);
  5581. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  5582. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  5583. if (hasBackdrop) {
  5584. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5585. }
  5586. composeFn(maskData.data, layerData.data, transferMap);
  5587. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  5588. }
  5589. }
  5590. function composeSMask(ctx, smask, layerCtx, layerBox) {
  5591. const layerOffsetX = layerBox[0];
  5592. const layerOffsetY = layerBox[1];
  5593. const layerWidth = layerBox[2] - layerOffsetX;
  5594. const layerHeight = layerBox[3] - layerOffsetY;
  5595. if (layerWidth === 0 || layerHeight === 0) {
  5596. return;
  5597. }
  5598. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  5599. ctx.save();
  5600. ctx.globalAlpha = 1;
  5601. ctx.globalCompositeOperation = "source-over";
  5602. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5603. ctx.drawImage(layerCtx.canvas, 0, 0);
  5604. ctx.restore();
  5605. }
  5606. function getImageSmoothingEnabled(transform, interpolate) {
  5607. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5608. scale[0] = Math.fround(scale[0]);
  5609. scale[1] = Math.fround(scale[1]);
  5610. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  5611. if (interpolate !== undefined) {
  5612. return interpolate;
  5613. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  5614. return true;
  5615. }
  5616. return false;
  5617. }
  5618. const LINE_CAP_STYLES = ["butt", "round", "square"];
  5619. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  5620. const NORMAL_CLIP = {};
  5621. const EO_CLIP = {};
  5622. class CanvasGraphics {
  5623. constructor(canvasCtx, commonObjs, objs, canvasFactory, {
  5624. optionalContentConfig,
  5625. markedContentStack = null
  5626. }, annotationCanvasMap, pageColors) {
  5627. this.ctx = canvasCtx;
  5628. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  5629. this.stateStack = [];
  5630. this.pendingClip = null;
  5631. this.pendingEOFill = false;
  5632. this.res = null;
  5633. this.xobjs = null;
  5634. this.commonObjs = commonObjs;
  5635. this.objs = objs;
  5636. this.canvasFactory = canvasFactory;
  5637. this.groupStack = [];
  5638. this.processingType3 = null;
  5639. this.baseTransform = null;
  5640. this.baseTransformStack = [];
  5641. this.groupLevel = 0;
  5642. this.smaskStack = [];
  5643. this.smaskCounter = 0;
  5644. this.tempSMask = null;
  5645. this.suspendedCtx = null;
  5646. this.contentVisible = true;
  5647. this.markedContentStack = markedContentStack || [];
  5648. this.optionalContentConfig = optionalContentConfig;
  5649. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  5650. this.cachedPatterns = new Map();
  5651. this.annotationCanvasMap = annotationCanvasMap;
  5652. this.viewportScale = 1;
  5653. this.outputScaleX = 1;
  5654. this.outputScaleY = 1;
  5655. this.backgroundColor = pageColors?.background || null;
  5656. this.foregroundColor = pageColors?.foreground || null;
  5657. this._cachedScaleForStroking = null;
  5658. this._cachedGetSinglePixelWidth = null;
  5659. this._cachedBitmapsMap = new Map();
  5660. }
  5661. getObject(data, fallback = null) {
  5662. if (typeof data === "string") {
  5663. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  5664. }
  5665. return fallback;
  5666. }
  5667. beginDrawing({
  5668. transform,
  5669. viewport,
  5670. transparency = false,
  5671. background = null
  5672. }) {
  5673. const width = this.ctx.canvas.width;
  5674. const height = this.ctx.canvas.height;
  5675. const defaultBackgroundColor = background || "#ffffff";
  5676. this.ctx.save();
  5677. if (this.foregroundColor && this.backgroundColor) {
  5678. this.ctx.fillStyle = this.foregroundColor;
  5679. const fg = this.foregroundColor = this.ctx.fillStyle;
  5680. this.ctx.fillStyle = this.backgroundColor;
  5681. const bg = this.backgroundColor = this.ctx.fillStyle;
  5682. let isValidDefaultBg = true;
  5683. let defaultBg = defaultBackgroundColor;
  5684. this.ctx.fillStyle = defaultBackgroundColor;
  5685. defaultBg = this.ctx.fillStyle;
  5686. isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
  5687. if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
  5688. this.foregroundColor = this.backgroundColor = null;
  5689. } else {
  5690. const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
  5691. const newComp = x => {
  5692. x /= 255;
  5693. return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  5694. };
  5695. const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
  5696. this.selectColor = (r, g, b) => {
  5697. const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
  5698. return Math.round(lumC) === lumB ? bg : fg;
  5699. };
  5700. }
  5701. }
  5702. this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
  5703. this.ctx.fillRect(0, 0, width, height);
  5704. this.ctx.restore();
  5705. if (transparency) {
  5706. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  5707. this.compositeCtx = this.ctx;
  5708. this.transparentCanvas = transparentCanvas.canvas;
  5709. this.ctx = transparentCanvas.context;
  5710. this.ctx.save();
  5711. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  5712. }
  5713. this.ctx.save();
  5714. resetCtxToDefault(this.ctx, this.foregroundColor);
  5715. if (transform) {
  5716. this.ctx.transform(...transform);
  5717. this.outputScaleX = transform[0];
  5718. this.outputScaleY = transform[0];
  5719. }
  5720. this.ctx.transform(...viewport.transform);
  5721. this.viewportScale = viewport.scale;
  5722. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  5723. }
  5724. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  5725. const argsArray = operatorList.argsArray;
  5726. const fnArray = operatorList.fnArray;
  5727. let i = executionStartIdx || 0;
  5728. const argsArrayLen = argsArray.length;
  5729. if (argsArrayLen === i) {
  5730. return i;
  5731. }
  5732. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  5733. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  5734. let steps = 0;
  5735. const commonObjs = this.commonObjs;
  5736. const objs = this.objs;
  5737. let fnId;
  5738. while (true) {
  5739. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  5740. stepper.breakIt(i, continueCallback);
  5741. return i;
  5742. }
  5743. fnId = fnArray[i];
  5744. if (fnId !== _util.OPS.dependency) {
  5745. this[fnId].apply(this, argsArray[i]);
  5746. } else {
  5747. for (const depObjId of argsArray[i]) {
  5748. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  5749. if (!objsPool.has(depObjId)) {
  5750. objsPool.get(depObjId, continueCallback);
  5751. return i;
  5752. }
  5753. }
  5754. }
  5755. i++;
  5756. if (i === argsArrayLen) {
  5757. return i;
  5758. }
  5759. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  5760. if (Date.now() > endTime) {
  5761. continueCallback();
  5762. return i;
  5763. }
  5764. steps = 0;
  5765. }
  5766. }
  5767. }
  5768. #restoreInitialState() {
  5769. while (this.stateStack.length || this.inSMaskMode) {
  5770. this.restore();
  5771. }
  5772. this.ctx.restore();
  5773. if (this.transparentCanvas) {
  5774. this.ctx = this.compositeCtx;
  5775. this.ctx.save();
  5776. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5777. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  5778. this.ctx.restore();
  5779. this.transparentCanvas = null;
  5780. }
  5781. }
  5782. endDrawing() {
  5783. this.#restoreInitialState();
  5784. this.cachedCanvases.clear();
  5785. this.cachedPatterns.clear();
  5786. for (const cache of this._cachedBitmapsMap.values()) {
  5787. for (const canvas of cache.values()) {
  5788. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  5789. canvas.width = canvas.height = 0;
  5790. }
  5791. }
  5792. cache.clear();
  5793. }
  5794. this._cachedBitmapsMap.clear();
  5795. }
  5796. _scaleImage(img, inverseTransform) {
  5797. const width = img.width;
  5798. const height = img.height;
  5799. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  5800. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  5801. let paintWidth = width,
  5802. paintHeight = height;
  5803. let tmpCanvasId = "prescale1";
  5804. let tmpCanvas, tmpCtx;
  5805. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5806. let newWidth = paintWidth,
  5807. newHeight = paintHeight;
  5808. if (widthScale > 2 && paintWidth > 1) {
  5809. newWidth = Math.ceil(paintWidth / 2);
  5810. widthScale /= paintWidth / newWidth;
  5811. }
  5812. if (heightScale > 2 && paintHeight > 1) {
  5813. newHeight = Math.ceil(paintHeight / 2);
  5814. heightScale /= paintHeight / newHeight;
  5815. }
  5816. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5817. tmpCtx = tmpCanvas.context;
  5818. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5819. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5820. img = tmpCanvas.canvas;
  5821. paintWidth = newWidth;
  5822. paintHeight = newHeight;
  5823. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5824. }
  5825. return {
  5826. img,
  5827. paintWidth,
  5828. paintHeight
  5829. };
  5830. }
  5831. _createMaskCanvas(img) {
  5832. const ctx = this.ctx;
  5833. const {
  5834. width,
  5835. height
  5836. } = img;
  5837. const fillColor = this.current.fillColor;
  5838. const isPatternFill = this.current.patternFill;
  5839. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5840. let cache, cacheKey, scaled, maskCanvas;
  5841. if ((img.bitmap || img.data) && img.count > 1) {
  5842. const mainKey = img.bitmap || img.data.buffer;
  5843. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  5844. cache = this._cachedBitmapsMap.get(mainKey);
  5845. if (!cache) {
  5846. cache = new Map();
  5847. this._cachedBitmapsMap.set(mainKey, cache);
  5848. }
  5849. const cachedImage = cache.get(cacheKey);
  5850. if (cachedImage && !isPatternFill) {
  5851. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  5852. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  5853. return {
  5854. canvas: cachedImage,
  5855. offsetX,
  5856. offsetY
  5857. };
  5858. }
  5859. scaled = cachedImage;
  5860. }
  5861. if (!scaled) {
  5862. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5863. putBinaryImageMask(maskCanvas.context, img);
  5864. }
  5865. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  5866. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  5867. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  5868. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  5869. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  5870. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  5871. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  5872. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  5873. const fillCtx = fillCanvas.context;
  5874. const offsetX = Math.min(cord1[0], cord2[0]);
  5875. const offsetY = Math.min(cord1[1], cord2[1]);
  5876. fillCtx.translate(-offsetX, -offsetY);
  5877. fillCtx.transform(...maskToCanvas);
  5878. if (!scaled) {
  5879. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  5880. scaled = scaled.img;
  5881. if (cache && isPatternFill) {
  5882. cache.set(cacheKey, scaled);
  5883. }
  5884. }
  5885. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  5886. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  5887. fillCtx.globalCompositeOperation = "source-in";
  5888. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  5889. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  5890. fillCtx.fillRect(0, 0, width, height);
  5891. if (cache && !isPatternFill) {
  5892. this.cachedCanvases.delete("fillCanvas");
  5893. cache.set(cacheKey, fillCanvas.canvas);
  5894. }
  5895. return {
  5896. canvas: fillCanvas.canvas,
  5897. offsetX: Math.round(offsetX),
  5898. offsetY: Math.round(offsetY)
  5899. };
  5900. }
  5901. setLineWidth(width) {
  5902. if (width !== this.current.lineWidth) {
  5903. this._cachedScaleForStroking = null;
  5904. }
  5905. this.current.lineWidth = width;
  5906. this.ctx.lineWidth = width;
  5907. }
  5908. setLineCap(style) {
  5909. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5910. }
  5911. setLineJoin(style) {
  5912. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5913. }
  5914. setMiterLimit(limit) {
  5915. this.ctx.miterLimit = limit;
  5916. }
  5917. setDash(dashArray, dashPhase) {
  5918. const ctx = this.ctx;
  5919. if (ctx.setLineDash !== undefined) {
  5920. ctx.setLineDash(dashArray);
  5921. ctx.lineDashOffset = dashPhase;
  5922. }
  5923. }
  5924. setRenderingIntent(intent) {}
  5925. setFlatness(flatness) {}
  5926. setGState(states) {
  5927. for (const [key, value] of states) {
  5928. switch (key) {
  5929. case "LW":
  5930. this.setLineWidth(value);
  5931. break;
  5932. case "LC":
  5933. this.setLineCap(value);
  5934. break;
  5935. case "LJ":
  5936. this.setLineJoin(value);
  5937. break;
  5938. case "ML":
  5939. this.setMiterLimit(value);
  5940. break;
  5941. case "D":
  5942. this.setDash(value[0], value[1]);
  5943. break;
  5944. case "RI":
  5945. this.setRenderingIntent(value);
  5946. break;
  5947. case "FL":
  5948. this.setFlatness(value);
  5949. break;
  5950. case "Font":
  5951. this.setFont(value[0], value[1]);
  5952. break;
  5953. case "CA":
  5954. this.current.strokeAlpha = value;
  5955. break;
  5956. case "ca":
  5957. this.current.fillAlpha = value;
  5958. this.ctx.globalAlpha = value;
  5959. break;
  5960. case "BM":
  5961. this.ctx.globalCompositeOperation = value;
  5962. break;
  5963. case "SMask":
  5964. this.current.activeSMask = value ? this.tempSMask : null;
  5965. this.tempSMask = null;
  5966. this.checkSMaskState();
  5967. break;
  5968. case "TR":
  5969. this.current.transferMaps = value;
  5970. }
  5971. }
  5972. }
  5973. get inSMaskMode() {
  5974. return !!this.suspendedCtx;
  5975. }
  5976. checkSMaskState() {
  5977. const inSMaskMode = this.inSMaskMode;
  5978. if (this.current.activeSMask && !inSMaskMode) {
  5979. this.beginSMaskMode();
  5980. } else if (!this.current.activeSMask && inSMaskMode) {
  5981. this.endSMaskMode();
  5982. }
  5983. }
  5984. beginSMaskMode() {
  5985. if (this.inSMaskMode) {
  5986. throw new Error("beginSMaskMode called while already in smask mode");
  5987. }
  5988. const drawnWidth = this.ctx.canvas.width;
  5989. const drawnHeight = this.ctx.canvas.height;
  5990. const cacheId = "smaskGroupAt" + this.groupLevel;
  5991. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  5992. this.suspendedCtx = this.ctx;
  5993. this.ctx = scratchCanvas.context;
  5994. const ctx = this.ctx;
  5995. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  5996. copyCtxState(this.suspendedCtx, ctx);
  5997. mirrorContextOperations(ctx, this.suspendedCtx);
  5998. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  5999. }
  6000. endSMaskMode() {
  6001. if (!this.inSMaskMode) {
  6002. throw new Error("endSMaskMode called while not in smask mode");
  6003. }
  6004. this.ctx._removeMirroring();
  6005. copyCtxState(this.ctx, this.suspendedCtx);
  6006. this.ctx = this.suspendedCtx;
  6007. this.suspendedCtx = null;
  6008. }
  6009. compose(dirtyBox) {
  6010. if (!this.current.activeSMask) {
  6011. return;
  6012. }
  6013. if (!dirtyBox) {
  6014. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  6015. } else {
  6016. dirtyBox[0] = Math.floor(dirtyBox[0]);
  6017. dirtyBox[1] = Math.floor(dirtyBox[1]);
  6018. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  6019. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  6020. }
  6021. const smask = this.current.activeSMask;
  6022. const suspendedCtx = this.suspendedCtx;
  6023. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  6024. this.ctx.save();
  6025. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  6026. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  6027. this.ctx.restore();
  6028. }
  6029. save() {
  6030. if (this.inSMaskMode) {
  6031. copyCtxState(this.ctx, this.suspendedCtx);
  6032. this.suspendedCtx.save();
  6033. } else {
  6034. this.ctx.save();
  6035. }
  6036. const old = this.current;
  6037. this.stateStack.push(old);
  6038. this.current = old.clone();
  6039. }
  6040. restore() {
  6041. if (this.stateStack.length === 0 && this.inSMaskMode) {
  6042. this.endSMaskMode();
  6043. }
  6044. if (this.stateStack.length !== 0) {
  6045. this.current = this.stateStack.pop();
  6046. if (this.inSMaskMode) {
  6047. this.suspendedCtx.restore();
  6048. copyCtxState(this.suspendedCtx, this.ctx);
  6049. } else {
  6050. this.ctx.restore();
  6051. }
  6052. this.checkSMaskState();
  6053. this.pendingClip = null;
  6054. this._cachedScaleForStroking = null;
  6055. this._cachedGetSinglePixelWidth = null;
  6056. }
  6057. }
  6058. transform(a, b, c, d, e, f) {
  6059. this.ctx.transform(a, b, c, d, e, f);
  6060. this._cachedScaleForStroking = null;
  6061. this._cachedGetSinglePixelWidth = null;
  6062. }
  6063. constructPath(ops, args, minMax) {
  6064. const ctx = this.ctx;
  6065. const current = this.current;
  6066. let x = current.x,
  6067. y = current.y;
  6068. let startX, startY;
  6069. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6070. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  6071. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  6072. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6073. switch (ops[i] | 0) {
  6074. case _util.OPS.rectangle:
  6075. x = args[j++];
  6076. y = args[j++];
  6077. const width = args[j++];
  6078. const height = args[j++];
  6079. const xw = x + width;
  6080. const yh = y + height;
  6081. ctx.moveTo(x, y);
  6082. if (width === 0 || height === 0) {
  6083. ctx.lineTo(xw, yh);
  6084. } else {
  6085. ctx.lineTo(xw, y);
  6086. ctx.lineTo(xw, yh);
  6087. ctx.lineTo(x, yh);
  6088. }
  6089. if (!isScalingMatrix) {
  6090. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  6091. }
  6092. ctx.closePath();
  6093. break;
  6094. case _util.OPS.moveTo:
  6095. x = args[j++];
  6096. y = args[j++];
  6097. ctx.moveTo(x, y);
  6098. if (!isScalingMatrix) {
  6099. current.updatePathMinMax(currentTransform, x, y);
  6100. }
  6101. break;
  6102. case _util.OPS.lineTo:
  6103. x = args[j++];
  6104. y = args[j++];
  6105. ctx.lineTo(x, y);
  6106. if (!isScalingMatrix) {
  6107. current.updatePathMinMax(currentTransform, x, y);
  6108. }
  6109. break;
  6110. case _util.OPS.curveTo:
  6111. startX = x;
  6112. startY = y;
  6113. x = args[j + 4];
  6114. y = args[j + 5];
  6115. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  6116. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  6117. j += 6;
  6118. break;
  6119. case _util.OPS.curveTo2:
  6120. startX = x;
  6121. startY = y;
  6122. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  6123. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  6124. x = args[j + 2];
  6125. y = args[j + 3];
  6126. j += 4;
  6127. break;
  6128. case _util.OPS.curveTo3:
  6129. startX = x;
  6130. startY = y;
  6131. x = args[j + 2];
  6132. y = args[j + 3];
  6133. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6134. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  6135. j += 4;
  6136. break;
  6137. case _util.OPS.closePath:
  6138. ctx.closePath();
  6139. break;
  6140. }
  6141. }
  6142. if (isScalingMatrix) {
  6143. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  6144. }
  6145. current.setCurrentPoint(x, y);
  6146. }
  6147. closePath() {
  6148. this.ctx.closePath();
  6149. }
  6150. stroke(consumePath = true) {
  6151. const ctx = this.ctx;
  6152. const strokeColor = this.current.strokeColor;
  6153. ctx.globalAlpha = this.current.strokeAlpha;
  6154. if (this.contentVisible) {
  6155. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  6156. ctx.save();
  6157. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  6158. this.rescaleAndStroke(false);
  6159. ctx.restore();
  6160. } else {
  6161. this.rescaleAndStroke(true);
  6162. }
  6163. }
  6164. if (consumePath) {
  6165. this.consumePath(this.current.getClippedPathBoundingBox());
  6166. }
  6167. ctx.globalAlpha = this.current.fillAlpha;
  6168. }
  6169. closeStroke() {
  6170. this.closePath();
  6171. this.stroke();
  6172. }
  6173. fill(consumePath = true) {
  6174. const ctx = this.ctx;
  6175. const fillColor = this.current.fillColor;
  6176. const isPatternFill = this.current.patternFill;
  6177. let needRestore = false;
  6178. if (isPatternFill) {
  6179. ctx.save();
  6180. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6181. needRestore = true;
  6182. }
  6183. const intersect = this.current.getClippedPathBoundingBox();
  6184. if (this.contentVisible && intersect !== null) {
  6185. if (this.pendingEOFill) {
  6186. ctx.fill("evenodd");
  6187. this.pendingEOFill = false;
  6188. } else {
  6189. ctx.fill();
  6190. }
  6191. }
  6192. if (needRestore) {
  6193. ctx.restore();
  6194. }
  6195. if (consumePath) {
  6196. this.consumePath(intersect);
  6197. }
  6198. }
  6199. eoFill() {
  6200. this.pendingEOFill = true;
  6201. this.fill();
  6202. }
  6203. fillStroke() {
  6204. this.fill(false);
  6205. this.stroke(false);
  6206. this.consumePath();
  6207. }
  6208. eoFillStroke() {
  6209. this.pendingEOFill = true;
  6210. this.fillStroke();
  6211. }
  6212. closeFillStroke() {
  6213. this.closePath();
  6214. this.fillStroke();
  6215. }
  6216. closeEOFillStroke() {
  6217. this.pendingEOFill = true;
  6218. this.closePath();
  6219. this.fillStroke();
  6220. }
  6221. endPath() {
  6222. this.consumePath();
  6223. }
  6224. clip() {
  6225. this.pendingClip = NORMAL_CLIP;
  6226. }
  6227. eoClip() {
  6228. this.pendingClip = EO_CLIP;
  6229. }
  6230. beginText() {
  6231. this.current.textMatrix = _util.IDENTITY_MATRIX;
  6232. this.current.textMatrixScale = 1;
  6233. this.current.x = this.current.lineX = 0;
  6234. this.current.y = this.current.lineY = 0;
  6235. }
  6236. endText() {
  6237. const paths = this.pendingTextPaths;
  6238. const ctx = this.ctx;
  6239. if (paths === undefined) {
  6240. ctx.beginPath();
  6241. return;
  6242. }
  6243. ctx.save();
  6244. ctx.beginPath();
  6245. for (const path of paths) {
  6246. ctx.setTransform(...path.transform);
  6247. ctx.translate(path.x, path.y);
  6248. path.addToPath(ctx, path.fontSize);
  6249. }
  6250. ctx.restore();
  6251. ctx.clip();
  6252. ctx.beginPath();
  6253. delete this.pendingTextPaths;
  6254. }
  6255. setCharSpacing(spacing) {
  6256. this.current.charSpacing = spacing;
  6257. }
  6258. setWordSpacing(spacing) {
  6259. this.current.wordSpacing = spacing;
  6260. }
  6261. setHScale(scale) {
  6262. this.current.textHScale = scale / 100;
  6263. }
  6264. setLeading(leading) {
  6265. this.current.leading = -leading;
  6266. }
  6267. setFont(fontRefName, size) {
  6268. const fontObj = this.commonObjs.get(fontRefName);
  6269. const current = this.current;
  6270. if (!fontObj) {
  6271. throw new Error(`Can't find font for ${fontRefName}`);
  6272. }
  6273. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6274. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6275. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  6276. }
  6277. if (size < 0) {
  6278. size = -size;
  6279. current.fontDirection = -1;
  6280. } else {
  6281. current.fontDirection = 1;
  6282. }
  6283. this.current.font = fontObj;
  6284. this.current.fontSize = size;
  6285. if (fontObj.isType3Font) {
  6286. return;
  6287. }
  6288. const name = fontObj.loadedName || "sans-serif";
  6289. let bold = "normal";
  6290. if (fontObj.black) {
  6291. bold = "900";
  6292. } else if (fontObj.bold) {
  6293. bold = "bold";
  6294. }
  6295. const italic = fontObj.italic ? "italic" : "normal";
  6296. const typeface = `"${name}", ${fontObj.fallbackName}`;
  6297. let browserFontSize = size;
  6298. if (size < MIN_FONT_SIZE) {
  6299. browserFontSize = MIN_FONT_SIZE;
  6300. } else if (size > MAX_FONT_SIZE) {
  6301. browserFontSize = MAX_FONT_SIZE;
  6302. }
  6303. this.current.fontSizeScale = size / browserFontSize;
  6304. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  6305. }
  6306. setTextRenderingMode(mode) {
  6307. this.current.textRenderingMode = mode;
  6308. }
  6309. setTextRise(rise) {
  6310. this.current.textRise = rise;
  6311. }
  6312. moveText(x, y) {
  6313. this.current.x = this.current.lineX += x;
  6314. this.current.y = this.current.lineY += y;
  6315. }
  6316. setLeadingMoveText(x, y) {
  6317. this.setLeading(-y);
  6318. this.moveText(x, y);
  6319. }
  6320. setTextMatrix(a, b, c, d, e, f) {
  6321. this.current.textMatrix = [a, b, c, d, e, f];
  6322. this.current.textMatrixScale = Math.hypot(a, b);
  6323. this.current.x = this.current.lineX = 0;
  6324. this.current.y = this.current.lineY = 0;
  6325. }
  6326. nextLine() {
  6327. this.moveText(0, this.current.leading);
  6328. }
  6329. paintChar(character, x, y, patternTransform) {
  6330. const ctx = this.ctx;
  6331. const current = this.current;
  6332. const font = current.font;
  6333. const textRenderingMode = current.textRenderingMode;
  6334. const fontSize = current.fontSize / current.fontSizeScale;
  6335. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6336. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  6337. const patternFill = current.patternFill && !font.missingFile;
  6338. let addToPath;
  6339. if (font.disableFontFace || isAddToPathSet || patternFill) {
  6340. addToPath = font.getPathGenerator(this.commonObjs, character);
  6341. }
  6342. if (font.disableFontFace || patternFill) {
  6343. ctx.save();
  6344. ctx.translate(x, y);
  6345. ctx.beginPath();
  6346. addToPath(ctx, fontSize);
  6347. if (patternTransform) {
  6348. ctx.setTransform(...patternTransform);
  6349. }
  6350. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6351. ctx.fill();
  6352. }
  6353. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6354. ctx.stroke();
  6355. }
  6356. ctx.restore();
  6357. } else {
  6358. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6359. ctx.fillText(character, x, y);
  6360. }
  6361. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6362. ctx.strokeText(character, x, y);
  6363. }
  6364. }
  6365. if (isAddToPathSet) {
  6366. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6367. paths.push({
  6368. transform: (0, _display_utils.getCurrentTransform)(ctx),
  6369. x,
  6370. y,
  6371. fontSize,
  6372. addToPath
  6373. });
  6374. }
  6375. }
  6376. get isFontSubpixelAAEnabled() {
  6377. const {
  6378. context: ctx
  6379. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  6380. ctx.scale(1.5, 1);
  6381. ctx.fillText("I", 0, 10);
  6382. const data = ctx.getImageData(0, 0, 10, 10).data;
  6383. let enabled = false;
  6384. for (let i = 3; i < data.length; i += 4) {
  6385. if (data[i] > 0 && data[i] < 255) {
  6386. enabled = true;
  6387. break;
  6388. }
  6389. }
  6390. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  6391. }
  6392. showText(glyphs) {
  6393. const current = this.current;
  6394. const font = current.font;
  6395. if (font.isType3Font) {
  6396. return this.showType3Text(glyphs);
  6397. }
  6398. const fontSize = current.fontSize;
  6399. if (fontSize === 0) {
  6400. return undefined;
  6401. }
  6402. const ctx = this.ctx;
  6403. const fontSizeScale = current.fontSizeScale;
  6404. const charSpacing = current.charSpacing;
  6405. const wordSpacing = current.wordSpacing;
  6406. const fontDirection = current.fontDirection;
  6407. const textHScale = current.textHScale * fontDirection;
  6408. const glyphsLength = glyphs.length;
  6409. const vertical = font.vertical;
  6410. const spacingDir = vertical ? 1 : -1;
  6411. const defaultVMetrics = font.defaultVMetrics;
  6412. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  6413. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  6414. ctx.save();
  6415. ctx.transform(...current.textMatrix);
  6416. ctx.translate(current.x, current.y + current.textRise);
  6417. if (fontDirection > 0) {
  6418. ctx.scale(textHScale, -1);
  6419. } else {
  6420. ctx.scale(textHScale, 1);
  6421. }
  6422. let patternTransform;
  6423. if (current.patternFill) {
  6424. ctx.save();
  6425. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6426. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6427. ctx.restore();
  6428. ctx.fillStyle = pattern;
  6429. }
  6430. let lineWidth = current.lineWidth;
  6431. const scale = current.textMatrixScale;
  6432. if (scale === 0 || lineWidth === 0) {
  6433. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6434. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6435. lineWidth = this.getSinglePixelWidth();
  6436. }
  6437. } else {
  6438. lineWidth /= scale;
  6439. }
  6440. if (fontSizeScale !== 1.0) {
  6441. ctx.scale(fontSizeScale, fontSizeScale);
  6442. lineWidth /= fontSizeScale;
  6443. }
  6444. ctx.lineWidth = lineWidth;
  6445. if (font.isInvalidPDFjsFont) {
  6446. const chars = [];
  6447. let width = 0;
  6448. for (const glyph of glyphs) {
  6449. chars.push(glyph.unicode);
  6450. width += glyph.width;
  6451. }
  6452. ctx.fillText(chars.join(""), 0, 0);
  6453. current.x += width * widthAdvanceScale * textHScale;
  6454. ctx.restore();
  6455. this.compose();
  6456. return undefined;
  6457. }
  6458. let x = 0,
  6459. i;
  6460. for (i = 0; i < glyphsLength; ++i) {
  6461. const glyph = glyphs[i];
  6462. if (typeof glyph === "number") {
  6463. x += spacingDir * glyph * fontSize / 1000;
  6464. continue;
  6465. }
  6466. let restoreNeeded = false;
  6467. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6468. const character = glyph.fontChar;
  6469. const accent = glyph.accent;
  6470. let scaledX, scaledY;
  6471. let width = glyph.width;
  6472. if (vertical) {
  6473. const vmetric = glyph.vmetric || defaultVMetrics;
  6474. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  6475. const vy = vmetric[2] * widthAdvanceScale;
  6476. width = vmetric ? -vmetric[0] : width;
  6477. scaledX = vx / fontSizeScale;
  6478. scaledY = (x + vy) / fontSizeScale;
  6479. } else {
  6480. scaledX = x / fontSizeScale;
  6481. scaledY = 0;
  6482. }
  6483. if (font.remeasure && width > 0) {
  6484. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6485. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6486. const characterScaleX = width / measuredWidth;
  6487. restoreNeeded = true;
  6488. ctx.save();
  6489. ctx.scale(characterScaleX, 1);
  6490. scaledX /= characterScaleX;
  6491. } else if (width !== measuredWidth) {
  6492. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6493. }
  6494. }
  6495. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  6496. if (simpleFillText && !accent) {
  6497. ctx.fillText(character, scaledX, scaledY);
  6498. } else {
  6499. this.paintChar(character, scaledX, scaledY, patternTransform);
  6500. if (accent) {
  6501. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  6502. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  6503. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  6504. }
  6505. }
  6506. }
  6507. let charWidth;
  6508. if (vertical) {
  6509. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  6510. } else {
  6511. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6512. }
  6513. x += charWidth;
  6514. if (restoreNeeded) {
  6515. ctx.restore();
  6516. }
  6517. }
  6518. if (vertical) {
  6519. current.y -= x;
  6520. } else {
  6521. current.x += x * textHScale;
  6522. }
  6523. ctx.restore();
  6524. this.compose();
  6525. return undefined;
  6526. }
  6527. showType3Text(glyphs) {
  6528. const ctx = this.ctx;
  6529. const current = this.current;
  6530. const font = current.font;
  6531. const fontSize = current.fontSize;
  6532. const fontDirection = current.fontDirection;
  6533. const spacingDir = font.vertical ? 1 : -1;
  6534. const charSpacing = current.charSpacing;
  6535. const wordSpacing = current.wordSpacing;
  6536. const textHScale = current.textHScale * fontDirection;
  6537. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6538. const glyphsLength = glyphs.length;
  6539. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  6540. let i, glyph, width, spacingLength;
  6541. if (isTextInvisible || fontSize === 0) {
  6542. return;
  6543. }
  6544. this._cachedScaleForStroking = null;
  6545. this._cachedGetSinglePixelWidth = null;
  6546. ctx.save();
  6547. ctx.transform(...current.textMatrix);
  6548. ctx.translate(current.x, current.y);
  6549. ctx.scale(textHScale, fontDirection);
  6550. for (i = 0; i < glyphsLength; ++i) {
  6551. glyph = glyphs[i];
  6552. if (typeof glyph === "number") {
  6553. spacingLength = spacingDir * glyph * fontSize / 1000;
  6554. this.ctx.translate(spacingLength, 0);
  6555. current.x += spacingLength * textHScale;
  6556. continue;
  6557. }
  6558. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6559. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  6560. if (!operatorList) {
  6561. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  6562. continue;
  6563. }
  6564. if (this.contentVisible) {
  6565. this.processingType3 = glyph;
  6566. this.save();
  6567. ctx.scale(fontSize, fontSize);
  6568. ctx.transform(...fontMatrix);
  6569. this.executeOperatorList(operatorList);
  6570. this.restore();
  6571. }
  6572. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  6573. width = transformed[0] * fontSize + spacing;
  6574. ctx.translate(width, 0);
  6575. current.x += width * textHScale;
  6576. }
  6577. ctx.restore();
  6578. this.processingType3 = null;
  6579. }
  6580. setCharWidth(xWidth, yWidth) {}
  6581. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  6582. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6583. this.ctx.clip();
  6584. this.endPath();
  6585. }
  6586. getColorN_Pattern(IR) {
  6587. let pattern;
  6588. if (IR[0] === "TilingPattern") {
  6589. const color = IR[1];
  6590. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  6591. const canvasGraphicsFactory = {
  6592. createCanvasGraphics: ctx => {
  6593. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
  6594. optionalContentConfig: this.optionalContentConfig,
  6595. markedContentStack: this.markedContentStack
  6596. });
  6597. }
  6598. };
  6599. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  6600. } else {
  6601. pattern = this._getPattern(IR[1], IR[2]);
  6602. }
  6603. return pattern;
  6604. }
  6605. setStrokeColorN() {
  6606. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6607. }
  6608. setFillColorN() {
  6609. this.current.fillColor = this.getColorN_Pattern(arguments);
  6610. this.current.patternFill = true;
  6611. }
  6612. setStrokeRGBColor(r, g, b) {
  6613. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6614. this.ctx.strokeStyle = color;
  6615. this.current.strokeColor = color;
  6616. }
  6617. setFillRGBColor(r, g, b) {
  6618. const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
  6619. this.ctx.fillStyle = color;
  6620. this.current.fillColor = color;
  6621. this.current.patternFill = false;
  6622. }
  6623. _getPattern(objId, matrix = null) {
  6624. let pattern;
  6625. if (this.cachedPatterns.has(objId)) {
  6626. pattern = this.cachedPatterns.get(objId);
  6627. } else {
  6628. pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
  6629. this.cachedPatterns.set(objId, pattern);
  6630. }
  6631. if (matrix) {
  6632. pattern.matrix = matrix;
  6633. }
  6634. return pattern;
  6635. }
  6636. shadingFill(objId) {
  6637. if (!this.contentVisible) {
  6638. return;
  6639. }
  6640. const ctx = this.ctx;
  6641. this.save();
  6642. const pattern = this._getPattern(objId);
  6643. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  6644. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  6645. if (inv) {
  6646. const canvas = ctx.canvas;
  6647. const width = canvas.width;
  6648. const height = canvas.height;
  6649. const bl = _util.Util.applyTransform([0, 0], inv);
  6650. const br = _util.Util.applyTransform([0, height], inv);
  6651. const ul = _util.Util.applyTransform([width, 0], inv);
  6652. const ur = _util.Util.applyTransform([width, height], inv);
  6653. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6654. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6655. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6656. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6657. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6658. } else {
  6659. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6660. }
  6661. this.compose(this.current.getClippedPathBoundingBox());
  6662. this.restore();
  6663. }
  6664. beginInlineImage() {
  6665. (0, _util.unreachable)("Should not call beginInlineImage");
  6666. }
  6667. beginImageData() {
  6668. (0, _util.unreachable)("Should not call beginImageData");
  6669. }
  6670. paintFormXObjectBegin(matrix, bbox) {
  6671. if (!this.contentVisible) {
  6672. return;
  6673. }
  6674. this.save();
  6675. this.baseTransformStack.push(this.baseTransform);
  6676. if (Array.isArray(matrix) && matrix.length === 6) {
  6677. this.transform(...matrix);
  6678. }
  6679. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  6680. if (bbox) {
  6681. const width = bbox[2] - bbox[0];
  6682. const height = bbox[3] - bbox[1];
  6683. this.ctx.rect(bbox[0], bbox[1], width, height);
  6684. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  6685. this.clip();
  6686. this.endPath();
  6687. }
  6688. }
  6689. paintFormXObjectEnd() {
  6690. if (!this.contentVisible) {
  6691. return;
  6692. }
  6693. this.restore();
  6694. this.baseTransform = this.baseTransformStack.pop();
  6695. }
  6696. beginGroup(group) {
  6697. if (!this.contentVisible) {
  6698. return;
  6699. }
  6700. this.save();
  6701. if (this.inSMaskMode) {
  6702. this.endSMaskMode();
  6703. this.current.activeSMask = null;
  6704. }
  6705. const currentCtx = this.ctx;
  6706. if (!group.isolated) {
  6707. (0, _util.info)("TODO: Support non-isolated groups.");
  6708. }
  6709. if (group.knockout) {
  6710. (0, _util.warn)("Knockout groups not supported.");
  6711. }
  6712. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  6713. if (group.matrix) {
  6714. currentCtx.transform(...group.matrix);
  6715. }
  6716. if (!group.bbox) {
  6717. throw new Error("Bounding box is required.");
  6718. }
  6719. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  6720. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  6721. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6722. const offsetX = Math.floor(bounds[0]);
  6723. const offsetY = Math.floor(bounds[1]);
  6724. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6725. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6726. let scaleX = 1,
  6727. scaleY = 1;
  6728. if (drawnWidth > MAX_GROUP_SIZE) {
  6729. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6730. drawnWidth = MAX_GROUP_SIZE;
  6731. }
  6732. if (drawnHeight > MAX_GROUP_SIZE) {
  6733. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6734. drawnHeight = MAX_GROUP_SIZE;
  6735. }
  6736. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  6737. let cacheId = "groupAt" + this.groupLevel;
  6738. if (group.smask) {
  6739. cacheId += "_smask_" + this.smaskCounter++ % 2;
  6740. }
  6741. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  6742. const groupCtx = scratchCanvas.context;
  6743. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6744. groupCtx.translate(-offsetX, -offsetY);
  6745. groupCtx.transform(...currentTransform);
  6746. if (group.smask) {
  6747. this.smaskStack.push({
  6748. canvas: scratchCanvas.canvas,
  6749. context: groupCtx,
  6750. offsetX,
  6751. offsetY,
  6752. scaleX,
  6753. scaleY,
  6754. subtype: group.smask.subtype,
  6755. backdrop: group.smask.backdrop,
  6756. transferMap: group.smask.transferMap || null,
  6757. startTransformInverse: null
  6758. });
  6759. } else {
  6760. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6761. currentCtx.translate(offsetX, offsetY);
  6762. currentCtx.scale(scaleX, scaleY);
  6763. currentCtx.save();
  6764. }
  6765. copyCtxState(currentCtx, groupCtx);
  6766. this.ctx = groupCtx;
  6767. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6768. this.groupStack.push(currentCtx);
  6769. this.groupLevel++;
  6770. }
  6771. endGroup(group) {
  6772. if (!this.contentVisible) {
  6773. return;
  6774. }
  6775. this.groupLevel--;
  6776. const groupCtx = this.ctx;
  6777. const ctx = this.groupStack.pop();
  6778. this.ctx = ctx;
  6779. this.ctx.imageSmoothingEnabled = false;
  6780. if (group.smask) {
  6781. this.tempSMask = this.smaskStack.pop();
  6782. this.restore();
  6783. } else {
  6784. this.ctx.restore();
  6785. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  6786. this.restore();
  6787. this.ctx.save();
  6788. this.ctx.setTransform(...currentMtx);
  6789. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  6790. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6791. this.ctx.restore();
  6792. this.compose(dirtyBox);
  6793. }
  6794. }
  6795. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  6796. this.#restoreInitialState();
  6797. resetCtxToDefault(this.ctx, this.foregroundColor);
  6798. this.ctx.save();
  6799. this.save();
  6800. if (this.baseTransform) {
  6801. this.ctx.setTransform(...this.baseTransform);
  6802. }
  6803. if (Array.isArray(rect) && rect.length === 4) {
  6804. const width = rect[2] - rect[0];
  6805. const height = rect[3] - rect[1];
  6806. if (hasOwnCanvas && this.annotationCanvasMap) {
  6807. transform = transform.slice();
  6808. transform[4] -= rect[0];
  6809. transform[5] -= rect[1];
  6810. rect = rect.slice();
  6811. rect[0] = rect[1] = 0;
  6812. rect[2] = width;
  6813. rect[3] = height;
  6814. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  6815. const {
  6816. viewportScale
  6817. } = this;
  6818. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  6819. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  6820. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  6821. const {
  6822. canvas,
  6823. context
  6824. } = this.annotationCanvas;
  6825. this.annotationCanvasMap.set(id, canvas);
  6826. this.annotationCanvas.savedCtx = this.ctx;
  6827. this.ctx = context;
  6828. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  6829. resetCtxToDefault(this.ctx, this.foregroundColor);
  6830. } else {
  6831. resetCtxToDefault(this.ctx, this.foregroundColor);
  6832. this.ctx.rect(rect[0], rect[1], width, height);
  6833. this.ctx.clip();
  6834. this.endPath();
  6835. }
  6836. }
  6837. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6838. this.transform(...transform);
  6839. this.transform(...matrix);
  6840. }
  6841. endAnnotation() {
  6842. if (this.annotationCanvas) {
  6843. this.ctx = this.annotationCanvas.savedCtx;
  6844. delete this.annotationCanvas.savedCtx;
  6845. delete this.annotationCanvas;
  6846. }
  6847. }
  6848. paintImageMaskXObject(img) {
  6849. if (!this.contentVisible) {
  6850. return;
  6851. }
  6852. const count = img.count;
  6853. img = this.getObject(img.data, img);
  6854. img.count = count;
  6855. const ctx = this.ctx;
  6856. const glyph = this.processingType3;
  6857. if (glyph) {
  6858. if (glyph.compiled === undefined) {
  6859. glyph.compiled = compileType3Glyph(img);
  6860. }
  6861. if (glyph.compiled) {
  6862. glyph.compiled(ctx);
  6863. return;
  6864. }
  6865. }
  6866. const mask = this._createMaskCanvas(img);
  6867. const maskCanvas = mask.canvas;
  6868. ctx.save();
  6869. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6870. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  6871. ctx.restore();
  6872. this.compose();
  6873. }
  6874. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  6875. if (!this.contentVisible) {
  6876. return;
  6877. }
  6878. img = this.getObject(img.data, img);
  6879. const ctx = this.ctx;
  6880. ctx.save();
  6881. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6882. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  6883. const mask = this._createMaskCanvas(img);
  6884. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  6885. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6886. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  6887. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  6888. ctx.drawImage(mask.canvas, x, y);
  6889. }
  6890. ctx.restore();
  6891. this.compose();
  6892. }
  6893. paintImageMaskXObjectGroup(images) {
  6894. if (!this.contentVisible) {
  6895. return;
  6896. }
  6897. const ctx = this.ctx;
  6898. const fillColor = this.current.fillColor;
  6899. const isPatternFill = this.current.patternFill;
  6900. for (const image of images) {
  6901. const {
  6902. data,
  6903. width,
  6904. height,
  6905. transform
  6906. } = image;
  6907. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  6908. const maskCtx = maskCanvas.context;
  6909. maskCtx.save();
  6910. const img = this.getObject(data, image);
  6911. putBinaryImageMask(maskCtx, img);
  6912. maskCtx.globalCompositeOperation = "source-in";
  6913. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  6914. maskCtx.fillRect(0, 0, width, height);
  6915. maskCtx.restore();
  6916. ctx.save();
  6917. ctx.transform(...transform);
  6918. ctx.scale(1, -1);
  6919. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  6920. ctx.restore();
  6921. }
  6922. this.compose();
  6923. }
  6924. paintImageXObject(objId) {
  6925. if (!this.contentVisible) {
  6926. return;
  6927. }
  6928. const imgData = this.getObject(objId);
  6929. if (!imgData) {
  6930. (0, _util.warn)("Dependent image isn't ready yet");
  6931. return;
  6932. }
  6933. this.paintInlineImageXObject(imgData);
  6934. }
  6935. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  6936. if (!this.contentVisible) {
  6937. return;
  6938. }
  6939. const imgData = this.getObject(objId);
  6940. if (!imgData) {
  6941. (0, _util.warn)("Dependent image isn't ready yet");
  6942. return;
  6943. }
  6944. const width = imgData.width;
  6945. const height = imgData.height;
  6946. const map = [];
  6947. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6948. map.push({
  6949. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  6950. x: 0,
  6951. y: 0,
  6952. w: width,
  6953. h: height
  6954. });
  6955. }
  6956. this.paintInlineImageXObjectGroup(imgData, map);
  6957. }
  6958. paintInlineImageXObject(imgData) {
  6959. if (!this.contentVisible) {
  6960. return;
  6961. }
  6962. const width = imgData.width;
  6963. const height = imgData.height;
  6964. const ctx = this.ctx;
  6965. this.save();
  6966. ctx.scale(1 / width, -1 / height);
  6967. let imgToPaint;
  6968. if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  6969. imgToPaint = imgData;
  6970. } else {
  6971. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  6972. const tmpCtx = tmpCanvas.context;
  6973. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6974. imgToPaint = tmpCanvas.canvas;
  6975. }
  6976. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  6977. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  6978. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  6979. this.compose();
  6980. this.restore();
  6981. }
  6982. paintInlineImageXObjectGroup(imgData, map) {
  6983. if (!this.contentVisible) {
  6984. return;
  6985. }
  6986. const ctx = this.ctx;
  6987. const w = imgData.width;
  6988. const h = imgData.height;
  6989. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  6990. const tmpCtx = tmpCanvas.context;
  6991. putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
  6992. for (const entry of map) {
  6993. ctx.save();
  6994. ctx.transform(...entry.transform);
  6995. ctx.scale(1, -1);
  6996. drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  6997. ctx.restore();
  6998. }
  6999. this.compose();
  7000. }
  7001. paintSolidColorImageMask() {
  7002. if (!this.contentVisible) {
  7003. return;
  7004. }
  7005. this.ctx.fillRect(0, 0, 1, 1);
  7006. this.compose();
  7007. }
  7008. markPoint(tag) {}
  7009. markPointProps(tag, properties) {}
  7010. beginMarkedContent(tag) {
  7011. this.markedContentStack.push({
  7012. visible: true
  7013. });
  7014. }
  7015. beginMarkedContentProps(tag, properties) {
  7016. if (tag === "OC") {
  7017. this.markedContentStack.push({
  7018. visible: this.optionalContentConfig.isVisible(properties)
  7019. });
  7020. } else {
  7021. this.markedContentStack.push({
  7022. visible: true
  7023. });
  7024. }
  7025. this.contentVisible = this.isContentVisible();
  7026. }
  7027. endMarkedContent() {
  7028. this.markedContentStack.pop();
  7029. this.contentVisible = this.isContentVisible();
  7030. }
  7031. beginCompat() {}
  7032. endCompat() {}
  7033. consumePath(clipBox) {
  7034. const isEmpty = this.current.isEmptyClip();
  7035. if (this.pendingClip) {
  7036. this.current.updateClipFromPath();
  7037. }
  7038. if (!this.pendingClip) {
  7039. this.compose(clipBox);
  7040. }
  7041. const ctx = this.ctx;
  7042. if (this.pendingClip) {
  7043. if (!isEmpty) {
  7044. if (this.pendingClip === EO_CLIP) {
  7045. ctx.clip("evenodd");
  7046. } else {
  7047. ctx.clip();
  7048. }
  7049. }
  7050. this.pendingClip = null;
  7051. }
  7052. this.current.startNewPathAndClipBox(this.current.clipBox);
  7053. ctx.beginPath();
  7054. }
  7055. getSinglePixelWidth() {
  7056. if (!this._cachedGetSinglePixelWidth) {
  7057. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  7058. if (m[1] === 0 && m[2] === 0) {
  7059. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  7060. } else {
  7061. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7062. const normX = Math.hypot(m[0], m[2]);
  7063. const normY = Math.hypot(m[1], m[3]);
  7064. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  7065. }
  7066. }
  7067. return this._cachedGetSinglePixelWidth;
  7068. }
  7069. getScaleForStroking() {
  7070. if (!this._cachedScaleForStroking) {
  7071. const {
  7072. lineWidth
  7073. } = this.current;
  7074. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  7075. let scaleX, scaleY;
  7076. if (m[1] === 0 && m[2] === 0) {
  7077. const normX = Math.abs(m[0]);
  7078. const normY = Math.abs(m[3]);
  7079. if (lineWidth === 0) {
  7080. scaleX = 1 / normX;
  7081. scaleY = 1 / normY;
  7082. } else {
  7083. const scaledXLineWidth = normX * lineWidth;
  7084. const scaledYLineWidth = normY * lineWidth;
  7085. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  7086. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  7087. }
  7088. } else {
  7089. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7090. const normX = Math.hypot(m[0], m[1]);
  7091. const normY = Math.hypot(m[2], m[3]);
  7092. if (lineWidth === 0) {
  7093. scaleX = normY / absDet;
  7094. scaleY = normX / absDet;
  7095. } else {
  7096. const baseArea = lineWidth * absDet;
  7097. scaleX = normY > baseArea ? normY / baseArea : 1;
  7098. scaleY = normX > baseArea ? normX / baseArea : 1;
  7099. }
  7100. }
  7101. this._cachedScaleForStroking = [scaleX, scaleY];
  7102. }
  7103. return this._cachedScaleForStroking;
  7104. }
  7105. rescaleAndStroke(saveRestore) {
  7106. const {
  7107. ctx
  7108. } = this;
  7109. const {
  7110. lineWidth
  7111. } = this.current;
  7112. const [scaleX, scaleY] = this.getScaleForStroking();
  7113. ctx.lineWidth = lineWidth || 1;
  7114. if (scaleX === 1 && scaleY === 1) {
  7115. ctx.stroke();
  7116. return;
  7117. }
  7118. let savedMatrix, savedDashes, savedDashOffset;
  7119. if (saveRestore) {
  7120. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  7121. savedDashes = ctx.getLineDash().slice();
  7122. savedDashOffset = ctx.lineDashOffset;
  7123. }
  7124. ctx.scale(scaleX, scaleY);
  7125. const scale = Math.max(scaleX, scaleY);
  7126. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  7127. ctx.lineDashOffset /= scale;
  7128. ctx.stroke();
  7129. if (saveRestore) {
  7130. ctx.setTransform(...savedMatrix);
  7131. ctx.setLineDash(savedDashes);
  7132. ctx.lineDashOffset = savedDashOffset;
  7133. }
  7134. }
  7135. isContentVisible() {
  7136. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  7137. if (!this.markedContentStack[i].visible) {
  7138. return false;
  7139. }
  7140. }
  7141. return true;
  7142. }
  7143. }
  7144. exports.CanvasGraphics = CanvasGraphics;
  7145. for (const op in _util.OPS) {
  7146. if (CanvasGraphics.prototype[op] !== undefined) {
  7147. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  7148. }
  7149. }
  7150. /***/ }),
  7151. /* 12 */
  7152. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7153. Object.defineProperty(exports, "__esModule", ({
  7154. value: true
  7155. }));
  7156. exports.TilingPattern = exports.PathType = void 0;
  7157. exports.getShadingPattern = getShadingPattern;
  7158. var _util = __w_pdfjs_require__(1);
  7159. var _display_utils = __w_pdfjs_require__(6);
  7160. var _is_node = __w_pdfjs_require__(10);
  7161. const PathType = {
  7162. FILL: "Fill",
  7163. STROKE: "Stroke",
  7164. SHADING: "Shading"
  7165. };
  7166. exports.PathType = PathType;
  7167. function applyBoundingBox(ctx, bbox) {
  7168. if (!bbox || _is_node.isNodeJS) {
  7169. return;
  7170. }
  7171. const width = bbox[2] - bbox[0];
  7172. const height = bbox[3] - bbox[1];
  7173. const region = new Path2D();
  7174. region.rect(bbox[0], bbox[1], width, height);
  7175. ctx.clip(region);
  7176. }
  7177. class BaseShadingPattern {
  7178. constructor() {
  7179. if (this.constructor === BaseShadingPattern) {
  7180. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  7181. }
  7182. }
  7183. getPattern() {
  7184. (0, _util.unreachable)("Abstract method `getPattern` called.");
  7185. }
  7186. }
  7187. class RadialAxialShadingPattern extends BaseShadingPattern {
  7188. constructor(IR) {
  7189. super();
  7190. this._type = IR[1];
  7191. this._bbox = IR[2];
  7192. this._colorStops = IR[3];
  7193. this._p0 = IR[4];
  7194. this._p1 = IR[5];
  7195. this._r0 = IR[6];
  7196. this._r1 = IR[7];
  7197. this.matrix = null;
  7198. }
  7199. _createGradient(ctx) {
  7200. let grad;
  7201. if (this._type === "axial") {
  7202. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  7203. } else if (this._type === "radial") {
  7204. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  7205. }
  7206. for (const colorStop of this._colorStops) {
  7207. grad.addColorStop(colorStop[0], colorStop[1]);
  7208. }
  7209. return grad;
  7210. }
  7211. getPattern(ctx, owner, inverse, pathType) {
  7212. let pattern;
  7213. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  7214. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  7215. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  7216. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  7217. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  7218. const tmpCtx = tmpCanvas.context;
  7219. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7220. tmpCtx.beginPath();
  7221. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7222. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  7223. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  7224. tmpCtx.transform(...owner.baseTransform);
  7225. if (this.matrix) {
  7226. tmpCtx.transform(...this.matrix);
  7227. }
  7228. applyBoundingBox(tmpCtx, this._bbox);
  7229. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  7230. tmpCtx.fill();
  7231. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  7232. const domMatrix = new DOMMatrix(inverse);
  7233. pattern.setTransform(domMatrix);
  7234. } else {
  7235. applyBoundingBox(ctx, this._bbox);
  7236. pattern = this._createGradient(ctx);
  7237. }
  7238. return pattern;
  7239. }
  7240. }
  7241. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7242. const coords = context.coords,
  7243. colors = context.colors;
  7244. const bytes = data.data,
  7245. rowSize = data.width * 4;
  7246. let tmp;
  7247. if (coords[p1 + 1] > coords[p2 + 1]) {
  7248. tmp = p1;
  7249. p1 = p2;
  7250. p2 = tmp;
  7251. tmp = c1;
  7252. c1 = c2;
  7253. c2 = tmp;
  7254. }
  7255. if (coords[p2 + 1] > coords[p3 + 1]) {
  7256. tmp = p2;
  7257. p2 = p3;
  7258. p3 = tmp;
  7259. tmp = c2;
  7260. c2 = c3;
  7261. c3 = tmp;
  7262. }
  7263. if (coords[p1 + 1] > coords[p2 + 1]) {
  7264. tmp = p1;
  7265. p1 = p2;
  7266. p2 = tmp;
  7267. tmp = c1;
  7268. c1 = c2;
  7269. c2 = tmp;
  7270. }
  7271. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7272. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7273. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7274. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7275. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7276. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7277. if (y1 >= y3) {
  7278. return;
  7279. }
  7280. const c1r = colors[c1],
  7281. c1g = colors[c1 + 1],
  7282. c1b = colors[c1 + 2];
  7283. const c2r = colors[c2],
  7284. c2g = colors[c2 + 1],
  7285. c2b = colors[c2 + 2];
  7286. const c3r = colors[c3],
  7287. c3g = colors[c3 + 1],
  7288. c3b = colors[c3 + 2];
  7289. const minY = Math.round(y1),
  7290. maxY = Math.round(y3);
  7291. let xa, car, cag, cab;
  7292. let xb, cbr, cbg, cbb;
  7293. for (let y = minY; y <= maxY; y++) {
  7294. if (y < y2) {
  7295. let k;
  7296. if (y < y1) {
  7297. k = 0;
  7298. } else {
  7299. k = (y1 - y) / (y1 - y2);
  7300. }
  7301. xa = x1 - (x1 - x2) * k;
  7302. car = c1r - (c1r - c2r) * k;
  7303. cag = c1g - (c1g - c2g) * k;
  7304. cab = c1b - (c1b - c2b) * k;
  7305. } else {
  7306. let k;
  7307. if (y > y3) {
  7308. k = 1;
  7309. } else if (y2 === y3) {
  7310. k = 0;
  7311. } else {
  7312. k = (y2 - y) / (y2 - y3);
  7313. }
  7314. xa = x2 - (x2 - x3) * k;
  7315. car = c2r - (c2r - c3r) * k;
  7316. cag = c2g - (c2g - c3g) * k;
  7317. cab = c2b - (c2b - c3b) * k;
  7318. }
  7319. let k;
  7320. if (y < y1) {
  7321. k = 0;
  7322. } else if (y > y3) {
  7323. k = 1;
  7324. } else {
  7325. k = (y1 - y) / (y1 - y3);
  7326. }
  7327. xb = x1 - (x1 - x3) * k;
  7328. cbr = c1r - (c1r - c3r) * k;
  7329. cbg = c1g - (c1g - c3g) * k;
  7330. cbb = c1b - (c1b - c3b) * k;
  7331. const x1_ = Math.round(Math.min(xa, xb));
  7332. const x2_ = Math.round(Math.max(xa, xb));
  7333. let j = rowSize * y + x1_ * 4;
  7334. for (let x = x1_; x <= x2_; x++) {
  7335. k = (xa - x) / (xa - xb);
  7336. if (k < 0) {
  7337. k = 0;
  7338. } else if (k > 1) {
  7339. k = 1;
  7340. }
  7341. bytes[j++] = car - (car - cbr) * k | 0;
  7342. bytes[j++] = cag - (cag - cbg) * k | 0;
  7343. bytes[j++] = cab - (cab - cbb) * k | 0;
  7344. bytes[j++] = 255;
  7345. }
  7346. }
  7347. }
  7348. function drawFigure(data, figure, context) {
  7349. const ps = figure.coords;
  7350. const cs = figure.colors;
  7351. let i, ii;
  7352. switch (figure.type) {
  7353. case "lattice":
  7354. const verticesPerRow = figure.verticesPerRow;
  7355. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  7356. const cols = verticesPerRow - 1;
  7357. for (i = 0; i < rows; i++) {
  7358. let q = i * verticesPerRow;
  7359. for (let j = 0; j < cols; j++, q++) {
  7360. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7361. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7362. }
  7363. }
  7364. break;
  7365. case "triangles":
  7366. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7367. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  7368. }
  7369. break;
  7370. default:
  7371. throw new Error("illegal figure");
  7372. }
  7373. }
  7374. class MeshShadingPattern extends BaseShadingPattern {
  7375. constructor(IR) {
  7376. super();
  7377. this._coords = IR[2];
  7378. this._colors = IR[3];
  7379. this._figures = IR[4];
  7380. this._bounds = IR[5];
  7381. this._bbox = IR[7];
  7382. this._background = IR[8];
  7383. this.matrix = null;
  7384. }
  7385. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  7386. const EXPECTED_SCALE = 1.1;
  7387. const MAX_PATTERN_SIZE = 3000;
  7388. const BORDER_SIZE = 2;
  7389. const offsetX = Math.floor(this._bounds[0]);
  7390. const offsetY = Math.floor(this._bounds[1]);
  7391. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  7392. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  7393. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7394. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7395. const scaleX = boundsWidth / width;
  7396. const scaleY = boundsHeight / height;
  7397. const context = {
  7398. coords: this._coords,
  7399. colors: this._colors,
  7400. offsetX: -offsetX,
  7401. offsetY: -offsetY,
  7402. scaleX: 1 / scaleX,
  7403. scaleY: 1 / scaleY
  7404. };
  7405. const paddedWidth = width + BORDER_SIZE * 2;
  7406. const paddedHeight = height + BORDER_SIZE * 2;
  7407. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  7408. const tmpCtx = tmpCanvas.context;
  7409. const data = tmpCtx.createImageData(width, height);
  7410. if (backgroundColor) {
  7411. const bytes = data.data;
  7412. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  7413. bytes[i] = backgroundColor[0];
  7414. bytes[i + 1] = backgroundColor[1];
  7415. bytes[i + 2] = backgroundColor[2];
  7416. bytes[i + 3] = 255;
  7417. }
  7418. }
  7419. for (const figure of this._figures) {
  7420. drawFigure(data, figure, context);
  7421. }
  7422. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  7423. const canvas = tmpCanvas.canvas;
  7424. return {
  7425. canvas,
  7426. offsetX: offsetX - BORDER_SIZE * scaleX,
  7427. offsetY: offsetY - BORDER_SIZE * scaleY,
  7428. scaleX,
  7429. scaleY
  7430. };
  7431. }
  7432. getPattern(ctx, owner, inverse, pathType) {
  7433. applyBoundingBox(ctx, this._bbox);
  7434. let scale;
  7435. if (pathType === PathType.SHADING) {
  7436. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  7437. } else {
  7438. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  7439. if (this.matrix) {
  7440. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7441. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  7442. }
  7443. }
  7444. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  7445. if (pathType !== PathType.SHADING) {
  7446. ctx.setTransform(...owner.baseTransform);
  7447. if (this.matrix) {
  7448. ctx.transform(...this.matrix);
  7449. }
  7450. }
  7451. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7452. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  7453. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  7454. }
  7455. }
  7456. class DummyShadingPattern extends BaseShadingPattern {
  7457. getPattern() {
  7458. return "hotpink";
  7459. }
  7460. }
  7461. function getShadingPattern(IR) {
  7462. switch (IR[0]) {
  7463. case "RadialAxial":
  7464. return new RadialAxialShadingPattern(IR);
  7465. case "Mesh":
  7466. return new MeshShadingPattern(IR);
  7467. case "Dummy":
  7468. return new DummyShadingPattern();
  7469. }
  7470. throw new Error(`Unknown IR type: ${IR[0]}`);
  7471. }
  7472. const PaintType = {
  7473. COLORED: 1,
  7474. UNCOLORED: 2
  7475. };
  7476. class TilingPattern {
  7477. static get MAX_PATTERN_SIZE() {
  7478. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  7479. }
  7480. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  7481. this.operatorList = IR[2];
  7482. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7483. this.bbox = IR[4];
  7484. this.xstep = IR[5];
  7485. this.ystep = IR[6];
  7486. this.paintType = IR[7];
  7487. this.tilingType = IR[8];
  7488. this.color = color;
  7489. this.ctx = ctx;
  7490. this.canvasGraphicsFactory = canvasGraphicsFactory;
  7491. this.baseTransform = baseTransform;
  7492. }
  7493. createPatternCanvas(owner) {
  7494. const operatorList = this.operatorList;
  7495. const bbox = this.bbox;
  7496. const xstep = this.xstep;
  7497. const ystep = this.ystep;
  7498. const paintType = this.paintType;
  7499. const tilingType = this.tilingType;
  7500. const color = this.color;
  7501. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  7502. (0, _util.info)("TilingType: " + tilingType);
  7503. const x0 = bbox[0],
  7504. y0 = bbox[1],
  7505. x1 = bbox[2],
  7506. y1 = bbox[3];
  7507. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7508. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  7509. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  7510. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  7511. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  7512. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  7513. const tmpCtx = tmpCanvas.context;
  7514. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  7515. graphics.groupLevel = owner.groupLevel;
  7516. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  7517. let adjustedX0 = x0;
  7518. let adjustedY0 = y0;
  7519. let adjustedX1 = x1;
  7520. let adjustedY1 = y1;
  7521. if (x0 < 0) {
  7522. adjustedX0 = 0;
  7523. adjustedX1 += Math.abs(x0);
  7524. }
  7525. if (y0 < 0) {
  7526. adjustedY0 = 0;
  7527. adjustedY1 += Math.abs(y0);
  7528. }
  7529. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  7530. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  7531. tmpCtx.save();
  7532. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  7533. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  7534. graphics.executeOperatorList(operatorList);
  7535. graphics.endDrawing();
  7536. return {
  7537. canvas: tmpCanvas.canvas,
  7538. scaleX: dimx.scale,
  7539. scaleY: dimy.scale,
  7540. offsetX: adjustedX0,
  7541. offsetY: adjustedY0
  7542. };
  7543. }
  7544. getSizeAndScale(step, realOutputSize, scale) {
  7545. step = Math.abs(step);
  7546. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  7547. let size = Math.ceil(step * scale);
  7548. if (size >= maxSize) {
  7549. size = maxSize;
  7550. } else {
  7551. scale = size / step;
  7552. }
  7553. return {
  7554. scale,
  7555. size
  7556. };
  7557. }
  7558. clipBbox(graphics, x0, y0, x1, y1) {
  7559. const bboxWidth = x1 - x0;
  7560. const bboxHeight = y1 - y0;
  7561. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  7562. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  7563. graphics.clip();
  7564. graphics.endPath();
  7565. }
  7566. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  7567. const context = graphics.ctx,
  7568. current = graphics.current;
  7569. switch (paintType) {
  7570. case PaintType.COLORED:
  7571. const ctx = this.ctx;
  7572. context.fillStyle = ctx.fillStyle;
  7573. context.strokeStyle = ctx.strokeStyle;
  7574. current.fillColor = ctx.fillStyle;
  7575. current.strokeColor = ctx.strokeStyle;
  7576. break;
  7577. case PaintType.UNCOLORED:
  7578. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  7579. context.fillStyle = cssColor;
  7580. context.strokeStyle = cssColor;
  7581. current.fillColor = cssColor;
  7582. current.strokeColor = cssColor;
  7583. break;
  7584. default:
  7585. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  7586. }
  7587. }
  7588. getPattern(ctx, owner, inverse, pathType) {
  7589. let matrix = inverse;
  7590. if (pathType !== PathType.SHADING) {
  7591. matrix = _util.Util.transform(matrix, owner.baseTransform);
  7592. if (this.matrix) {
  7593. matrix = _util.Util.transform(matrix, this.matrix);
  7594. }
  7595. }
  7596. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  7597. let domMatrix = new DOMMatrix(matrix);
  7598. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7599. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  7600. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  7601. pattern.setTransform(domMatrix);
  7602. return pattern;
  7603. }
  7604. }
  7605. exports.TilingPattern = TilingPattern;
  7606. /***/ }),
  7607. /* 13 */
  7608. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7609. Object.defineProperty(exports, "__esModule", ({
  7610. value: true
  7611. }));
  7612. exports.applyMaskImageData = applyMaskImageData;
  7613. var _util = __w_pdfjs_require__(1);
  7614. function applyMaskImageData({
  7615. src,
  7616. srcPos = 0,
  7617. dest,
  7618. destPos = 0,
  7619. width,
  7620. height,
  7621. inverseDecode = false
  7622. }) {
  7623. const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7624. const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  7625. const widthInSource = width >> 3;
  7626. const widthRemainder = width & 7;
  7627. const srcLength = src.length;
  7628. dest = new Uint32Array(dest.buffer);
  7629. for (let i = 0; i < height; i++) {
  7630. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  7631. const elem = srcPos < srcLength ? src[srcPos] : 255;
  7632. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  7633. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  7634. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  7635. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  7636. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  7637. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  7638. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  7639. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  7640. }
  7641. if (widthRemainder === 0) {
  7642. continue;
  7643. }
  7644. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  7645. for (let j = 0; j < widthRemainder; j++) {
  7646. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  7647. }
  7648. }
  7649. return {
  7650. srcPos,
  7651. destPos
  7652. };
  7653. }
  7654. /***/ }),
  7655. /* 14 */
  7656. /***/ ((__unused_webpack_module, exports) => {
  7657. Object.defineProperty(exports, "__esModule", ({
  7658. value: true
  7659. }));
  7660. exports.GlobalWorkerOptions = void 0;
  7661. const GlobalWorkerOptions = Object.create(null);
  7662. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  7663. GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
  7664. GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
  7665. /***/ }),
  7666. /* 15 */
  7667. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7668. Object.defineProperty(exports, "__esModule", ({
  7669. value: true
  7670. }));
  7671. exports.MessageHandler = void 0;
  7672. var _util = __w_pdfjs_require__(1);
  7673. const CallbackKind = {
  7674. UNKNOWN: 0,
  7675. DATA: 1,
  7676. ERROR: 2
  7677. };
  7678. const StreamKind = {
  7679. UNKNOWN: 0,
  7680. CANCEL: 1,
  7681. CANCEL_COMPLETE: 2,
  7682. CLOSE: 3,
  7683. ENQUEUE: 4,
  7684. ERROR: 5,
  7685. PULL: 6,
  7686. PULL_COMPLETE: 7,
  7687. START_COMPLETE: 8
  7688. };
  7689. function wrapReason(reason) {
  7690. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  7691. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  7692. }
  7693. switch (reason.name) {
  7694. case "AbortException":
  7695. return new _util.AbortException(reason.message);
  7696. case "MissingPDFException":
  7697. return new _util.MissingPDFException(reason.message);
  7698. case "PasswordException":
  7699. return new _util.PasswordException(reason.message, reason.code);
  7700. case "UnexpectedResponseException":
  7701. return new _util.UnexpectedResponseException(reason.message, reason.status);
  7702. case "UnknownErrorException":
  7703. return new _util.UnknownErrorException(reason.message, reason.details);
  7704. default:
  7705. return new _util.UnknownErrorException(reason.message, reason.toString());
  7706. }
  7707. }
  7708. class MessageHandler {
  7709. constructor(sourceName, targetName, comObj) {
  7710. this.sourceName = sourceName;
  7711. this.targetName = targetName;
  7712. this.comObj = comObj;
  7713. this.callbackId = 1;
  7714. this.streamId = 1;
  7715. this.streamSinks = Object.create(null);
  7716. this.streamControllers = Object.create(null);
  7717. this.callbackCapabilities = Object.create(null);
  7718. this.actionHandler = Object.create(null);
  7719. this._onComObjOnMessage = event => {
  7720. const data = event.data;
  7721. if (data.targetName !== this.sourceName) {
  7722. return;
  7723. }
  7724. if (data.stream) {
  7725. this._processStreamMessage(data);
  7726. return;
  7727. }
  7728. if (data.callback) {
  7729. const callbackId = data.callbackId;
  7730. const capability = this.callbackCapabilities[callbackId];
  7731. if (!capability) {
  7732. throw new Error(`Cannot resolve callback ${callbackId}`);
  7733. }
  7734. delete this.callbackCapabilities[callbackId];
  7735. if (data.callback === CallbackKind.DATA) {
  7736. capability.resolve(data.data);
  7737. } else if (data.callback === CallbackKind.ERROR) {
  7738. capability.reject(wrapReason(data.reason));
  7739. } else {
  7740. throw new Error("Unexpected callback case");
  7741. }
  7742. return;
  7743. }
  7744. const action = this.actionHandler[data.action];
  7745. if (!action) {
  7746. throw new Error(`Unknown action from worker: ${data.action}`);
  7747. }
  7748. if (data.callbackId) {
  7749. const cbSourceName = this.sourceName;
  7750. const cbTargetName = data.sourceName;
  7751. new Promise(function (resolve) {
  7752. resolve(action(data.data));
  7753. }).then(function (result) {
  7754. comObj.postMessage({
  7755. sourceName: cbSourceName,
  7756. targetName: cbTargetName,
  7757. callback: CallbackKind.DATA,
  7758. callbackId: data.callbackId,
  7759. data: result
  7760. });
  7761. }, function (reason) {
  7762. comObj.postMessage({
  7763. sourceName: cbSourceName,
  7764. targetName: cbTargetName,
  7765. callback: CallbackKind.ERROR,
  7766. callbackId: data.callbackId,
  7767. reason: wrapReason(reason)
  7768. });
  7769. });
  7770. return;
  7771. }
  7772. if (data.streamId) {
  7773. this._createStreamSink(data);
  7774. return;
  7775. }
  7776. action(data.data);
  7777. };
  7778. comObj.addEventListener("message", this._onComObjOnMessage);
  7779. }
  7780. on(actionName, handler) {
  7781. const ah = this.actionHandler;
  7782. if (ah[actionName]) {
  7783. throw new Error(`There is already an actionName called "${actionName}"`);
  7784. }
  7785. ah[actionName] = handler;
  7786. }
  7787. send(actionName, data, transfers) {
  7788. this.comObj.postMessage({
  7789. sourceName: this.sourceName,
  7790. targetName: this.targetName,
  7791. action: actionName,
  7792. data
  7793. }, transfers);
  7794. }
  7795. sendWithPromise(actionName, data, transfers) {
  7796. const callbackId = this.callbackId++;
  7797. const capability = (0, _util.createPromiseCapability)();
  7798. this.callbackCapabilities[callbackId] = capability;
  7799. try {
  7800. this.comObj.postMessage({
  7801. sourceName: this.sourceName,
  7802. targetName: this.targetName,
  7803. action: actionName,
  7804. callbackId,
  7805. data
  7806. }, transfers);
  7807. } catch (ex) {
  7808. capability.reject(ex);
  7809. }
  7810. return capability.promise;
  7811. }
  7812. sendWithStream(actionName, data, queueingStrategy, transfers) {
  7813. const streamId = this.streamId++,
  7814. sourceName = this.sourceName,
  7815. targetName = this.targetName,
  7816. comObj = this.comObj;
  7817. return new ReadableStream({
  7818. start: controller => {
  7819. const startCapability = (0, _util.createPromiseCapability)();
  7820. this.streamControllers[streamId] = {
  7821. controller,
  7822. startCall: startCapability,
  7823. pullCall: null,
  7824. cancelCall: null,
  7825. isClosed: false
  7826. };
  7827. comObj.postMessage({
  7828. sourceName,
  7829. targetName,
  7830. action: actionName,
  7831. streamId,
  7832. data,
  7833. desiredSize: controller.desiredSize
  7834. }, transfers);
  7835. return startCapability.promise;
  7836. },
  7837. pull: controller => {
  7838. const pullCapability = (0, _util.createPromiseCapability)();
  7839. this.streamControllers[streamId].pullCall = pullCapability;
  7840. comObj.postMessage({
  7841. sourceName,
  7842. targetName,
  7843. stream: StreamKind.PULL,
  7844. streamId,
  7845. desiredSize: controller.desiredSize
  7846. });
  7847. return pullCapability.promise;
  7848. },
  7849. cancel: reason => {
  7850. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  7851. const cancelCapability = (0, _util.createPromiseCapability)();
  7852. this.streamControllers[streamId].cancelCall = cancelCapability;
  7853. this.streamControllers[streamId].isClosed = true;
  7854. comObj.postMessage({
  7855. sourceName,
  7856. targetName,
  7857. stream: StreamKind.CANCEL,
  7858. streamId,
  7859. reason: wrapReason(reason)
  7860. });
  7861. return cancelCapability.promise;
  7862. }
  7863. }, queueingStrategy);
  7864. }
  7865. _createStreamSink(data) {
  7866. const streamId = data.streamId,
  7867. sourceName = this.sourceName,
  7868. targetName = data.sourceName,
  7869. comObj = this.comObj;
  7870. const self = this,
  7871. action = this.actionHandler[data.action];
  7872. const streamSink = {
  7873. enqueue(chunk, size = 1, transfers) {
  7874. if (this.isCancelled) {
  7875. return;
  7876. }
  7877. const lastDesiredSize = this.desiredSize;
  7878. this.desiredSize -= size;
  7879. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  7880. this.sinkCapability = (0, _util.createPromiseCapability)();
  7881. this.ready = this.sinkCapability.promise;
  7882. }
  7883. comObj.postMessage({
  7884. sourceName,
  7885. targetName,
  7886. stream: StreamKind.ENQUEUE,
  7887. streamId,
  7888. chunk
  7889. }, transfers);
  7890. },
  7891. close() {
  7892. if (this.isCancelled) {
  7893. return;
  7894. }
  7895. this.isCancelled = true;
  7896. comObj.postMessage({
  7897. sourceName,
  7898. targetName,
  7899. stream: StreamKind.CLOSE,
  7900. streamId
  7901. });
  7902. delete self.streamSinks[streamId];
  7903. },
  7904. error(reason) {
  7905. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  7906. if (this.isCancelled) {
  7907. return;
  7908. }
  7909. this.isCancelled = true;
  7910. comObj.postMessage({
  7911. sourceName,
  7912. targetName,
  7913. stream: StreamKind.ERROR,
  7914. streamId,
  7915. reason: wrapReason(reason)
  7916. });
  7917. },
  7918. sinkCapability: (0, _util.createPromiseCapability)(),
  7919. onPull: null,
  7920. onCancel: null,
  7921. isCancelled: false,
  7922. desiredSize: data.desiredSize,
  7923. ready: null
  7924. };
  7925. streamSink.sinkCapability.resolve();
  7926. streamSink.ready = streamSink.sinkCapability.promise;
  7927. this.streamSinks[streamId] = streamSink;
  7928. new Promise(function (resolve) {
  7929. resolve(action(data.data, streamSink));
  7930. }).then(function () {
  7931. comObj.postMessage({
  7932. sourceName,
  7933. targetName,
  7934. stream: StreamKind.START_COMPLETE,
  7935. streamId,
  7936. success: true
  7937. });
  7938. }, function (reason) {
  7939. comObj.postMessage({
  7940. sourceName,
  7941. targetName,
  7942. stream: StreamKind.START_COMPLETE,
  7943. streamId,
  7944. reason: wrapReason(reason)
  7945. });
  7946. });
  7947. }
  7948. _processStreamMessage(data) {
  7949. const streamId = data.streamId,
  7950. sourceName = this.sourceName,
  7951. targetName = data.sourceName,
  7952. comObj = this.comObj;
  7953. const streamController = this.streamControllers[streamId],
  7954. streamSink = this.streamSinks[streamId];
  7955. switch (data.stream) {
  7956. case StreamKind.START_COMPLETE:
  7957. if (data.success) {
  7958. streamController.startCall.resolve();
  7959. } else {
  7960. streamController.startCall.reject(wrapReason(data.reason));
  7961. }
  7962. break;
  7963. case StreamKind.PULL_COMPLETE:
  7964. if (data.success) {
  7965. streamController.pullCall.resolve();
  7966. } else {
  7967. streamController.pullCall.reject(wrapReason(data.reason));
  7968. }
  7969. break;
  7970. case StreamKind.PULL:
  7971. if (!streamSink) {
  7972. comObj.postMessage({
  7973. sourceName,
  7974. targetName,
  7975. stream: StreamKind.PULL_COMPLETE,
  7976. streamId,
  7977. success: true
  7978. });
  7979. break;
  7980. }
  7981. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  7982. streamSink.sinkCapability.resolve();
  7983. }
  7984. streamSink.desiredSize = data.desiredSize;
  7985. new Promise(function (resolve) {
  7986. resolve(streamSink.onPull && streamSink.onPull());
  7987. }).then(function () {
  7988. comObj.postMessage({
  7989. sourceName,
  7990. targetName,
  7991. stream: StreamKind.PULL_COMPLETE,
  7992. streamId,
  7993. success: true
  7994. });
  7995. }, function (reason) {
  7996. comObj.postMessage({
  7997. sourceName,
  7998. targetName,
  7999. stream: StreamKind.PULL_COMPLETE,
  8000. streamId,
  8001. reason: wrapReason(reason)
  8002. });
  8003. });
  8004. break;
  8005. case StreamKind.ENQUEUE:
  8006. (0, _util.assert)(streamController, "enqueue should have stream controller");
  8007. if (streamController.isClosed) {
  8008. break;
  8009. }
  8010. streamController.controller.enqueue(data.chunk);
  8011. break;
  8012. case StreamKind.CLOSE:
  8013. (0, _util.assert)(streamController, "close should have stream controller");
  8014. if (streamController.isClosed) {
  8015. break;
  8016. }
  8017. streamController.isClosed = true;
  8018. streamController.controller.close();
  8019. this._deleteStreamController(streamController, streamId);
  8020. break;
  8021. case StreamKind.ERROR:
  8022. (0, _util.assert)(streamController, "error should have stream controller");
  8023. streamController.controller.error(wrapReason(data.reason));
  8024. this._deleteStreamController(streamController, streamId);
  8025. break;
  8026. case StreamKind.CANCEL_COMPLETE:
  8027. if (data.success) {
  8028. streamController.cancelCall.resolve();
  8029. } else {
  8030. streamController.cancelCall.reject(wrapReason(data.reason));
  8031. }
  8032. this._deleteStreamController(streamController, streamId);
  8033. break;
  8034. case StreamKind.CANCEL:
  8035. if (!streamSink) {
  8036. break;
  8037. }
  8038. new Promise(function (resolve) {
  8039. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  8040. }).then(function () {
  8041. comObj.postMessage({
  8042. sourceName,
  8043. targetName,
  8044. stream: StreamKind.CANCEL_COMPLETE,
  8045. streamId,
  8046. success: true
  8047. });
  8048. }, function (reason) {
  8049. comObj.postMessage({
  8050. sourceName,
  8051. targetName,
  8052. stream: StreamKind.CANCEL_COMPLETE,
  8053. streamId,
  8054. reason: wrapReason(reason)
  8055. });
  8056. });
  8057. streamSink.sinkCapability.reject(wrapReason(data.reason));
  8058. streamSink.isCancelled = true;
  8059. delete this.streamSinks[streamId];
  8060. break;
  8061. default:
  8062. throw new Error("Unexpected stream case");
  8063. }
  8064. }
  8065. async _deleteStreamController(streamController, streamId) {
  8066. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  8067. delete this.streamControllers[streamId];
  8068. }
  8069. destroy() {
  8070. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  8071. }
  8072. }
  8073. exports.MessageHandler = MessageHandler;
  8074. /***/ }),
  8075. /* 16 */
  8076. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8077. Object.defineProperty(exports, "__esModule", ({
  8078. value: true
  8079. }));
  8080. exports.Metadata = void 0;
  8081. var _util = __w_pdfjs_require__(1);
  8082. class Metadata {
  8083. #metadataMap;
  8084. #data;
  8085. constructor({
  8086. parsedData,
  8087. rawData
  8088. }) {
  8089. this.#metadataMap = parsedData;
  8090. this.#data = rawData;
  8091. }
  8092. getRaw() {
  8093. return this.#data;
  8094. }
  8095. get(name) {
  8096. return this.#metadataMap.get(name) ?? null;
  8097. }
  8098. getAll() {
  8099. return (0, _util.objectFromMap)(this.#metadataMap);
  8100. }
  8101. has(name) {
  8102. return this.#metadataMap.has(name);
  8103. }
  8104. }
  8105. exports.Metadata = Metadata;
  8106. /***/ }),
  8107. /* 17 */
  8108. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8109. Object.defineProperty(exports, "__esModule", ({
  8110. value: true
  8111. }));
  8112. exports.OptionalContentConfig = void 0;
  8113. var _util = __w_pdfjs_require__(1);
  8114. var _murmurhash = __w_pdfjs_require__(8);
  8115. const INTERNAL = Symbol("INTERNAL");
  8116. class OptionalContentGroup {
  8117. #visible = true;
  8118. constructor(name, intent) {
  8119. this.name = name;
  8120. this.intent = intent;
  8121. }
  8122. get visible() {
  8123. return this.#visible;
  8124. }
  8125. _setVisible(internal, visible) {
  8126. if (internal !== INTERNAL) {
  8127. (0, _util.unreachable)("Internal method `_setVisible` called.");
  8128. }
  8129. this.#visible = visible;
  8130. }
  8131. }
  8132. class OptionalContentConfig {
  8133. #cachedGetHash = null;
  8134. #groups = new Map();
  8135. #initialHash = null;
  8136. #order = null;
  8137. constructor(data) {
  8138. this.name = null;
  8139. this.creator = null;
  8140. if (data === null) {
  8141. return;
  8142. }
  8143. this.name = data.name;
  8144. this.creator = data.creator;
  8145. this.#order = data.order;
  8146. for (const group of data.groups) {
  8147. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  8148. }
  8149. if (data.baseState === "OFF") {
  8150. for (const group of this.#groups.values()) {
  8151. group._setVisible(INTERNAL, false);
  8152. }
  8153. }
  8154. for (const on of data.on) {
  8155. this.#groups.get(on)._setVisible(INTERNAL, true);
  8156. }
  8157. for (const off of data.off) {
  8158. this.#groups.get(off)._setVisible(INTERNAL, false);
  8159. }
  8160. this.#initialHash = this.getHash();
  8161. }
  8162. #evaluateVisibilityExpression(array) {
  8163. const length = array.length;
  8164. if (length < 2) {
  8165. return true;
  8166. }
  8167. const operator = array[0];
  8168. for (let i = 1; i < length; i++) {
  8169. const element = array[i];
  8170. let state;
  8171. if (Array.isArray(element)) {
  8172. state = this.#evaluateVisibilityExpression(element);
  8173. } else if (this.#groups.has(element)) {
  8174. state = this.#groups.get(element).visible;
  8175. } else {
  8176. (0, _util.warn)(`Optional content group not found: ${element}`);
  8177. return true;
  8178. }
  8179. switch (operator) {
  8180. case "And":
  8181. if (!state) {
  8182. return false;
  8183. }
  8184. break;
  8185. case "Or":
  8186. if (state) {
  8187. return true;
  8188. }
  8189. break;
  8190. case "Not":
  8191. return !state;
  8192. default:
  8193. return true;
  8194. }
  8195. }
  8196. return operator === "And";
  8197. }
  8198. isVisible(group) {
  8199. if (this.#groups.size === 0) {
  8200. return true;
  8201. }
  8202. if (!group) {
  8203. (0, _util.warn)("Optional content group not defined.");
  8204. return true;
  8205. }
  8206. if (group.type === "OCG") {
  8207. if (!this.#groups.has(group.id)) {
  8208. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  8209. return true;
  8210. }
  8211. return this.#groups.get(group.id).visible;
  8212. } else if (group.type === "OCMD") {
  8213. if (group.expression) {
  8214. return this.#evaluateVisibilityExpression(group.expression);
  8215. }
  8216. if (!group.policy || group.policy === "AnyOn") {
  8217. for (const id of group.ids) {
  8218. if (!this.#groups.has(id)) {
  8219. (0, _util.warn)(`Optional content group not found: ${id}`);
  8220. return true;
  8221. }
  8222. if (this.#groups.get(id).visible) {
  8223. return true;
  8224. }
  8225. }
  8226. return false;
  8227. } else if (group.policy === "AllOn") {
  8228. for (const id of group.ids) {
  8229. if (!this.#groups.has(id)) {
  8230. (0, _util.warn)(`Optional content group not found: ${id}`);
  8231. return true;
  8232. }
  8233. if (!this.#groups.get(id).visible) {
  8234. return false;
  8235. }
  8236. }
  8237. return true;
  8238. } else if (group.policy === "AnyOff") {
  8239. for (const id of group.ids) {
  8240. if (!this.#groups.has(id)) {
  8241. (0, _util.warn)(`Optional content group not found: ${id}`);
  8242. return true;
  8243. }
  8244. if (!this.#groups.get(id).visible) {
  8245. return true;
  8246. }
  8247. }
  8248. return false;
  8249. } else if (group.policy === "AllOff") {
  8250. for (const id of group.ids) {
  8251. if (!this.#groups.has(id)) {
  8252. (0, _util.warn)(`Optional content group not found: ${id}`);
  8253. return true;
  8254. }
  8255. if (this.#groups.get(id).visible) {
  8256. return false;
  8257. }
  8258. }
  8259. return true;
  8260. }
  8261. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  8262. return true;
  8263. }
  8264. (0, _util.warn)(`Unknown group type ${group.type}.`);
  8265. return true;
  8266. }
  8267. setVisibility(id, visible = true) {
  8268. if (!this.#groups.has(id)) {
  8269. (0, _util.warn)(`Optional content group not found: ${id}`);
  8270. return;
  8271. }
  8272. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  8273. this.#cachedGetHash = null;
  8274. }
  8275. get hasInitialVisibility() {
  8276. return this.getHash() === this.#initialHash;
  8277. }
  8278. getOrder() {
  8279. if (!this.#groups.size) {
  8280. return null;
  8281. }
  8282. if (this.#order) {
  8283. return this.#order.slice();
  8284. }
  8285. return [...this.#groups.keys()];
  8286. }
  8287. getGroups() {
  8288. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  8289. }
  8290. getGroup(id) {
  8291. return this.#groups.get(id) || null;
  8292. }
  8293. getHash() {
  8294. if (this.#cachedGetHash !== null) {
  8295. return this.#cachedGetHash;
  8296. }
  8297. const hash = new _murmurhash.MurmurHash3_64();
  8298. for (const [id, group] of this.#groups) {
  8299. hash.update(`${id}:${group.visible}`);
  8300. }
  8301. return this.#cachedGetHash = hash.hexdigest();
  8302. }
  8303. }
  8304. exports.OptionalContentConfig = OptionalContentConfig;
  8305. /***/ }),
  8306. /* 18 */
  8307. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8308. Object.defineProperty(exports, "__esModule", ({
  8309. value: true
  8310. }));
  8311. exports.PDFDataTransportStream = void 0;
  8312. var _util = __w_pdfjs_require__(1);
  8313. var _display_utils = __w_pdfjs_require__(6);
  8314. class PDFDataTransportStream {
  8315. constructor(params, pdfDataRangeTransport) {
  8316. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  8317. this._queuedChunks = [];
  8318. this._progressiveDone = params.progressiveDone || false;
  8319. this._contentDispositionFilename = params.contentDispositionFilename || null;
  8320. const initialData = params.initialData;
  8321. if (initialData?.length > 0) {
  8322. const buffer = new Uint8Array(initialData).buffer;
  8323. this._queuedChunks.push(buffer);
  8324. }
  8325. this._pdfDataRangeTransport = pdfDataRangeTransport;
  8326. this._isStreamingSupported = !params.disableStream;
  8327. this._isRangeSupported = !params.disableRange;
  8328. this._contentLength = params.length;
  8329. this._fullRequestReader = null;
  8330. this._rangeReaders = [];
  8331. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  8332. this._onReceiveData({
  8333. begin,
  8334. chunk
  8335. });
  8336. });
  8337. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  8338. this._onProgress({
  8339. loaded,
  8340. total
  8341. });
  8342. });
  8343. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  8344. this._onReceiveData({
  8345. chunk
  8346. });
  8347. });
  8348. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  8349. this._onProgressiveDone();
  8350. });
  8351. this._pdfDataRangeTransport.transportReady();
  8352. }
  8353. _onReceiveData(args) {
  8354. const buffer = new Uint8Array(args.chunk).buffer;
  8355. if (args.begin === undefined) {
  8356. if (this._fullRequestReader) {
  8357. this._fullRequestReader._enqueue(buffer);
  8358. } else {
  8359. this._queuedChunks.push(buffer);
  8360. }
  8361. } else {
  8362. const found = this._rangeReaders.some(function (rangeReader) {
  8363. if (rangeReader._begin !== args.begin) {
  8364. return false;
  8365. }
  8366. rangeReader._enqueue(buffer);
  8367. return true;
  8368. });
  8369. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  8370. }
  8371. }
  8372. get _progressiveDataLength() {
  8373. return this._fullRequestReader?._loaded ?? 0;
  8374. }
  8375. _onProgress(evt) {
  8376. if (evt.total === undefined) {
  8377. this._rangeReaders[0]?.onProgress?.({
  8378. loaded: evt.loaded
  8379. });
  8380. } else {
  8381. this._fullRequestReader?.onProgress?.({
  8382. loaded: evt.loaded,
  8383. total: evt.total
  8384. });
  8385. }
  8386. }
  8387. _onProgressiveDone() {
  8388. this._fullRequestReader?.progressiveDone();
  8389. this._progressiveDone = true;
  8390. }
  8391. _removeRangeReader(reader) {
  8392. const i = this._rangeReaders.indexOf(reader);
  8393. if (i >= 0) {
  8394. this._rangeReaders.splice(i, 1);
  8395. }
  8396. }
  8397. getFullReader() {
  8398. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  8399. const queuedChunks = this._queuedChunks;
  8400. this._queuedChunks = null;
  8401. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  8402. }
  8403. getRangeReader(begin, end) {
  8404. if (end <= this._progressiveDataLength) {
  8405. return null;
  8406. }
  8407. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  8408. this._pdfDataRangeTransport.requestDataRange(begin, end);
  8409. this._rangeReaders.push(reader);
  8410. return reader;
  8411. }
  8412. cancelAllRequests(reason) {
  8413. this._fullRequestReader?.cancel(reason);
  8414. for (const reader of this._rangeReaders.slice(0)) {
  8415. reader.cancel(reason);
  8416. }
  8417. this._pdfDataRangeTransport.abort();
  8418. }
  8419. }
  8420. exports.PDFDataTransportStream = PDFDataTransportStream;
  8421. class PDFDataTransportStreamReader {
  8422. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  8423. this._stream = stream;
  8424. this._done = progressiveDone || false;
  8425. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  8426. this._queuedChunks = queuedChunks || [];
  8427. this._loaded = 0;
  8428. for (const chunk of this._queuedChunks) {
  8429. this._loaded += chunk.byteLength;
  8430. }
  8431. this._requests = [];
  8432. this._headersReady = Promise.resolve();
  8433. stream._fullRequestReader = this;
  8434. this.onProgress = null;
  8435. }
  8436. _enqueue(chunk) {
  8437. if (this._done) {
  8438. return;
  8439. }
  8440. if (this._requests.length > 0) {
  8441. const requestCapability = this._requests.shift();
  8442. requestCapability.resolve({
  8443. value: chunk,
  8444. done: false
  8445. });
  8446. } else {
  8447. this._queuedChunks.push(chunk);
  8448. }
  8449. this._loaded += chunk.byteLength;
  8450. }
  8451. get headersReady() {
  8452. return this._headersReady;
  8453. }
  8454. get filename() {
  8455. return this._filename;
  8456. }
  8457. get isRangeSupported() {
  8458. return this._stream._isRangeSupported;
  8459. }
  8460. get isStreamingSupported() {
  8461. return this._stream._isStreamingSupported;
  8462. }
  8463. get contentLength() {
  8464. return this._stream._contentLength;
  8465. }
  8466. async read() {
  8467. if (this._queuedChunks.length > 0) {
  8468. const chunk = this._queuedChunks.shift();
  8469. return {
  8470. value: chunk,
  8471. done: false
  8472. };
  8473. }
  8474. if (this._done) {
  8475. return {
  8476. value: undefined,
  8477. done: true
  8478. };
  8479. }
  8480. const requestCapability = (0, _util.createPromiseCapability)();
  8481. this._requests.push(requestCapability);
  8482. return requestCapability.promise;
  8483. }
  8484. cancel(reason) {
  8485. this._done = true;
  8486. for (const requestCapability of this._requests) {
  8487. requestCapability.resolve({
  8488. value: undefined,
  8489. done: true
  8490. });
  8491. }
  8492. this._requests.length = 0;
  8493. }
  8494. progressiveDone() {
  8495. if (this._done) {
  8496. return;
  8497. }
  8498. this._done = true;
  8499. }
  8500. }
  8501. class PDFDataTransportStreamRangeReader {
  8502. constructor(stream, begin, end) {
  8503. this._stream = stream;
  8504. this._begin = begin;
  8505. this._end = end;
  8506. this._queuedChunk = null;
  8507. this._requests = [];
  8508. this._done = false;
  8509. this.onProgress = null;
  8510. }
  8511. _enqueue(chunk) {
  8512. if (this._done) {
  8513. return;
  8514. }
  8515. if (this._requests.length === 0) {
  8516. this._queuedChunk = chunk;
  8517. } else {
  8518. const requestsCapability = this._requests.shift();
  8519. requestsCapability.resolve({
  8520. value: chunk,
  8521. done: false
  8522. });
  8523. for (const requestCapability of this._requests) {
  8524. requestCapability.resolve({
  8525. value: undefined,
  8526. done: true
  8527. });
  8528. }
  8529. this._requests.length = 0;
  8530. }
  8531. this._done = true;
  8532. this._stream._removeRangeReader(this);
  8533. }
  8534. get isStreamingSupported() {
  8535. return false;
  8536. }
  8537. async read() {
  8538. if (this._queuedChunk) {
  8539. const chunk = this._queuedChunk;
  8540. this._queuedChunk = null;
  8541. return {
  8542. value: chunk,
  8543. done: false
  8544. };
  8545. }
  8546. if (this._done) {
  8547. return {
  8548. value: undefined,
  8549. done: true
  8550. };
  8551. }
  8552. const requestCapability = (0, _util.createPromiseCapability)();
  8553. this._requests.push(requestCapability);
  8554. return requestCapability.promise;
  8555. }
  8556. cancel(reason) {
  8557. this._done = true;
  8558. for (const requestCapability of this._requests) {
  8559. requestCapability.resolve({
  8560. value: undefined,
  8561. done: true
  8562. });
  8563. }
  8564. this._requests.length = 0;
  8565. this._stream._removeRangeReader(this);
  8566. }
  8567. }
  8568. /***/ }),
  8569. /* 19 */
  8570. /***/ ((__unused_webpack_module, exports) => {
  8571. Object.defineProperty(exports, "__esModule", ({
  8572. value: true
  8573. }));
  8574. exports.XfaText = void 0;
  8575. class XfaText {
  8576. static textContent(xfa) {
  8577. const items = [];
  8578. const output = {
  8579. items,
  8580. styles: Object.create(null)
  8581. };
  8582. function walk(node) {
  8583. if (!node) {
  8584. return;
  8585. }
  8586. let str = null;
  8587. const name = node.name;
  8588. if (name === "#text") {
  8589. str = node.value;
  8590. } else if (!XfaText.shouldBuildText(name)) {
  8591. return;
  8592. } else if (node?.attributes?.textContent) {
  8593. str = node.attributes.textContent;
  8594. } else if (node.value) {
  8595. str = node.value;
  8596. }
  8597. if (str !== null) {
  8598. items.push({
  8599. str
  8600. });
  8601. }
  8602. if (!node.children) {
  8603. return;
  8604. }
  8605. for (const child of node.children) {
  8606. walk(child);
  8607. }
  8608. }
  8609. walk(xfa);
  8610. return output;
  8611. }
  8612. static shouldBuildText(name) {
  8613. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  8614. }
  8615. }
  8616. exports.XfaText = XfaText;
  8617. /***/ }),
  8618. /* 20 */
  8619. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8620. Object.defineProperty(exports, "__esModule", ({
  8621. value: true
  8622. }));
  8623. exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  8624. var _base_factory = __w_pdfjs_require__(7);
  8625. ;
  8626. const fetchData = function (url) {
  8627. return new Promise((resolve, reject) => {
  8628. const fs = require("fs");
  8629. fs.readFile(url, (error, data) => {
  8630. if (error || !data) {
  8631. reject(new Error(error));
  8632. return;
  8633. }
  8634. resolve(new Uint8Array(data));
  8635. });
  8636. });
  8637. };
  8638. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  8639. _createCanvas(width, height) {
  8640. const Canvas = require("canvas");
  8641. return Canvas.createCanvas(width, height);
  8642. }
  8643. }
  8644. exports.NodeCanvasFactory = NodeCanvasFactory;
  8645. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  8646. _fetchData(url, compressionType) {
  8647. return fetchData(url).then(data => {
  8648. return {
  8649. cMapData: data,
  8650. compressionType
  8651. };
  8652. });
  8653. }
  8654. }
  8655. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  8656. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  8657. _fetchData(url) {
  8658. return fetchData(url);
  8659. }
  8660. }
  8661. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  8662. /***/ }),
  8663. /* 21 */
  8664. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8665. Object.defineProperty(exports, "__esModule", ({
  8666. value: true
  8667. }));
  8668. exports.TextLayerRenderTask = void 0;
  8669. exports.renderTextLayer = renderTextLayer;
  8670. exports.updateTextLayer = updateTextLayer;
  8671. var _util = __w_pdfjs_require__(1);
  8672. var _display_utils = __w_pdfjs_require__(6);
  8673. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  8674. const DEFAULT_FONT_SIZE = 30;
  8675. const DEFAULT_FONT_ASCENT = 0.8;
  8676. const ascentCache = new Map();
  8677. function getCtx(size, isOffscreenCanvasSupported) {
  8678. let ctx;
  8679. if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
  8680. ctx = new OffscreenCanvas(size, size).getContext("2d", {
  8681. alpha: false
  8682. });
  8683. } else {
  8684. const canvas = document.createElement("canvas");
  8685. canvas.width = canvas.height = size;
  8686. ctx = canvas.getContext("2d", {
  8687. alpha: false
  8688. });
  8689. }
  8690. return ctx;
  8691. }
  8692. function getAscent(fontFamily, isOffscreenCanvasSupported) {
  8693. const cachedAscent = ascentCache.get(fontFamily);
  8694. if (cachedAscent) {
  8695. return cachedAscent;
  8696. }
  8697. const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
  8698. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  8699. const metrics = ctx.measureText("");
  8700. let ascent = metrics.fontBoundingBoxAscent;
  8701. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  8702. if (ascent) {
  8703. const ratio = ascent / (ascent + descent);
  8704. ascentCache.set(fontFamily, ratio);
  8705. ctx.canvas.width = ctx.canvas.height = 0;
  8706. return ratio;
  8707. }
  8708. ctx.strokeStyle = "red";
  8709. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8710. ctx.strokeText("g", 0, 0);
  8711. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8712. descent = 0;
  8713. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  8714. if (pixels[i] > 0) {
  8715. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  8716. break;
  8717. }
  8718. }
  8719. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  8720. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  8721. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  8722. ascent = 0;
  8723. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  8724. if (pixels[i] > 0) {
  8725. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  8726. break;
  8727. }
  8728. }
  8729. ctx.canvas.width = ctx.canvas.height = 0;
  8730. if (ascent) {
  8731. const ratio = ascent / (ascent + descent);
  8732. ascentCache.set(fontFamily, ratio);
  8733. return ratio;
  8734. }
  8735. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  8736. return DEFAULT_FONT_ASCENT;
  8737. }
  8738. function appendText(task, geom, styles) {
  8739. const textDiv = document.createElement("span");
  8740. const textDivProperties = {
  8741. angle: 0,
  8742. canvasWidth: 0,
  8743. hasText: geom.str !== "",
  8744. hasEOL: geom.hasEOL,
  8745. fontSize: 0
  8746. };
  8747. task._textDivs.push(textDiv);
  8748. const tx = _util.Util.transform(task._transform, geom.transform);
  8749. let angle = Math.atan2(tx[1], tx[0]);
  8750. const style = styles[geom.fontName];
  8751. if (style.vertical) {
  8752. angle += Math.PI / 2;
  8753. }
  8754. const fontHeight = Math.hypot(tx[2], tx[3]);
  8755. const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
  8756. let left, top;
  8757. if (angle === 0) {
  8758. left = tx[4];
  8759. top = tx[5] - fontAscent;
  8760. } else {
  8761. left = tx[4] + fontAscent * Math.sin(angle);
  8762. top = tx[5] - fontAscent * Math.cos(angle);
  8763. }
  8764. const scaleFactorStr = "calc(var(--scale-factor)*";
  8765. const divStyle = textDiv.style;
  8766. if (task._container === task._rootContainer) {
  8767. divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
  8768. divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
  8769. } else {
  8770. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  8771. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  8772. }
  8773. divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
  8774. divStyle.fontFamily = style.fontFamily;
  8775. textDivProperties.fontSize = fontHeight;
  8776. textDiv.setAttribute("role", "presentation");
  8777. textDiv.textContent = geom.str;
  8778. textDiv.dir = geom.dir;
  8779. if (task._fontInspectorEnabled) {
  8780. textDiv.dataset.fontName = geom.fontName;
  8781. }
  8782. if (angle !== 0) {
  8783. textDivProperties.angle = angle * (180 / Math.PI);
  8784. }
  8785. let shouldScaleText = false;
  8786. if (geom.str.length > 1) {
  8787. shouldScaleText = true;
  8788. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  8789. const absScaleX = Math.abs(geom.transform[0]),
  8790. absScaleY = Math.abs(geom.transform[3]);
  8791. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  8792. shouldScaleText = true;
  8793. }
  8794. }
  8795. if (shouldScaleText) {
  8796. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  8797. }
  8798. task._textDivProperties.set(textDiv, textDivProperties);
  8799. if (task._isReadableStream) {
  8800. task._layoutText(textDiv);
  8801. }
  8802. }
  8803. function layout(params) {
  8804. const {
  8805. div,
  8806. scale,
  8807. properties,
  8808. ctx,
  8809. prevFontSize,
  8810. prevFontFamily
  8811. } = params;
  8812. const {
  8813. style
  8814. } = div;
  8815. let transform = "";
  8816. if (properties.canvasWidth !== 0 && properties.hasText) {
  8817. const {
  8818. fontFamily
  8819. } = style;
  8820. const {
  8821. canvasWidth,
  8822. fontSize
  8823. } = properties;
  8824. if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
  8825. ctx.font = `${fontSize * scale}px ${fontFamily}`;
  8826. params.prevFontSize = fontSize;
  8827. params.prevFontFamily = fontFamily;
  8828. }
  8829. const {
  8830. width
  8831. } = ctx.measureText(div.textContent);
  8832. if (width > 0) {
  8833. transform = `scaleX(${canvasWidth * scale / width})`;
  8834. }
  8835. }
  8836. if (properties.angle !== 0) {
  8837. transform = `rotate(${properties.angle}deg) ${transform}`;
  8838. }
  8839. if (transform.length > 0) {
  8840. style.transform = transform;
  8841. }
  8842. }
  8843. function render(task) {
  8844. if (task._canceled) {
  8845. return;
  8846. }
  8847. const textDivs = task._textDivs;
  8848. const capability = task._capability;
  8849. const textDivsLength = textDivs.length;
  8850. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  8851. capability.resolve();
  8852. return;
  8853. }
  8854. if (!task._isReadableStream) {
  8855. for (const textDiv of textDivs) {
  8856. task._layoutText(textDiv);
  8857. }
  8858. }
  8859. capability.resolve();
  8860. }
  8861. class TextLayerRenderTask {
  8862. constructor({
  8863. textContentSource,
  8864. container,
  8865. viewport,
  8866. textDivs,
  8867. textDivProperties,
  8868. textContentItemsStr,
  8869. isOffscreenCanvasSupported
  8870. }) {
  8871. this._textContentSource = textContentSource;
  8872. this._isReadableStream = textContentSource instanceof ReadableStream;
  8873. this._container = this._rootContainer = container;
  8874. this._textDivs = textDivs || [];
  8875. this._textContentItemsStr = textContentItemsStr || [];
  8876. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  8877. this._reader = null;
  8878. this._textDivProperties = textDivProperties || new WeakMap();
  8879. this._canceled = false;
  8880. this._capability = (0, _util.createPromiseCapability)();
  8881. this._layoutTextParams = {
  8882. prevFontSize: null,
  8883. prevFontFamily: null,
  8884. div: null,
  8885. scale: viewport.scale * (globalThis.devicePixelRatio || 1),
  8886. properties: null,
  8887. ctx: getCtx(0, isOffscreenCanvasSupported)
  8888. };
  8889. const {
  8890. pageWidth,
  8891. pageHeight,
  8892. pageX,
  8893. pageY
  8894. } = viewport.rawDims;
  8895. this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  8896. this._pageWidth = pageWidth;
  8897. this._pageHeight = pageHeight;
  8898. (0, _display_utils.setLayerDimensions)(container, viewport);
  8899. this._capability.promise.finally(() => {
  8900. this._layoutTextParams = null;
  8901. }).catch(() => {});
  8902. }
  8903. get promise() {
  8904. return this._capability.promise;
  8905. }
  8906. cancel() {
  8907. this._canceled = true;
  8908. if (this._reader) {
  8909. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  8910. this._reader = null;
  8911. }
  8912. this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
  8913. }
  8914. _processItems(items, styleCache) {
  8915. for (const item of items) {
  8916. if (item.str === undefined) {
  8917. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  8918. const parent = this._container;
  8919. this._container = document.createElement("span");
  8920. this._container.classList.add("markedContent");
  8921. if (item.id !== null) {
  8922. this._container.setAttribute("id", `${item.id}`);
  8923. }
  8924. parent.append(this._container);
  8925. } else if (item.type === "endMarkedContent") {
  8926. this._container = this._container.parentNode;
  8927. }
  8928. continue;
  8929. }
  8930. this._textContentItemsStr.push(item.str);
  8931. appendText(this, item, styleCache);
  8932. }
  8933. }
  8934. _layoutText(textDiv) {
  8935. const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
  8936. this._layoutTextParams.div = textDiv;
  8937. layout(this._layoutTextParams);
  8938. if (textDivProperties.hasText) {
  8939. this._container.append(textDiv);
  8940. }
  8941. if (textDivProperties.hasEOL) {
  8942. const br = document.createElement("br");
  8943. br.setAttribute("role", "presentation");
  8944. this._container.append(br);
  8945. }
  8946. }
  8947. _render() {
  8948. const capability = (0, _util.createPromiseCapability)();
  8949. let styleCache = Object.create(null);
  8950. if (this._isReadableStream) {
  8951. const pump = () => {
  8952. this._reader.read().then(({
  8953. value,
  8954. done
  8955. }) => {
  8956. if (done) {
  8957. capability.resolve();
  8958. return;
  8959. }
  8960. Object.assign(styleCache, value.styles);
  8961. this._processItems(value.items, styleCache);
  8962. pump();
  8963. }, capability.reject);
  8964. };
  8965. this._reader = this._textContentSource.getReader();
  8966. pump();
  8967. } else if (this._textContentSource) {
  8968. const {
  8969. items,
  8970. styles
  8971. } = this._textContentSource;
  8972. this._processItems(items, styles);
  8973. capability.resolve();
  8974. } else {
  8975. throw new Error('No "textContentSource" parameter specified.');
  8976. }
  8977. capability.promise.then(() => {
  8978. styleCache = null;
  8979. render(this);
  8980. }, this._capability.reject);
  8981. }
  8982. }
  8983. exports.TextLayerRenderTask = TextLayerRenderTask;
  8984. function renderTextLayer(params) {
  8985. if (!params.textContentSource && (params.textContent || params.textContentStream)) {
  8986. (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
  8987. params.textContentSource = params.textContent || params.textContentStream;
  8988. }
  8989. const task = new TextLayerRenderTask(params);
  8990. task._render();
  8991. return task;
  8992. }
  8993. function updateTextLayer({
  8994. container,
  8995. viewport,
  8996. textDivs,
  8997. textDivProperties,
  8998. isOffscreenCanvasSupported,
  8999. mustRotate = true,
  9000. mustRescale = true
  9001. }) {
  9002. if (mustRotate) {
  9003. (0, _display_utils.setLayerDimensions)(container, {
  9004. rotation: viewport.rotation
  9005. });
  9006. }
  9007. if (mustRescale) {
  9008. const ctx = getCtx(0, isOffscreenCanvasSupported);
  9009. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  9010. const params = {
  9011. prevFontSize: null,
  9012. prevFontFamily: null,
  9013. div: null,
  9014. scale,
  9015. properties: null,
  9016. ctx
  9017. };
  9018. for (const div of textDivs) {
  9019. params.properties = textDivProperties.get(div);
  9020. params.div = div;
  9021. layout(params);
  9022. }
  9023. }
  9024. }
  9025. /***/ }),
  9026. /* 22 */
  9027. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9028. Object.defineProperty(exports, "__esModule", ({
  9029. value: true
  9030. }));
  9031. exports.AnnotationEditorLayer = void 0;
  9032. var _util = __w_pdfjs_require__(1);
  9033. var _tools = __w_pdfjs_require__(5);
  9034. var _freetext = __w_pdfjs_require__(23);
  9035. var _ink = __w_pdfjs_require__(24);
  9036. var _display_utils = __w_pdfjs_require__(6);
  9037. class AnnotationEditorLayer {
  9038. #accessibilityManager;
  9039. #allowClick = false;
  9040. #boundPointerup = this.pointerup.bind(this);
  9041. #boundPointerdown = this.pointerdown.bind(this);
  9042. #editors = new Map();
  9043. #hadPointerDown = false;
  9044. #isCleaningUp = false;
  9045. #uiManager;
  9046. static _initialized = false;
  9047. constructor(options) {
  9048. if (!AnnotationEditorLayer._initialized) {
  9049. AnnotationEditorLayer._initialized = true;
  9050. _freetext.FreeTextEditor.initialize(options.l10n);
  9051. _ink.InkEditor.initialize(options.l10n);
  9052. }
  9053. options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
  9054. this.#uiManager = options.uiManager;
  9055. this.pageIndex = options.pageIndex;
  9056. this.div = options.div;
  9057. this.#accessibilityManager = options.accessibilityManager;
  9058. this.#uiManager.addLayer(this);
  9059. }
  9060. updateToolbar(mode) {
  9061. this.#uiManager.updateToolbar(mode);
  9062. }
  9063. updateMode(mode = this.#uiManager.getMode()) {
  9064. this.#cleanup();
  9065. if (mode === _util.AnnotationEditorType.INK) {
  9066. this.addInkEditorIfNeeded(false);
  9067. this.disableClick();
  9068. } else {
  9069. this.enableClick();
  9070. }
  9071. this.#uiManager.unselectAll();
  9072. this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
  9073. this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
  9074. }
  9075. addInkEditorIfNeeded(isCommitting) {
  9076. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  9077. return;
  9078. }
  9079. if (!isCommitting) {
  9080. for (const editor of this.#editors.values()) {
  9081. if (editor.isEmpty()) {
  9082. editor.setInBackground();
  9083. return;
  9084. }
  9085. }
  9086. }
  9087. const editor = this.#createAndAddNewEditor({
  9088. offsetX: 0,
  9089. offsetY: 0
  9090. });
  9091. editor.setInBackground();
  9092. }
  9093. setEditingState(isEditing) {
  9094. this.#uiManager.setEditingState(isEditing);
  9095. }
  9096. addCommands(params) {
  9097. this.#uiManager.addCommands(params);
  9098. }
  9099. enable() {
  9100. this.div.style.pointerEvents = "auto";
  9101. for (const editor of this.#editors.values()) {
  9102. editor.enableEditing();
  9103. }
  9104. }
  9105. disable() {
  9106. this.div.style.pointerEvents = "none";
  9107. for (const editor of this.#editors.values()) {
  9108. editor.disableEditing();
  9109. }
  9110. }
  9111. setActiveEditor(editor) {
  9112. const currentActive = this.#uiManager.getActive();
  9113. if (currentActive === editor) {
  9114. return;
  9115. }
  9116. this.#uiManager.setActiveEditor(editor);
  9117. }
  9118. enableClick() {
  9119. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  9120. this.div.addEventListener("pointerup", this.#boundPointerup);
  9121. }
  9122. disableClick() {
  9123. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  9124. this.div.removeEventListener("pointerup", this.#boundPointerup);
  9125. }
  9126. attach(editor) {
  9127. this.#editors.set(editor.id, editor);
  9128. }
  9129. detach(editor) {
  9130. this.#editors.delete(editor.id);
  9131. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  9132. }
  9133. remove(editor) {
  9134. this.#uiManager.removeEditor(editor);
  9135. this.detach(editor);
  9136. editor.div.style.display = "none";
  9137. setTimeout(() => {
  9138. editor.div.style.display = "";
  9139. editor.div.remove();
  9140. editor.isAttachedToDOM = false;
  9141. if (document.activeElement === document.body) {
  9142. this.#uiManager.focusMainContainer();
  9143. }
  9144. }, 0);
  9145. if (!this.#isCleaningUp) {
  9146. this.addInkEditorIfNeeded(false);
  9147. }
  9148. }
  9149. #changeParent(editor) {
  9150. if (editor.parent === this) {
  9151. return;
  9152. }
  9153. this.attach(editor);
  9154. editor.parent?.detach(editor);
  9155. editor.setParent(this);
  9156. if (editor.div && editor.isAttachedToDOM) {
  9157. editor.div.remove();
  9158. this.div.append(editor.div);
  9159. }
  9160. }
  9161. add(editor) {
  9162. this.#changeParent(editor);
  9163. this.#uiManager.addEditor(editor);
  9164. this.attach(editor);
  9165. if (!editor.isAttachedToDOM) {
  9166. const div = editor.render();
  9167. this.div.append(div);
  9168. editor.isAttachedToDOM = true;
  9169. }
  9170. this.moveEditorInDOM(editor);
  9171. editor.onceAdded();
  9172. this.#uiManager.addToAnnotationStorage(editor);
  9173. }
  9174. moveEditorInDOM(editor) {
  9175. this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  9176. }
  9177. addOrRebuild(editor) {
  9178. if (editor.needsToBeRebuilt()) {
  9179. editor.rebuild();
  9180. } else {
  9181. this.add(editor);
  9182. }
  9183. }
  9184. addANewEditor(editor) {
  9185. const cmd = () => {
  9186. this.addOrRebuild(editor);
  9187. };
  9188. const undo = () => {
  9189. editor.remove();
  9190. };
  9191. this.addCommands({
  9192. cmd,
  9193. undo,
  9194. mustExec: true
  9195. });
  9196. }
  9197. addUndoableEditor(editor) {
  9198. const cmd = () => {
  9199. this.addOrRebuild(editor);
  9200. };
  9201. const undo = () => {
  9202. editor.remove();
  9203. };
  9204. this.addCommands({
  9205. cmd,
  9206. undo,
  9207. mustExec: false
  9208. });
  9209. }
  9210. getNextId() {
  9211. return this.#uiManager.getId();
  9212. }
  9213. #createNewEditor(params) {
  9214. switch (this.#uiManager.getMode()) {
  9215. case _util.AnnotationEditorType.FREETEXT:
  9216. return new _freetext.FreeTextEditor(params);
  9217. case _util.AnnotationEditorType.INK:
  9218. return new _ink.InkEditor(params);
  9219. }
  9220. return null;
  9221. }
  9222. deserialize(data) {
  9223. switch (data.annotationType) {
  9224. case _util.AnnotationEditorType.FREETEXT:
  9225. return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
  9226. case _util.AnnotationEditorType.INK:
  9227. return _ink.InkEditor.deserialize(data, this, this.#uiManager);
  9228. }
  9229. return null;
  9230. }
  9231. #createAndAddNewEditor(event) {
  9232. const id = this.getNextId();
  9233. const editor = this.#createNewEditor({
  9234. parent: this,
  9235. id,
  9236. x: event.offsetX,
  9237. y: event.offsetY,
  9238. uiManager: this.#uiManager
  9239. });
  9240. if (editor) {
  9241. this.add(editor);
  9242. }
  9243. return editor;
  9244. }
  9245. setSelected(editor) {
  9246. this.#uiManager.setSelected(editor);
  9247. }
  9248. toggleSelected(editor) {
  9249. this.#uiManager.toggleSelected(editor);
  9250. }
  9251. isSelected(editor) {
  9252. return this.#uiManager.isSelected(editor);
  9253. }
  9254. unselect(editor) {
  9255. this.#uiManager.unselect(editor);
  9256. }
  9257. pointerup(event) {
  9258. const {
  9259. isMac
  9260. } = _util.FeatureTest.platform;
  9261. if (event.button !== 0 || event.ctrlKey && isMac) {
  9262. return;
  9263. }
  9264. if (event.target !== this.div) {
  9265. return;
  9266. }
  9267. if (!this.#hadPointerDown) {
  9268. return;
  9269. }
  9270. this.#hadPointerDown = false;
  9271. if (!this.#allowClick) {
  9272. this.#allowClick = true;
  9273. return;
  9274. }
  9275. this.#createAndAddNewEditor(event);
  9276. }
  9277. pointerdown(event) {
  9278. const {
  9279. isMac
  9280. } = _util.FeatureTest.platform;
  9281. if (event.button !== 0 || event.ctrlKey && isMac) {
  9282. return;
  9283. }
  9284. if (event.target !== this.div) {
  9285. return;
  9286. }
  9287. this.#hadPointerDown = true;
  9288. const editor = this.#uiManager.getActive();
  9289. this.#allowClick = !editor || editor.isEmpty();
  9290. }
  9291. drop(event) {
  9292. const id = event.dataTransfer.getData("text/plain");
  9293. const editor = this.#uiManager.getEditor(id);
  9294. if (!editor) {
  9295. return;
  9296. }
  9297. event.preventDefault();
  9298. event.dataTransfer.dropEffect = "move";
  9299. this.#changeParent(editor);
  9300. const rect = this.div.getBoundingClientRect();
  9301. const endX = event.clientX - rect.x;
  9302. const endY = event.clientY - rect.y;
  9303. editor.translate(endX - editor.startX, endY - editor.startY);
  9304. this.moveEditorInDOM(editor);
  9305. editor.div.focus();
  9306. }
  9307. dragover(event) {
  9308. event.preventDefault();
  9309. }
  9310. destroy() {
  9311. if (this.#uiManager.getActive()?.parent === this) {
  9312. this.#uiManager.setActiveEditor(null);
  9313. }
  9314. for (const editor of this.#editors.values()) {
  9315. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  9316. editor.setParent(null);
  9317. editor.isAttachedToDOM = false;
  9318. editor.div.remove();
  9319. }
  9320. this.div = null;
  9321. this.#editors.clear();
  9322. this.#uiManager.removeLayer(this);
  9323. }
  9324. #cleanup() {
  9325. this.#isCleaningUp = true;
  9326. for (const editor of this.#editors.values()) {
  9327. if (editor.isEmpty()) {
  9328. editor.remove();
  9329. }
  9330. }
  9331. this.#isCleaningUp = false;
  9332. }
  9333. render({
  9334. viewport
  9335. }) {
  9336. this.viewport = viewport;
  9337. (0, _display_utils.setLayerDimensions)(this.div, viewport);
  9338. (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
  9339. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  9340. this.add(editor);
  9341. }
  9342. this.updateMode();
  9343. }
  9344. update({
  9345. viewport
  9346. }) {
  9347. this.#uiManager.commitOrRemove();
  9348. this.viewport = viewport;
  9349. (0, _display_utils.setLayerDimensions)(this.div, {
  9350. rotation: viewport.rotation
  9351. });
  9352. this.updateMode();
  9353. }
  9354. get pageDimensions() {
  9355. const {
  9356. pageWidth,
  9357. pageHeight
  9358. } = this.viewport.rawDims;
  9359. return [pageWidth, pageHeight];
  9360. }
  9361. }
  9362. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  9363. /***/ }),
  9364. /* 23 */
  9365. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9366. Object.defineProperty(exports, "__esModule", ({
  9367. value: true
  9368. }));
  9369. exports.FreeTextEditor = void 0;
  9370. var _util = __w_pdfjs_require__(1);
  9371. var _tools = __w_pdfjs_require__(5);
  9372. var _editor = __w_pdfjs_require__(4);
  9373. class FreeTextEditor extends _editor.AnnotationEditor {
  9374. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  9375. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  9376. #boundEditorDivInput = this.editorDivInput.bind(this);
  9377. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  9378. #color;
  9379. #content = "";
  9380. #editorDivId = `${this.id}-editor`;
  9381. #hasAlreadyBeenCommitted = false;
  9382. #fontSize;
  9383. static _freeTextDefaultContent = "";
  9384. static _l10nPromise;
  9385. static _internalPadding = 0;
  9386. static _defaultColor = null;
  9387. static _defaultFontSize = 10;
  9388. static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  9389. static _type = "freetext";
  9390. constructor(params) {
  9391. super({
  9392. ...params,
  9393. name: "freeTextEditor"
  9394. });
  9395. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9396. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  9397. }
  9398. static initialize(l10n) {
  9399. this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
  9400. const style = getComputedStyle(document.documentElement);
  9401. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  9402. }
  9403. static updateDefaultParams(type, value) {
  9404. switch (type) {
  9405. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  9406. FreeTextEditor._defaultFontSize = value;
  9407. break;
  9408. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  9409. FreeTextEditor._defaultColor = value;
  9410. break;
  9411. }
  9412. }
  9413. updateParams(type, value) {
  9414. switch (type) {
  9415. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  9416. this.#updateFontSize(value);
  9417. break;
  9418. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  9419. this.#updateColor(value);
  9420. break;
  9421. }
  9422. }
  9423. static get defaultPropertiesToUpdate() {
  9424. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  9425. }
  9426. get propertiesToUpdate() {
  9427. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  9428. }
  9429. #updateFontSize(fontSize) {
  9430. const setFontsize = size => {
  9431. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  9432. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  9433. this.#fontSize = size;
  9434. this.#setEditorDimensions();
  9435. };
  9436. const savedFontsize = this.#fontSize;
  9437. this.addCommands({
  9438. cmd: () => {
  9439. setFontsize(fontSize);
  9440. },
  9441. undo: () => {
  9442. setFontsize(savedFontsize);
  9443. },
  9444. mustExec: true,
  9445. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  9446. overwriteIfSameType: true,
  9447. keepUndo: true
  9448. });
  9449. }
  9450. #updateColor(color) {
  9451. const savedColor = this.#color;
  9452. this.addCommands({
  9453. cmd: () => {
  9454. this.#color = this.editorDiv.style.color = color;
  9455. },
  9456. undo: () => {
  9457. this.#color = this.editorDiv.style.color = savedColor;
  9458. },
  9459. mustExec: true,
  9460. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  9461. overwriteIfSameType: true,
  9462. keepUndo: true
  9463. });
  9464. }
  9465. getInitialTranslation() {
  9466. const scale = this.parentScale;
  9467. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  9468. }
  9469. rebuild() {
  9470. super.rebuild();
  9471. if (this.div === null) {
  9472. return;
  9473. }
  9474. if (!this.isAttachedToDOM) {
  9475. this.parent.add(this);
  9476. }
  9477. }
  9478. enableEditMode() {
  9479. if (this.isInEditMode()) {
  9480. return;
  9481. }
  9482. this.parent.setEditingState(false);
  9483. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  9484. super.enableEditMode();
  9485. this.overlayDiv.classList.remove("enabled");
  9486. this.editorDiv.contentEditable = true;
  9487. this.div.draggable = false;
  9488. this.div.removeAttribute("aria-activedescendant");
  9489. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  9490. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  9491. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  9492. this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  9493. }
  9494. disableEditMode() {
  9495. if (!this.isInEditMode()) {
  9496. return;
  9497. }
  9498. this.parent.setEditingState(true);
  9499. super.disableEditMode();
  9500. this.overlayDiv.classList.add("enabled");
  9501. this.editorDiv.contentEditable = false;
  9502. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  9503. this.div.draggable = true;
  9504. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  9505. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  9506. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  9507. this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
  9508. this.div.focus({
  9509. preventScroll: true
  9510. });
  9511. this.isEditing = false;
  9512. this.parent.div.classList.add("freeTextEditing");
  9513. }
  9514. focusin(event) {
  9515. super.focusin(event);
  9516. if (event.target !== this.editorDiv) {
  9517. this.editorDiv.focus();
  9518. }
  9519. }
  9520. onceAdded() {
  9521. if (this.width) {
  9522. return;
  9523. }
  9524. this.enableEditMode();
  9525. this.editorDiv.focus();
  9526. }
  9527. isEmpty() {
  9528. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  9529. }
  9530. remove() {
  9531. this.isEditing = false;
  9532. this.parent.setEditingState(true);
  9533. this.parent.div.classList.add("freeTextEditing");
  9534. super.remove();
  9535. }
  9536. #extractText() {
  9537. const divs = this.editorDiv.getElementsByTagName("div");
  9538. if (divs.length === 0) {
  9539. return this.editorDiv.innerText;
  9540. }
  9541. const buffer = [];
  9542. for (const div of divs) {
  9543. buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
  9544. }
  9545. return buffer.join("\n");
  9546. }
  9547. #setEditorDimensions() {
  9548. const [parentWidth, parentHeight] = this.parentDimensions;
  9549. let rect;
  9550. if (this.isAttachedToDOM) {
  9551. rect = this.div.getBoundingClientRect();
  9552. } else {
  9553. const {
  9554. currentLayer,
  9555. div
  9556. } = this;
  9557. const savedDisplay = div.style.display;
  9558. div.style.display = "hidden";
  9559. currentLayer.div.append(this.div);
  9560. rect = div.getBoundingClientRect();
  9561. div.remove();
  9562. div.style.display = savedDisplay;
  9563. }
  9564. this.width = rect.width / parentWidth;
  9565. this.height = rect.height / parentHeight;
  9566. }
  9567. commit() {
  9568. if (!this.isInEditMode()) {
  9569. return;
  9570. }
  9571. super.commit();
  9572. if (!this.#hasAlreadyBeenCommitted) {
  9573. this.#hasAlreadyBeenCommitted = true;
  9574. this.parent.addUndoableEditor(this);
  9575. }
  9576. this.disableEditMode();
  9577. this.#content = this.#extractText().trimEnd();
  9578. this.#setEditorDimensions();
  9579. }
  9580. shouldGetKeyboardEvents() {
  9581. return this.isInEditMode();
  9582. }
  9583. dblclick(event) {
  9584. this.enableEditMode();
  9585. this.editorDiv.focus();
  9586. }
  9587. keydown(event) {
  9588. if (event.target === this.div && event.key === "Enter") {
  9589. this.enableEditMode();
  9590. this.editorDiv.focus();
  9591. }
  9592. }
  9593. editorDivKeydown(event) {
  9594. FreeTextEditor._keyboardManager.exec(this, event);
  9595. }
  9596. editorDivFocus(event) {
  9597. this.isEditing = true;
  9598. }
  9599. editorDivBlur(event) {
  9600. this.isEditing = false;
  9601. }
  9602. editorDivInput(event) {
  9603. this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  9604. }
  9605. disableEditing() {
  9606. this.editorDiv.setAttribute("role", "comment");
  9607. this.editorDiv.removeAttribute("aria-multiline");
  9608. }
  9609. enableEditing() {
  9610. this.editorDiv.setAttribute("role", "textbox");
  9611. this.editorDiv.setAttribute("aria-multiline", true);
  9612. }
  9613. render() {
  9614. if (this.div) {
  9615. return this.div;
  9616. }
  9617. let baseX, baseY;
  9618. if (this.width) {
  9619. baseX = this.x;
  9620. baseY = this.y;
  9621. }
  9622. super.render();
  9623. this.editorDiv = document.createElement("div");
  9624. this.editorDiv.className = "internal";
  9625. this.editorDiv.setAttribute("id", this.#editorDivId);
  9626. this.enableEditing();
  9627. FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  9628. FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  9629. this.editorDiv.contentEditable = true;
  9630. const {
  9631. style
  9632. } = this.editorDiv;
  9633. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  9634. style.color = this.#color;
  9635. this.div.append(this.editorDiv);
  9636. this.overlayDiv = document.createElement("div");
  9637. this.overlayDiv.classList.add("overlay", "enabled");
  9638. this.div.append(this.overlayDiv);
  9639. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  9640. if (this.width) {
  9641. const [parentWidth, parentHeight] = this.parentDimensions;
  9642. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  9643. for (const line of this.#content.split("\n")) {
  9644. const div = document.createElement("div");
  9645. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  9646. this.editorDiv.append(div);
  9647. }
  9648. this.div.draggable = true;
  9649. this.editorDiv.contentEditable = false;
  9650. } else {
  9651. this.div.draggable = false;
  9652. this.editorDiv.contentEditable = true;
  9653. }
  9654. return this.div;
  9655. }
  9656. get contentDiv() {
  9657. return this.editorDiv;
  9658. }
  9659. static deserialize(data, parent, uiManager) {
  9660. const editor = super.deserialize(data, parent, uiManager);
  9661. editor.#fontSize = data.fontSize;
  9662. editor.#color = _util.Util.makeHexColor(...data.color);
  9663. editor.#content = data.value;
  9664. return editor;
  9665. }
  9666. serialize() {
  9667. if (this.isEmpty()) {
  9668. return null;
  9669. }
  9670. const padding = FreeTextEditor._internalPadding * this.parentScale;
  9671. const rect = this.getRect(padding, padding);
  9672. const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  9673. return {
  9674. annotationType: _util.AnnotationEditorType.FREETEXT,
  9675. color,
  9676. fontSize: this.#fontSize,
  9677. value: this.#content,
  9678. pageIndex: this.pageIndex,
  9679. rect,
  9680. rotation: this.rotation
  9681. };
  9682. }
  9683. }
  9684. exports.FreeTextEditor = FreeTextEditor;
  9685. /***/ }),
  9686. /* 24 */
  9687. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9688. Object.defineProperty(exports, "__esModule", ({
  9689. value: true
  9690. }));
  9691. exports.InkEditor = void 0;
  9692. Object.defineProperty(exports, "fitCurve", ({
  9693. enumerable: true,
  9694. get: function () {
  9695. return _pdfjsFitCurve.fitCurve;
  9696. }
  9697. }));
  9698. var _util = __w_pdfjs_require__(1);
  9699. var _editor = __w_pdfjs_require__(4);
  9700. var _pdfjsFitCurve = __w_pdfjs_require__(25);
  9701. var _tools = __w_pdfjs_require__(5);
  9702. const RESIZER_SIZE = 16;
  9703. const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
  9704. class InkEditor extends _editor.AnnotationEditor {
  9705. #aspectRatio = 0;
  9706. #baseHeight = 0;
  9707. #baseWidth = 0;
  9708. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  9709. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  9710. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  9711. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  9712. #disableEditing = false;
  9713. #isCanvasInitialized = false;
  9714. #lastPoint = null;
  9715. #observer = null;
  9716. #realWidth = 0;
  9717. #realHeight = 0;
  9718. #requestFrameCallback = null;
  9719. static _defaultColor = null;
  9720. static _defaultOpacity = 1;
  9721. static _defaultThickness = 1;
  9722. static _l10nPromise;
  9723. static _type = "ink";
  9724. constructor(params) {
  9725. super({
  9726. ...params,
  9727. name: "inkEditor"
  9728. });
  9729. this.color = params.color || null;
  9730. this.thickness = params.thickness || null;
  9731. this.opacity = params.opacity || null;
  9732. this.paths = [];
  9733. this.bezierPath2D = [];
  9734. this.currentPath = [];
  9735. this.scaleFactor = 1;
  9736. this.translationX = this.translationY = 0;
  9737. this.x = 0;
  9738. this.y = 0;
  9739. }
  9740. static initialize(l10n) {
  9741. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  9742. }
  9743. static updateDefaultParams(type, value) {
  9744. switch (type) {
  9745. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9746. InkEditor._defaultThickness = value;
  9747. break;
  9748. case _util.AnnotationEditorParamsType.INK_COLOR:
  9749. InkEditor._defaultColor = value;
  9750. break;
  9751. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9752. InkEditor._defaultOpacity = value / 100;
  9753. break;
  9754. }
  9755. }
  9756. updateParams(type, value) {
  9757. switch (type) {
  9758. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  9759. this.#updateThickness(value);
  9760. break;
  9761. case _util.AnnotationEditorParamsType.INK_COLOR:
  9762. this.#updateColor(value);
  9763. break;
  9764. case _util.AnnotationEditorParamsType.INK_OPACITY:
  9765. this.#updateOpacity(value);
  9766. break;
  9767. }
  9768. }
  9769. static get defaultPropertiesToUpdate() {
  9770. 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)]];
  9771. }
  9772. get propertiesToUpdate() {
  9773. 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))]];
  9774. }
  9775. #updateThickness(thickness) {
  9776. const savedThickness = this.thickness;
  9777. this.addCommands({
  9778. cmd: () => {
  9779. this.thickness = thickness;
  9780. this.#fitToContent();
  9781. },
  9782. undo: () => {
  9783. this.thickness = savedThickness;
  9784. this.#fitToContent();
  9785. },
  9786. mustExec: true,
  9787. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  9788. overwriteIfSameType: true,
  9789. keepUndo: true
  9790. });
  9791. }
  9792. #updateColor(color) {
  9793. const savedColor = this.color;
  9794. this.addCommands({
  9795. cmd: () => {
  9796. this.color = color;
  9797. this.#redraw();
  9798. },
  9799. undo: () => {
  9800. this.color = savedColor;
  9801. this.#redraw();
  9802. },
  9803. mustExec: true,
  9804. type: _util.AnnotationEditorParamsType.INK_COLOR,
  9805. overwriteIfSameType: true,
  9806. keepUndo: true
  9807. });
  9808. }
  9809. #updateOpacity(opacity) {
  9810. opacity /= 100;
  9811. const savedOpacity = this.opacity;
  9812. this.addCommands({
  9813. cmd: () => {
  9814. this.opacity = opacity;
  9815. this.#redraw();
  9816. },
  9817. undo: () => {
  9818. this.opacity = savedOpacity;
  9819. this.#redraw();
  9820. },
  9821. mustExec: true,
  9822. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  9823. overwriteIfSameType: true,
  9824. keepUndo: true
  9825. });
  9826. }
  9827. rebuild() {
  9828. super.rebuild();
  9829. if (this.div === null) {
  9830. return;
  9831. }
  9832. if (!this.canvas) {
  9833. this.#createCanvas();
  9834. this.#createObserver();
  9835. }
  9836. if (!this.isAttachedToDOM) {
  9837. this.parent.add(this);
  9838. this.#setCanvasDims();
  9839. }
  9840. this.#fitToContent();
  9841. }
  9842. remove() {
  9843. if (this.canvas === null) {
  9844. return;
  9845. }
  9846. if (!this.isEmpty()) {
  9847. this.commit();
  9848. }
  9849. this.canvas.width = this.canvas.height = 0;
  9850. this.canvas.remove();
  9851. this.canvas = null;
  9852. this.#observer.disconnect();
  9853. this.#observer = null;
  9854. super.remove();
  9855. }
  9856. setParent(parent) {
  9857. if (!this.parent && parent) {
  9858. this._uiManager.removeShouldRescale(this);
  9859. } else if (this.parent && parent === null) {
  9860. this._uiManager.addShouldRescale(this);
  9861. }
  9862. super.setParent(parent);
  9863. }
  9864. onScaleChanging() {
  9865. const [parentWidth, parentHeight] = this.parentDimensions;
  9866. const width = this.width * parentWidth;
  9867. const height = this.height * parentHeight;
  9868. this.setDimensions(width, height);
  9869. }
  9870. enableEditMode() {
  9871. if (this.#disableEditing || this.canvas === null) {
  9872. return;
  9873. }
  9874. super.enableEditMode();
  9875. this.div.draggable = false;
  9876. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  9877. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  9878. }
  9879. disableEditMode() {
  9880. if (!this.isInEditMode() || this.canvas === null) {
  9881. return;
  9882. }
  9883. super.disableEditMode();
  9884. this.div.draggable = !this.isEmpty();
  9885. this.div.classList.remove("editing");
  9886. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  9887. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  9888. }
  9889. onceAdded() {
  9890. this.div.draggable = !this.isEmpty();
  9891. }
  9892. isEmpty() {
  9893. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  9894. }
  9895. #getInitialBBox() {
  9896. const {
  9897. parentRotation,
  9898. parentDimensions: [width, height]
  9899. } = this;
  9900. switch (parentRotation) {
  9901. case 90:
  9902. return [0, height, height, width];
  9903. case 180:
  9904. return [width, height, width, height];
  9905. case 270:
  9906. return [width, 0, height, width];
  9907. default:
  9908. return [0, 0, width, height];
  9909. }
  9910. }
  9911. #setStroke() {
  9912. const {
  9913. ctx,
  9914. color,
  9915. opacity,
  9916. thickness,
  9917. parentScale,
  9918. scaleFactor
  9919. } = this;
  9920. ctx.lineWidth = thickness * parentScale / scaleFactor;
  9921. ctx.lineCap = "round";
  9922. ctx.lineJoin = "round";
  9923. ctx.miterLimit = 10;
  9924. ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
  9925. }
  9926. #startDrawing(x, y) {
  9927. this.isEditing = true;
  9928. if (!this.#isCanvasInitialized) {
  9929. this.#isCanvasInitialized = true;
  9930. this.#setCanvasDims();
  9931. this.thickness ||= InkEditor._defaultThickness;
  9932. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  9933. this.opacity ??= InkEditor._defaultOpacity;
  9934. }
  9935. this.currentPath.push([x, y]);
  9936. this.#lastPoint = null;
  9937. this.#setStroke();
  9938. this.ctx.beginPath();
  9939. this.ctx.moveTo(x, y);
  9940. this.#requestFrameCallback = () => {
  9941. if (!this.#requestFrameCallback) {
  9942. return;
  9943. }
  9944. if (this.#lastPoint) {
  9945. if (this.isEmpty()) {
  9946. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  9947. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  9948. } else {
  9949. this.#redraw();
  9950. }
  9951. this.ctx.lineTo(...this.#lastPoint);
  9952. this.#lastPoint = null;
  9953. this.ctx.stroke();
  9954. }
  9955. window.requestAnimationFrame(this.#requestFrameCallback);
  9956. };
  9957. window.requestAnimationFrame(this.#requestFrameCallback);
  9958. }
  9959. #draw(x, y) {
  9960. const [lastX, lastY] = this.currentPath.at(-1);
  9961. if (x === lastX && y === lastY) {
  9962. return;
  9963. }
  9964. this.currentPath.push([x, y]);
  9965. this.#lastPoint = [x, y];
  9966. }
  9967. #stopDrawing(x, y) {
  9968. this.ctx.closePath();
  9969. this.#requestFrameCallback = null;
  9970. x = Math.min(Math.max(x, 0), this.canvas.width);
  9971. y = Math.min(Math.max(y, 0), this.canvas.height);
  9972. const [lastX, lastY] = this.currentPath.at(-1);
  9973. if (x !== lastX || y !== lastY) {
  9974. this.currentPath.push([x, y]);
  9975. }
  9976. let bezier;
  9977. if (this.currentPath.length !== 1) {
  9978. bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
  9979. } else {
  9980. const xy = [x, y];
  9981. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  9982. }
  9983. const path2D = InkEditor.#buildPath2D(bezier);
  9984. this.currentPath.length = 0;
  9985. const cmd = () => {
  9986. this.paths.push(bezier);
  9987. this.bezierPath2D.push(path2D);
  9988. this.rebuild();
  9989. };
  9990. const undo = () => {
  9991. this.paths.pop();
  9992. this.bezierPath2D.pop();
  9993. if (this.paths.length === 0) {
  9994. this.remove();
  9995. } else {
  9996. if (!this.canvas) {
  9997. this.#createCanvas();
  9998. this.#createObserver();
  9999. }
  10000. this.#fitToContent();
  10001. }
  10002. };
  10003. this.addCommands({
  10004. cmd,
  10005. undo,
  10006. mustExec: true
  10007. });
  10008. }
  10009. #redraw() {
  10010. if (this.isEmpty()) {
  10011. this.#updateTransform();
  10012. return;
  10013. }
  10014. this.#setStroke();
  10015. const {
  10016. canvas,
  10017. ctx
  10018. } = this;
  10019. ctx.setTransform(1, 0, 0, 1, 0, 0);
  10020. ctx.clearRect(0, 0, canvas.width, canvas.height);
  10021. this.#updateTransform();
  10022. for (const path of this.bezierPath2D) {
  10023. ctx.stroke(path);
  10024. }
  10025. }
  10026. commit() {
  10027. if (this.#disableEditing) {
  10028. return;
  10029. }
  10030. super.commit();
  10031. this.isEditing = false;
  10032. this.disableEditMode();
  10033. this.setInForeground();
  10034. this.#disableEditing = true;
  10035. this.div.classList.add("disabled");
  10036. this.#fitToContent(true);
  10037. this.parent.addInkEditorIfNeeded(true);
  10038. this.parent.moveEditorInDOM(this);
  10039. this.div.focus({
  10040. preventScroll: true
  10041. });
  10042. }
  10043. focusin(event) {
  10044. super.focusin(event);
  10045. this.enableEditMode();
  10046. }
  10047. canvasPointerdown(event) {
  10048. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  10049. return;
  10050. }
  10051. this.setInForeground();
  10052. if (event.type !== "mouse") {
  10053. this.div.focus();
  10054. }
  10055. event.stopPropagation();
  10056. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  10057. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  10058. this.#startDrawing(event.offsetX, event.offsetY);
  10059. }
  10060. canvasPointermove(event) {
  10061. event.stopPropagation();
  10062. this.#draw(event.offsetX, event.offsetY);
  10063. }
  10064. canvasPointerup(event) {
  10065. if (event.button !== 0) {
  10066. return;
  10067. }
  10068. if (this.isInEditMode() && this.currentPath.length !== 0) {
  10069. event.stopPropagation();
  10070. this.#endDrawing(event);
  10071. this.setInBackground();
  10072. }
  10073. }
  10074. canvasPointerleave(event) {
  10075. this.#endDrawing(event);
  10076. this.setInBackground();
  10077. }
  10078. #endDrawing(event) {
  10079. this.#stopDrawing(event.offsetX, event.offsetY);
  10080. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  10081. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  10082. this.addToAnnotationStorage();
  10083. }
  10084. #createCanvas() {
  10085. this.canvas = document.createElement("canvas");
  10086. this.canvas.width = this.canvas.height = 0;
  10087. this.canvas.className = "inkEditorCanvas";
  10088. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  10089. this.div.append(this.canvas);
  10090. this.ctx = this.canvas.getContext("2d");
  10091. }
  10092. #createObserver() {
  10093. let timeoutId = null;
  10094. this.#observer = new ResizeObserver(entries => {
  10095. const rect = entries[0].contentRect;
  10096. if (rect.width && rect.height) {
  10097. if (timeoutId !== null) {
  10098. clearTimeout(timeoutId);
  10099. }
  10100. timeoutId = setTimeout(() => {
  10101. this.fixDims();
  10102. timeoutId = null;
  10103. }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
  10104. this.setDimensions(rect.width, rect.height);
  10105. }
  10106. });
  10107. this.#observer.observe(this.div);
  10108. }
  10109. render() {
  10110. if (this.div) {
  10111. return this.div;
  10112. }
  10113. let baseX, baseY;
  10114. if (this.width) {
  10115. baseX = this.x;
  10116. baseY = this.y;
  10117. }
  10118. super.render();
  10119. InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  10120. const [x, y, w, h] = this.#getInitialBBox();
  10121. this.setAt(x, y, 0, 0);
  10122. this.setDims(w, h);
  10123. this.#createCanvas();
  10124. if (this.width) {
  10125. const [parentWidth, parentHeight] = this.parentDimensions;
  10126. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  10127. this.#isCanvasInitialized = true;
  10128. this.#setCanvasDims();
  10129. this.setDims(this.width * parentWidth, this.height * parentHeight);
  10130. this.#redraw();
  10131. this.#setMinDims();
  10132. this.div.classList.add("disabled");
  10133. } else {
  10134. this.div.classList.add("editing");
  10135. this.enableEditMode();
  10136. }
  10137. this.#createObserver();
  10138. return this.div;
  10139. }
  10140. #setCanvasDims() {
  10141. if (!this.#isCanvasInitialized) {
  10142. return;
  10143. }
  10144. const [parentWidth, parentHeight] = this.parentDimensions;
  10145. this.canvas.width = Math.ceil(this.width * parentWidth);
  10146. this.canvas.height = Math.ceil(this.height * parentHeight);
  10147. this.#updateTransform();
  10148. }
  10149. setDimensions(width, height) {
  10150. const roundedWidth = Math.round(width);
  10151. const roundedHeight = Math.round(height);
  10152. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  10153. return;
  10154. }
  10155. this.#realWidth = roundedWidth;
  10156. this.#realHeight = roundedHeight;
  10157. this.canvas.style.visibility = "hidden";
  10158. if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
  10159. height = Math.ceil(width / this.#aspectRatio);
  10160. this.setDims(width, height);
  10161. }
  10162. const [parentWidth, parentHeight] = this.parentDimensions;
  10163. this.width = width / parentWidth;
  10164. this.height = height / parentHeight;
  10165. if (this.#disableEditing) {
  10166. this.#setScaleFactor(width, height);
  10167. }
  10168. this.#setCanvasDims();
  10169. this.#redraw();
  10170. this.canvas.style.visibility = "visible";
  10171. }
  10172. #setScaleFactor(width, height) {
  10173. const padding = this.#getPadding();
  10174. const scaleFactorW = (width - padding) / this.#baseWidth;
  10175. const scaleFactorH = (height - padding) / this.#baseHeight;
  10176. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  10177. }
  10178. #updateTransform() {
  10179. const padding = this.#getPadding() / 2;
  10180. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  10181. }
  10182. static #buildPath2D(bezier) {
  10183. const path2D = new Path2D();
  10184. for (let i = 0, ii = bezier.length; i < ii; i++) {
  10185. const [first, control1, control2, second] = bezier[i];
  10186. if (i === 0) {
  10187. path2D.moveTo(...first);
  10188. }
  10189. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  10190. }
  10191. return path2D;
  10192. }
  10193. #serializePaths(s, tx, ty, h) {
  10194. const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
  10195. const paths = [];
  10196. const padding = this.thickness / 2;
  10197. let buffer, points;
  10198. for (const bezier of this.paths) {
  10199. buffer = [];
  10200. points = [];
  10201. for (let i = 0, ii = bezier.length; i < ii; i++) {
  10202. const [first, control1, control2, second] = bezier[i];
  10203. const p10 = s * (first[0] + tx) + padding;
  10204. const p11 = h - s * (first[1] + ty) - padding;
  10205. const p20 = s * (control1[0] + tx) + padding;
  10206. const p21 = h - s * (control1[1] + ty) - padding;
  10207. const p30 = s * (control2[0] + tx) + padding;
  10208. const p31 = h - s * (control2[1] + ty) - padding;
  10209. const p40 = s * (second[0] + tx) + padding;
  10210. const p41 = h - s * (second[1] + ty) - padding;
  10211. if (i === 0) {
  10212. buffer.push(p10, p11);
  10213. points.push(p10, p11);
  10214. }
  10215. buffer.push(p20, p21, p30, p31, p40, p41);
  10216. this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
  10217. }
  10218. paths.push({
  10219. bezier: buffer,
  10220. points
  10221. });
  10222. }
  10223. return paths;
  10224. }
  10225. #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
  10226. if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
  10227. points.push(p40, p41);
  10228. return;
  10229. }
  10230. for (let i = 1; i < n - 1; i++) {
  10231. const t = i / n;
  10232. const mt = 1 - t;
  10233. let q10 = t * p10 + mt * p20;
  10234. let q11 = t * p11 + mt * p21;
  10235. let q20 = t * p20 + mt * p30;
  10236. let q21 = t * p21 + mt * p31;
  10237. const q30 = t * p30 + mt * p40;
  10238. const q31 = t * p31 + mt * p41;
  10239. q10 = t * q10 + mt * q20;
  10240. q11 = t * q11 + mt * q21;
  10241. q20 = t * q20 + mt * q30;
  10242. q21 = t * q21 + mt * q31;
  10243. q10 = t * q10 + mt * q20;
  10244. q11 = t * q11 + mt * q21;
  10245. points.push(q10, q11);
  10246. }
  10247. points.push(p40, p41);
  10248. }
  10249. #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
  10250. const tol = 10;
  10251. const ax = (3 * p20 - 2 * p10 - p40) ** 2;
  10252. const ay = (3 * p21 - 2 * p11 - p41) ** 2;
  10253. const bx = (3 * p30 - p10 - 2 * p40) ** 2;
  10254. const by = (3 * p31 - p11 - 2 * p41) ** 2;
  10255. return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  10256. }
  10257. #getBbox() {
  10258. let xMin = Infinity;
  10259. let xMax = -Infinity;
  10260. let yMin = Infinity;
  10261. let yMax = -Infinity;
  10262. for (const path of this.paths) {
  10263. for (const [first, control1, control2, second] of path) {
  10264. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  10265. xMin = Math.min(xMin, bbox[0]);
  10266. yMin = Math.min(yMin, bbox[1]);
  10267. xMax = Math.max(xMax, bbox[2]);
  10268. yMax = Math.max(yMax, bbox[3]);
  10269. }
  10270. }
  10271. return [xMin, yMin, xMax, yMax];
  10272. }
  10273. #getPadding() {
  10274. return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  10275. }
  10276. #fitToContent(firstTime = false) {
  10277. if (this.isEmpty()) {
  10278. return;
  10279. }
  10280. if (!this.#disableEditing) {
  10281. this.#redraw();
  10282. return;
  10283. }
  10284. const bbox = this.#getBbox();
  10285. const padding = this.#getPadding();
  10286. this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  10287. this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  10288. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  10289. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  10290. const [parentWidth, parentHeight] = this.parentDimensions;
  10291. this.width = width / parentWidth;
  10292. this.height = height / parentHeight;
  10293. this.#aspectRatio = width / height;
  10294. this.#setMinDims();
  10295. const prevTranslationX = this.translationX;
  10296. const prevTranslationY = this.translationY;
  10297. this.translationX = -bbox[0];
  10298. this.translationY = -bbox[1];
  10299. this.#setCanvasDims();
  10300. this.#redraw();
  10301. this.#realWidth = width;
  10302. this.#realHeight = height;
  10303. this.setDims(width, height);
  10304. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  10305. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  10306. }
  10307. #setMinDims() {
  10308. const {
  10309. style
  10310. } = this.div;
  10311. if (this.#aspectRatio >= 1) {
  10312. style.minHeight = `${RESIZER_SIZE}px`;
  10313. style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
  10314. } else {
  10315. style.minWidth = `${RESIZER_SIZE}px`;
  10316. style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
  10317. }
  10318. }
  10319. static deserialize(data, parent, uiManager) {
  10320. const editor = super.deserialize(data, parent, uiManager);
  10321. editor.thickness = data.thickness;
  10322. editor.color = _util.Util.makeHexColor(...data.color);
  10323. editor.opacity = data.opacity;
  10324. const [pageWidth, pageHeight] = editor.pageDimensions;
  10325. const width = editor.width * pageWidth;
  10326. const height = editor.height * pageHeight;
  10327. const scaleFactor = editor.parentScale;
  10328. const padding = data.thickness / 2;
  10329. editor.#aspectRatio = width / height;
  10330. editor.#disableEditing = true;
  10331. editor.#realWidth = Math.round(width);
  10332. editor.#realHeight = Math.round(height);
  10333. for (const {
  10334. bezier
  10335. } of data.paths) {
  10336. const path = [];
  10337. editor.paths.push(path);
  10338. let p0 = scaleFactor * (bezier[0] - padding);
  10339. let p1 = scaleFactor * (height - bezier[1] - padding);
  10340. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  10341. const p10 = scaleFactor * (bezier[i] - padding);
  10342. const p11 = scaleFactor * (height - bezier[i + 1] - padding);
  10343. const p20 = scaleFactor * (bezier[i + 2] - padding);
  10344. const p21 = scaleFactor * (height - bezier[i + 3] - padding);
  10345. const p30 = scaleFactor * (bezier[i + 4] - padding);
  10346. const p31 = scaleFactor * (height - bezier[i + 5] - padding);
  10347. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  10348. p0 = p30;
  10349. p1 = p31;
  10350. }
  10351. const path2D = this.#buildPath2D(path);
  10352. editor.bezierPath2D.push(path2D);
  10353. }
  10354. const bbox = editor.#getBbox();
  10355. editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  10356. editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  10357. editor.#setScaleFactor(width, height);
  10358. return editor;
  10359. }
  10360. serialize() {
  10361. if (this.isEmpty()) {
  10362. return null;
  10363. }
  10364. const rect = this.getRect(0, 0);
  10365. const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
  10366. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  10367. return {
  10368. annotationType: _util.AnnotationEditorType.INK,
  10369. color,
  10370. thickness: this.thickness,
  10371. opacity: this.opacity,
  10372. paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, height),
  10373. pageIndex: this.pageIndex,
  10374. rect,
  10375. rotation: this.rotation
  10376. };
  10377. }
  10378. }
  10379. exports.InkEditor = InkEditor;
  10380. /***/ }),
  10381. /* 25 */
  10382. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10383. Object.defineProperty(exports, "__esModule", ({
  10384. value: true
  10385. }));
  10386. exports.fitCurve = void 0;
  10387. const fitCurve = __w_pdfjs_require__(26);
  10388. exports.fitCurve = fitCurve;
  10389. /***/ }),
  10390. /* 26 */
  10391. /***/ ((module) => {
  10392. function fitCurve(points, maxError, progressCallback) {
  10393. if (!Array.isArray(points)) {
  10394. throw new TypeError("First argument should be an array");
  10395. }
  10396. points.forEach(point => {
  10397. if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
  10398. throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
  10399. }
  10400. });
  10401. points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  10402. if (points.length < 2) {
  10403. return [];
  10404. }
  10405. const len = points.length;
  10406. const leftTangent = createTangent(points[1], points[0]);
  10407. const rightTangent = createTangent(points[len - 2], points[len - 1]);
  10408. return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
  10409. }
  10410. function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  10411. const MaxIterations = 20;
  10412. var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  10413. if (points.length === 2) {
  10414. dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
  10415. bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
  10416. return [bezCurve];
  10417. }
  10418. u = chordLengthParameterize(points);
  10419. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  10420. if (maxError === 0 || maxError < error) {
  10421. return [bezCurve];
  10422. }
  10423. if (maxError < error * error) {
  10424. uPrime = u;
  10425. prevErr = maxError;
  10426. prevSplit = splitPoint;
  10427. for (i = 0; i < MaxIterations; i++) {
  10428. uPrime = reparameterize(bezCurve, points, uPrime);
  10429. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
  10430. if (maxError < error) {
  10431. return [bezCurve];
  10432. } else if (splitPoint === prevSplit) {
  10433. let errChange = maxError / prevErr;
  10434. if (errChange > .9999 && errChange < 1.0001) {
  10435. break;
  10436. }
  10437. }
  10438. prevErr = maxError;
  10439. prevSplit = splitPoint;
  10440. }
  10441. }
  10442. beziers = [];
  10443. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  10444. if (centerVector.every(val => val === 0)) {
  10445. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
  10446. [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  10447. }
  10448. toCenterTangent = maths.normalize(centerVector);
  10449. fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  10450. beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  10451. beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  10452. return beziers;
  10453. }
  10454. ;
  10455. function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  10456. var bezCurve, maxError, splitPoint;
  10457. bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  10458. [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  10459. if (progressCallback) {
  10460. progressCallback({
  10461. bez: bezCurve,
  10462. points: points,
  10463. params: paramsOrig,
  10464. maxErr: maxError,
  10465. maxPoint: splitPoint
  10466. });
  10467. }
  10468. return [bezCurve, maxError, splitPoint];
  10469. }
  10470. function generateBezier(points, parameters, leftTangent, rightTangent) {
  10471. var bezCurve,
  10472. A,
  10473. a,
  10474. C,
  10475. X,
  10476. det_C0_C1,
  10477. det_C0_X,
  10478. det_X_C1,
  10479. alpha_l,
  10480. alpha_r,
  10481. epsilon,
  10482. segLength,
  10483. i,
  10484. len,
  10485. tmp,
  10486. u,
  10487. ux,
  10488. firstPoint = points[0],
  10489. lastPoint = points[points.length - 1];
  10490. bezCurve = [firstPoint, null, null, lastPoint];
  10491. A = maths.zeros_Xx2x2(parameters.length);
  10492. for (i = 0, len = parameters.length; i < len; i++) {
  10493. u = parameters[i];
  10494. ux = 1 - u;
  10495. a = A[i];
  10496. a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
  10497. a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  10498. }
  10499. C = [[0, 0], [0, 0]];
  10500. X = [0, 0];
  10501. for (i = 0, len = points.length; i < len; i++) {
  10502. u = parameters[i];
  10503. a = A[i];
  10504. C[0][0] += maths.dot(a[0], a[0]);
  10505. C[0][1] += maths.dot(a[0], a[1]);
  10506. C[1][0] += maths.dot(a[0], a[1]);
  10507. C[1][1] += maths.dot(a[1], a[1]);
  10508. tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
  10509. X[0] += maths.dot(a[0], tmp);
  10510. X[1] += maths.dot(a[1], tmp);
  10511. }
  10512. det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  10513. det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  10514. det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  10515. alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  10516. alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  10517. segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  10518. epsilon = 1.0e-6 * segLength;
  10519. if (alpha_l < epsilon || alpha_r < epsilon) {
  10520. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
  10521. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  10522. } else {
  10523. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
  10524. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  10525. }
  10526. return bezCurve;
  10527. }
  10528. ;
  10529. function reparameterize(bezier, points, parameters) {
  10530. return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
  10531. }
  10532. ;
  10533. function newtonRaphsonRootFind(bez, point, u) {
  10534. var d = maths.subtract(bezier.q(bez, u), point),
  10535. qprime = bezier.qprime(bez, u),
  10536. numerator = maths.mulMatrix(d, qprime),
  10537. denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  10538. if (denominator === 0) {
  10539. return u;
  10540. } else {
  10541. return u - numerator / denominator;
  10542. }
  10543. }
  10544. ;
  10545. function chordLengthParameterize(points) {
  10546. var u = [],
  10547. currU,
  10548. prevU,
  10549. prevP;
  10550. points.forEach((p, i) => {
  10551. currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
  10552. u.push(currU);
  10553. prevU = currU;
  10554. prevP = p;
  10555. });
  10556. u = u.map(x => x / prevU);
  10557. return u;
  10558. }
  10559. ;
  10560. function computeMaxError(points, bez, parameters) {
  10561. var dist, maxDist, splitPoint, v, i, count, point, t;
  10562. maxDist = 0;
  10563. splitPoint = Math.floor(points.length / 2);
  10564. const t_distMap = mapTtoRelativeDistances(bez, 10);
  10565. for (i = 0, count = points.length; i < count; i++) {
  10566. point = points[i];
  10567. t = find_t(bez, parameters[i], t_distMap, 10);
  10568. v = maths.subtract(bezier.q(bez, t), point);
  10569. dist = v[0] * v[0] + v[1] * v[1];
  10570. if (dist > maxDist) {
  10571. maxDist = dist;
  10572. splitPoint = i;
  10573. }
  10574. }
  10575. return [maxDist, splitPoint];
  10576. }
  10577. ;
  10578. var mapTtoRelativeDistances = function (bez, B_parts) {
  10579. var B_t_curr;
  10580. var B_t_dist = [0];
  10581. var B_t_prev = bez[0];
  10582. var sumLen = 0;
  10583. for (var i = 1; i <= B_parts; i++) {
  10584. B_t_curr = bezier.q(bez, i / B_parts);
  10585. sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
  10586. B_t_dist.push(sumLen);
  10587. B_t_prev = B_t_curr;
  10588. }
  10589. B_t_dist = B_t_dist.map(x => x / sumLen);
  10590. return B_t_dist;
  10591. };
  10592. function find_t(bez, param, t_distMap, B_parts) {
  10593. if (param < 0) {
  10594. return 0;
  10595. }
  10596. if (param > 1) {
  10597. return 1;
  10598. }
  10599. var lenMax, lenMin, tMax, tMin, t;
  10600. for (var i = 1; i <= B_parts; i++) {
  10601. if (param <= t_distMap[i]) {
  10602. tMin = (i - 1) / B_parts;
  10603. tMax = i / B_parts;
  10604. lenMin = t_distMap[i - 1];
  10605. lenMax = t_distMap[i];
  10606. t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
  10607. break;
  10608. }
  10609. }
  10610. return t;
  10611. }
  10612. function createTangent(pointA, pointB) {
  10613. return maths.normalize(maths.subtract(pointA, pointB));
  10614. }
  10615. class maths {
  10616. static zeros_Xx2x2(x) {
  10617. var zs = [];
  10618. while (x--) {
  10619. zs.push([0, 0]);
  10620. }
  10621. return zs;
  10622. }
  10623. static mulItems(items, multiplier) {
  10624. return items.map(x => x * multiplier);
  10625. }
  10626. static mulMatrix(m1, m2) {
  10627. return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  10628. }
  10629. static subtract(arr1, arr2) {
  10630. return arr1.map((x1, i) => x1 - arr2[i]);
  10631. }
  10632. static addArrays(arr1, arr2) {
  10633. return arr1.map((x1, i) => x1 + arr2[i]);
  10634. }
  10635. static addItems(items, addition) {
  10636. return items.map(x => x + addition);
  10637. }
  10638. static sum(items) {
  10639. return items.reduce((sum, x) => sum + x);
  10640. }
  10641. static dot(m1, m2) {
  10642. return maths.mulMatrix(m1, m2);
  10643. }
  10644. static vectorLen(v) {
  10645. return Math.hypot(...v);
  10646. }
  10647. static divItems(items, divisor) {
  10648. return items.map(x => x / divisor);
  10649. }
  10650. static squareItems(items) {
  10651. return items.map(x => x * x);
  10652. }
  10653. static normalize(v) {
  10654. return this.divItems(v, this.vectorLen(v));
  10655. }
  10656. }
  10657. class bezier {
  10658. static q(ctrlPoly, t) {
  10659. var tx = 1.0 - t;
  10660. var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
  10661. pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
  10662. pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
  10663. pD = maths.mulItems(ctrlPoly[3], t * t * t);
  10664. return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  10665. }
  10666. static qprime(ctrlPoly, t) {
  10667. var tx = 1.0 - t;
  10668. var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
  10669. pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
  10670. pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
  10671. return maths.addArrays(maths.addArrays(pA, pB), pC);
  10672. }
  10673. static qprimeprime(ctrlPoly, t) {
  10674. 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));
  10675. }
  10676. }
  10677. module.exports = fitCurve;
  10678. module.exports.fitCubic = fitCubic;
  10679. module.exports.createTangent = createTangent;
  10680. /***/ }),
  10681. /* 27 */
  10682. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10683. Object.defineProperty(exports, "__esModule", ({
  10684. value: true
  10685. }));
  10686. exports.AnnotationLayer = void 0;
  10687. var _util = __w_pdfjs_require__(1);
  10688. var _display_utils = __w_pdfjs_require__(6);
  10689. var _annotation_storage = __w_pdfjs_require__(3);
  10690. var _scripting_utils = __w_pdfjs_require__(28);
  10691. var _xfa_layer = __w_pdfjs_require__(29);
  10692. const DEFAULT_TAB_INDEX = 1000;
  10693. const DEFAULT_FONT_SIZE = 9;
  10694. const GetElementsByNameSet = new WeakSet();
  10695. function getRectDims(rect) {
  10696. return {
  10697. width: rect[2] - rect[0],
  10698. height: rect[3] - rect[1]
  10699. };
  10700. }
  10701. class AnnotationElementFactory {
  10702. static create(parameters) {
  10703. const subtype = parameters.data.annotationType;
  10704. switch (subtype) {
  10705. case _util.AnnotationType.LINK:
  10706. return new LinkAnnotationElement(parameters);
  10707. case _util.AnnotationType.TEXT:
  10708. return new TextAnnotationElement(parameters);
  10709. case _util.AnnotationType.WIDGET:
  10710. const fieldType = parameters.data.fieldType;
  10711. switch (fieldType) {
  10712. case "Tx":
  10713. return new TextWidgetAnnotationElement(parameters);
  10714. case "Btn":
  10715. if (parameters.data.radioButton) {
  10716. return new RadioButtonWidgetAnnotationElement(parameters);
  10717. } else if (parameters.data.checkBox) {
  10718. return new CheckboxWidgetAnnotationElement(parameters);
  10719. }
  10720. return new PushButtonWidgetAnnotationElement(parameters);
  10721. case "Ch":
  10722. return new ChoiceWidgetAnnotationElement(parameters);
  10723. }
  10724. return new WidgetAnnotationElement(parameters);
  10725. case _util.AnnotationType.POPUP:
  10726. return new PopupAnnotationElement(parameters);
  10727. case _util.AnnotationType.FREETEXT:
  10728. return new FreeTextAnnotationElement(parameters);
  10729. case _util.AnnotationType.LINE:
  10730. return new LineAnnotationElement(parameters);
  10731. case _util.AnnotationType.SQUARE:
  10732. return new SquareAnnotationElement(parameters);
  10733. case _util.AnnotationType.CIRCLE:
  10734. return new CircleAnnotationElement(parameters);
  10735. case _util.AnnotationType.POLYLINE:
  10736. return new PolylineAnnotationElement(parameters);
  10737. case _util.AnnotationType.CARET:
  10738. return new CaretAnnotationElement(parameters);
  10739. case _util.AnnotationType.INK:
  10740. return new InkAnnotationElement(parameters);
  10741. case _util.AnnotationType.POLYGON:
  10742. return new PolygonAnnotationElement(parameters);
  10743. case _util.AnnotationType.HIGHLIGHT:
  10744. return new HighlightAnnotationElement(parameters);
  10745. case _util.AnnotationType.UNDERLINE:
  10746. return new UnderlineAnnotationElement(parameters);
  10747. case _util.AnnotationType.SQUIGGLY:
  10748. return new SquigglyAnnotationElement(parameters);
  10749. case _util.AnnotationType.STRIKEOUT:
  10750. return new StrikeOutAnnotationElement(parameters);
  10751. case _util.AnnotationType.STAMP:
  10752. return new StampAnnotationElement(parameters);
  10753. case _util.AnnotationType.FILEATTACHMENT:
  10754. return new FileAttachmentAnnotationElement(parameters);
  10755. default:
  10756. return new AnnotationElement(parameters);
  10757. }
  10758. }
  10759. }
  10760. class AnnotationElement {
  10761. constructor(parameters, {
  10762. isRenderable = false,
  10763. ignoreBorder = false,
  10764. createQuadrilaterals = false
  10765. } = {}) {
  10766. this.isRenderable = isRenderable;
  10767. this.data = parameters.data;
  10768. this.layer = parameters.layer;
  10769. this.page = parameters.page;
  10770. this.viewport = parameters.viewport;
  10771. this.linkService = parameters.linkService;
  10772. this.downloadManager = parameters.downloadManager;
  10773. this.imageResourcesPath = parameters.imageResourcesPath;
  10774. this.renderForms = parameters.renderForms;
  10775. this.svgFactory = parameters.svgFactory;
  10776. this.annotationStorage = parameters.annotationStorage;
  10777. this.enableScripting = parameters.enableScripting;
  10778. this.hasJSActions = parameters.hasJSActions;
  10779. this._fieldObjects = parameters.fieldObjects;
  10780. if (isRenderable) {
  10781. this.container = this._createContainer(ignoreBorder);
  10782. }
  10783. if (createQuadrilaterals) {
  10784. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  10785. }
  10786. }
  10787. _createContainer(ignoreBorder = false) {
  10788. const {
  10789. data,
  10790. page,
  10791. viewport
  10792. } = this;
  10793. const container = document.createElement("section");
  10794. container.setAttribute("data-annotation-id", data.id);
  10795. const {
  10796. pageWidth,
  10797. pageHeight,
  10798. pageX,
  10799. pageY
  10800. } = viewport.rawDims;
  10801. const {
  10802. width,
  10803. height
  10804. } = getRectDims(data.rect);
  10805. 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]]);
  10806. if (!ignoreBorder && data.borderStyle.width > 0) {
  10807. container.style.borderWidth = `${data.borderStyle.width}px`;
  10808. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  10809. const verticalRadius = data.borderStyle.verticalCornerRadius;
  10810. if (horizontalRadius > 0 || verticalRadius > 0) {
  10811. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  10812. container.style.borderRadius = radius;
  10813. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  10814. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  10815. container.style.borderRadius = radius;
  10816. }
  10817. switch (data.borderStyle.style) {
  10818. case _util.AnnotationBorderStyleType.SOLID:
  10819. container.style.borderStyle = "solid";
  10820. break;
  10821. case _util.AnnotationBorderStyleType.DASHED:
  10822. container.style.borderStyle = "dashed";
  10823. break;
  10824. case _util.AnnotationBorderStyleType.BEVELED:
  10825. (0, _util.warn)("Unimplemented border style: beveled");
  10826. break;
  10827. case _util.AnnotationBorderStyleType.INSET:
  10828. (0, _util.warn)("Unimplemented border style: inset");
  10829. break;
  10830. case _util.AnnotationBorderStyleType.UNDERLINE:
  10831. container.style.borderBottomStyle = "solid";
  10832. break;
  10833. default:
  10834. break;
  10835. }
  10836. const borderColor = data.borderColor || null;
  10837. if (borderColor) {
  10838. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  10839. } else {
  10840. container.style.borderWidth = 0;
  10841. }
  10842. }
  10843. container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  10844. container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  10845. const {
  10846. rotation
  10847. } = data;
  10848. if (data.hasOwnCanvas || rotation === 0) {
  10849. container.style.width = `${100 * width / pageWidth}%`;
  10850. container.style.height = `${100 * height / pageHeight}%`;
  10851. } else {
  10852. this.setRotation(rotation, container);
  10853. }
  10854. return container;
  10855. }
  10856. setRotation(angle, container = this.container) {
  10857. const {
  10858. pageWidth,
  10859. pageHeight
  10860. } = this.viewport.rawDims;
  10861. const {
  10862. width,
  10863. height
  10864. } = getRectDims(this.data.rect);
  10865. let elementWidth, elementHeight;
  10866. if (angle % 180 === 0) {
  10867. elementWidth = 100 * width / pageWidth;
  10868. elementHeight = 100 * height / pageHeight;
  10869. } else {
  10870. elementWidth = 100 * height / pageWidth;
  10871. elementHeight = 100 * width / pageHeight;
  10872. }
  10873. container.style.width = `${elementWidth}%`;
  10874. container.style.height = `${elementHeight}%`;
  10875. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  10876. }
  10877. get _commonActions() {
  10878. const setColor = (jsName, styleName, event) => {
  10879. const color = event.detail[jsName];
  10880. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  10881. };
  10882. return (0, _util.shadow)(this, "_commonActions", {
  10883. display: event => {
  10884. const hidden = event.detail.display % 2 === 1;
  10885. this.container.style.visibility = hidden ? "hidden" : "visible";
  10886. this.annotationStorage.setValue(this.data.id, {
  10887. hidden,
  10888. print: event.detail.display === 0 || event.detail.display === 3
  10889. });
  10890. },
  10891. print: event => {
  10892. this.annotationStorage.setValue(this.data.id, {
  10893. print: event.detail.print
  10894. });
  10895. },
  10896. hidden: event => {
  10897. this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
  10898. this.annotationStorage.setValue(this.data.id, {
  10899. hidden: event.detail.hidden
  10900. });
  10901. },
  10902. focus: event => {
  10903. setTimeout(() => event.target.focus({
  10904. preventScroll: false
  10905. }), 0);
  10906. },
  10907. userName: event => {
  10908. event.target.title = event.detail.userName;
  10909. },
  10910. readonly: event => {
  10911. if (event.detail.readonly) {
  10912. event.target.setAttribute("readonly", "");
  10913. } else {
  10914. event.target.removeAttribute("readonly");
  10915. }
  10916. },
  10917. required: event => {
  10918. this._setRequired(event.target, event.detail.required);
  10919. },
  10920. bgColor: event => {
  10921. setColor("bgColor", "backgroundColor", event);
  10922. },
  10923. fillColor: event => {
  10924. setColor("fillColor", "backgroundColor", event);
  10925. },
  10926. fgColor: event => {
  10927. setColor("fgColor", "color", event);
  10928. },
  10929. textColor: event => {
  10930. setColor("textColor", "color", event);
  10931. },
  10932. borderColor: event => {
  10933. setColor("borderColor", "borderColor", event);
  10934. },
  10935. strokeColor: event => {
  10936. setColor("strokeColor", "borderColor", event);
  10937. },
  10938. rotation: event => {
  10939. const angle = event.detail.rotation;
  10940. this.setRotation(angle);
  10941. this.annotationStorage.setValue(this.data.id, {
  10942. rotation: angle
  10943. });
  10944. }
  10945. });
  10946. }
  10947. _dispatchEventFromSandbox(actions, jsEvent) {
  10948. const commonActions = this._commonActions;
  10949. for (const name of Object.keys(jsEvent.detail)) {
  10950. const action = actions[name] || commonActions[name];
  10951. action?.(jsEvent);
  10952. }
  10953. }
  10954. _setDefaultPropertiesFromJS(element) {
  10955. if (!this.enableScripting) {
  10956. return;
  10957. }
  10958. const storedData = this.annotationStorage.getRawValue(this.data.id);
  10959. if (!storedData) {
  10960. return;
  10961. }
  10962. const commonActions = this._commonActions;
  10963. for (const [actionName, detail] of Object.entries(storedData)) {
  10964. const action = commonActions[actionName];
  10965. if (action) {
  10966. const eventProxy = {
  10967. detail: {
  10968. [actionName]: detail
  10969. },
  10970. target: element
  10971. };
  10972. action(eventProxy);
  10973. delete storedData[actionName];
  10974. }
  10975. }
  10976. }
  10977. _createQuadrilaterals(ignoreBorder = false) {
  10978. if (!this.data.quadPoints) {
  10979. return null;
  10980. }
  10981. const quadrilaterals = [];
  10982. const savedRect = this.data.rect;
  10983. for (const quadPoint of this.data.quadPoints) {
  10984. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  10985. quadrilaterals.push(this._createContainer(ignoreBorder));
  10986. }
  10987. this.data.rect = savedRect;
  10988. return quadrilaterals;
  10989. }
  10990. _createPopup(trigger, data) {
  10991. let container = this.container;
  10992. if (this.quadrilaterals) {
  10993. trigger = trigger || this.quadrilaterals;
  10994. container = this.quadrilaterals[0];
  10995. }
  10996. if (!trigger) {
  10997. trigger = document.createElement("div");
  10998. trigger.className = "popupTriggerArea";
  10999. container.append(trigger);
  11000. }
  11001. const popupElement = new PopupElement({
  11002. container,
  11003. trigger,
  11004. color: data.color,
  11005. titleObj: data.titleObj,
  11006. modificationDate: data.modificationDate,
  11007. contentsObj: data.contentsObj,
  11008. richText: data.richText,
  11009. hideWrapper: true
  11010. });
  11011. const popup = popupElement.render();
  11012. popup.style.left = "100%";
  11013. container.append(popup);
  11014. }
  11015. _renderQuadrilaterals(className) {
  11016. for (const quadrilateral of this.quadrilaterals) {
  11017. quadrilateral.className = className;
  11018. }
  11019. return this.quadrilaterals;
  11020. }
  11021. render() {
  11022. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  11023. }
  11024. _getElementsByName(name, skipId = null) {
  11025. const fields = [];
  11026. if (this._fieldObjects) {
  11027. const fieldObj = this._fieldObjects[name];
  11028. if (fieldObj) {
  11029. for (const {
  11030. page,
  11031. id,
  11032. exportValues
  11033. } of fieldObj) {
  11034. if (page === -1) {
  11035. continue;
  11036. }
  11037. if (id === skipId) {
  11038. continue;
  11039. }
  11040. const exportValue = typeof exportValues === "string" ? exportValues : null;
  11041. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  11042. if (domElement && !GetElementsByNameSet.has(domElement)) {
  11043. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  11044. continue;
  11045. }
  11046. fields.push({
  11047. id,
  11048. exportValue,
  11049. domElement
  11050. });
  11051. }
  11052. }
  11053. return fields;
  11054. }
  11055. for (const domElement of document.getElementsByName(name)) {
  11056. const {
  11057. exportValue
  11058. } = domElement;
  11059. const id = domElement.getAttribute("data-element-id");
  11060. if (id === skipId) {
  11061. continue;
  11062. }
  11063. if (!GetElementsByNameSet.has(domElement)) {
  11064. continue;
  11065. }
  11066. fields.push({
  11067. id,
  11068. exportValue,
  11069. domElement
  11070. });
  11071. }
  11072. return fields;
  11073. }
  11074. }
  11075. class LinkAnnotationElement extends AnnotationElement {
  11076. constructor(parameters, options = null) {
  11077. super(parameters, {
  11078. isRenderable: true,
  11079. ignoreBorder: !!options?.ignoreBorder,
  11080. createQuadrilaterals: true
  11081. });
  11082. this.isTooltipOnly = parameters.data.isTooltipOnly;
  11083. }
  11084. render() {
  11085. const {
  11086. data,
  11087. linkService
  11088. } = this;
  11089. const link = document.createElement("a");
  11090. link.setAttribute("data-element-id", data.id);
  11091. let isBound = false;
  11092. if (data.url) {
  11093. linkService.addLinkAttributes(link, data.url, data.newWindow);
  11094. isBound = true;
  11095. } else if (data.action) {
  11096. this._bindNamedAction(link, data.action);
  11097. isBound = true;
  11098. } else if (data.attachment) {
  11099. this._bindAttachment(link, data.attachment);
  11100. isBound = true;
  11101. } else if (data.setOCGState) {
  11102. this.#bindSetOCGState(link, data.setOCGState);
  11103. isBound = true;
  11104. } else if (data.dest) {
  11105. this._bindLink(link, data.dest);
  11106. isBound = true;
  11107. } else {
  11108. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  11109. this._bindJSAction(link, data);
  11110. isBound = true;
  11111. }
  11112. if (data.resetForm) {
  11113. this._bindResetFormAction(link, data.resetForm);
  11114. isBound = true;
  11115. } else if (this.isTooltipOnly && !isBound) {
  11116. this._bindLink(link, "");
  11117. isBound = true;
  11118. }
  11119. }
  11120. if (this.quadrilaterals) {
  11121. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  11122. const linkElement = index === 0 ? link : link.cloneNode();
  11123. quadrilateral.append(linkElement);
  11124. return quadrilateral;
  11125. });
  11126. }
  11127. this.container.className = "linkAnnotation";
  11128. if (isBound) {
  11129. this.container.append(link);
  11130. }
  11131. return this.container;
  11132. }
  11133. #setInternalLink() {
  11134. this.container.setAttribute("data-internal-link", "");
  11135. }
  11136. _bindLink(link, destination) {
  11137. link.href = this.linkService.getDestinationHash(destination);
  11138. link.onclick = () => {
  11139. if (destination) {
  11140. this.linkService.goToDestination(destination);
  11141. }
  11142. return false;
  11143. };
  11144. if (destination || destination === "") {
  11145. this.#setInternalLink();
  11146. }
  11147. }
  11148. _bindNamedAction(link, action) {
  11149. link.href = this.linkService.getAnchorUrl("");
  11150. link.onclick = () => {
  11151. this.linkService.executeNamedAction(action);
  11152. return false;
  11153. };
  11154. this.#setInternalLink();
  11155. }
  11156. _bindAttachment(link, attachment) {
  11157. link.href = this.linkService.getAnchorUrl("");
  11158. link.onclick = () => {
  11159. this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
  11160. return false;
  11161. };
  11162. this.#setInternalLink();
  11163. }
  11164. #bindSetOCGState(link, action) {
  11165. link.href = this.linkService.getAnchorUrl("");
  11166. link.onclick = () => {
  11167. this.linkService.executeSetOCGState(action);
  11168. return false;
  11169. };
  11170. this.#setInternalLink();
  11171. }
  11172. _bindJSAction(link, data) {
  11173. link.href = this.linkService.getAnchorUrl("");
  11174. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  11175. for (const name of Object.keys(data.actions)) {
  11176. const jsName = map.get(name);
  11177. if (!jsName) {
  11178. continue;
  11179. }
  11180. link[jsName] = () => {
  11181. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11182. source: this,
  11183. detail: {
  11184. id: data.id,
  11185. name
  11186. }
  11187. });
  11188. return false;
  11189. };
  11190. }
  11191. if (!link.onclick) {
  11192. link.onclick = () => false;
  11193. }
  11194. this.#setInternalLink();
  11195. }
  11196. _bindResetFormAction(link, resetForm) {
  11197. const otherClickAction = link.onclick;
  11198. if (!otherClickAction) {
  11199. link.href = this.linkService.getAnchorUrl("");
  11200. }
  11201. this.#setInternalLink();
  11202. if (!this._fieldObjects) {
  11203. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  11204. if (!otherClickAction) {
  11205. link.onclick = () => false;
  11206. }
  11207. return;
  11208. }
  11209. link.onclick = () => {
  11210. otherClickAction?.();
  11211. const {
  11212. fields: resetFormFields,
  11213. refs: resetFormRefs,
  11214. include
  11215. } = resetForm;
  11216. const allFields = [];
  11217. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  11218. const fieldIds = new Set(resetFormRefs);
  11219. for (const fieldName of resetFormFields) {
  11220. const fields = this._fieldObjects[fieldName] || [];
  11221. for (const {
  11222. id
  11223. } of fields) {
  11224. fieldIds.add(id);
  11225. }
  11226. }
  11227. for (const fields of Object.values(this._fieldObjects)) {
  11228. for (const field of fields) {
  11229. if (fieldIds.has(field.id) === include) {
  11230. allFields.push(field);
  11231. }
  11232. }
  11233. }
  11234. } else {
  11235. for (const fields of Object.values(this._fieldObjects)) {
  11236. allFields.push(...fields);
  11237. }
  11238. }
  11239. const storage = this.annotationStorage;
  11240. const allIds = [];
  11241. for (const field of allFields) {
  11242. const {
  11243. id
  11244. } = field;
  11245. allIds.push(id);
  11246. switch (field.type) {
  11247. case "text":
  11248. {
  11249. const value = field.defaultValue || "";
  11250. storage.setValue(id, {
  11251. value
  11252. });
  11253. break;
  11254. }
  11255. case "checkbox":
  11256. case "radiobutton":
  11257. {
  11258. const value = field.defaultValue === field.exportValues;
  11259. storage.setValue(id, {
  11260. value
  11261. });
  11262. break;
  11263. }
  11264. case "combobox":
  11265. case "listbox":
  11266. {
  11267. const value = field.defaultValue || "";
  11268. storage.setValue(id, {
  11269. value
  11270. });
  11271. break;
  11272. }
  11273. default:
  11274. continue;
  11275. }
  11276. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  11277. if (!domElement) {
  11278. continue;
  11279. } else if (!GetElementsByNameSet.has(domElement)) {
  11280. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  11281. continue;
  11282. }
  11283. domElement.dispatchEvent(new Event("resetform"));
  11284. }
  11285. if (this.enableScripting) {
  11286. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11287. source: this,
  11288. detail: {
  11289. id: "app",
  11290. ids: allIds,
  11291. name: "ResetForm"
  11292. }
  11293. });
  11294. }
  11295. return false;
  11296. };
  11297. }
  11298. }
  11299. class TextAnnotationElement extends AnnotationElement {
  11300. constructor(parameters) {
  11301. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  11302. super(parameters, {
  11303. isRenderable
  11304. });
  11305. }
  11306. render() {
  11307. this.container.className = "textAnnotation";
  11308. const image = document.createElement("img");
  11309. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  11310. image.alt = "[{{type}} Annotation]";
  11311. image.dataset.l10nId = "text_annotation_type";
  11312. image.dataset.l10nArgs = JSON.stringify({
  11313. type: this.data.name
  11314. });
  11315. if (!this.data.hasPopup) {
  11316. this._createPopup(image, this.data);
  11317. }
  11318. this.container.append(image);
  11319. return this.container;
  11320. }
  11321. }
  11322. class WidgetAnnotationElement extends AnnotationElement {
  11323. render() {
  11324. if (this.data.alternativeText) {
  11325. this.container.title = this.data.alternativeText;
  11326. }
  11327. return this.container;
  11328. }
  11329. _getKeyModifier(event) {
  11330. const {
  11331. isWin,
  11332. isMac
  11333. } = _util.FeatureTest.platform;
  11334. return isWin && event.ctrlKey || isMac && event.metaKey;
  11335. }
  11336. _setEventListener(element, baseName, eventName, valueGetter) {
  11337. if (baseName.includes("mouse")) {
  11338. element.addEventListener(baseName, event => {
  11339. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11340. source: this,
  11341. detail: {
  11342. id: this.data.id,
  11343. name: eventName,
  11344. value: valueGetter(event),
  11345. shift: event.shiftKey,
  11346. modifier: this._getKeyModifier(event)
  11347. }
  11348. });
  11349. });
  11350. } else {
  11351. element.addEventListener(baseName, event => {
  11352. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11353. source: this,
  11354. detail: {
  11355. id: this.data.id,
  11356. name: eventName,
  11357. value: valueGetter(event)
  11358. }
  11359. });
  11360. });
  11361. }
  11362. }
  11363. _setEventListeners(element, names, getter) {
  11364. for (const [baseName, eventName] of names) {
  11365. if (eventName === "Action" || this.data.actions?.[eventName]) {
  11366. this._setEventListener(element, baseName, eventName, getter);
  11367. }
  11368. }
  11369. }
  11370. _setBackgroundColor(element) {
  11371. const color = this.data.backgroundColor || null;
  11372. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  11373. }
  11374. _setTextStyle(element) {
  11375. const TEXT_ALIGNMENT = ["left", "center", "right"];
  11376. const {
  11377. fontColor
  11378. } = this.data.defaultAppearanceData;
  11379. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  11380. const style = element.style;
  11381. let computedFontSize;
  11382. const BORDER_SIZE = 2;
  11383. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  11384. if (this.data.multiLine) {
  11385. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  11386. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  11387. const lineHeight = height / numberOfLines;
  11388. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
  11389. } else {
  11390. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  11391. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
  11392. }
  11393. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  11394. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  11395. if (this.data.textAlignment !== null) {
  11396. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  11397. }
  11398. }
  11399. _setRequired(element, isRequired) {
  11400. if (isRequired) {
  11401. element.setAttribute("required", true);
  11402. } else {
  11403. element.removeAttribute("required");
  11404. }
  11405. element.setAttribute("aria-required", isRequired);
  11406. }
  11407. }
  11408. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  11409. constructor(parameters) {
  11410. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  11411. super(parameters, {
  11412. isRenderable
  11413. });
  11414. }
  11415. setPropertyOnSiblings(base, key, value, keyInStorage) {
  11416. const storage = this.annotationStorage;
  11417. for (const element of this._getElementsByName(base.name, base.id)) {
  11418. if (element.domElement) {
  11419. element.domElement[key] = value;
  11420. }
  11421. storage.setValue(element.id, {
  11422. [keyInStorage]: value
  11423. });
  11424. }
  11425. }
  11426. render() {
  11427. const storage = this.annotationStorage;
  11428. const id = this.data.id;
  11429. this.container.className = "textWidgetAnnotation";
  11430. let element = null;
  11431. if (this.renderForms) {
  11432. const storedData = storage.getValue(id, {
  11433. value: this.data.fieldValue
  11434. });
  11435. let textContent = storedData.formattedValue || storedData.value || "";
  11436. const maxLen = storage.getValue(id, {
  11437. charLimit: this.data.maxLen
  11438. }).charLimit;
  11439. if (maxLen && textContent.length > maxLen) {
  11440. textContent = textContent.slice(0, maxLen);
  11441. }
  11442. const elementData = {
  11443. userValue: textContent,
  11444. formattedValue: null,
  11445. lastCommittedValue: null,
  11446. commitKey: 1
  11447. };
  11448. if (this.data.multiLine) {
  11449. element = document.createElement("textarea");
  11450. element.textContent = textContent;
  11451. if (this.data.doNotScroll) {
  11452. element.style.overflowY = "hidden";
  11453. }
  11454. } else {
  11455. element = document.createElement("input");
  11456. element.type = "text";
  11457. element.setAttribute("value", textContent);
  11458. if (this.data.doNotScroll) {
  11459. element.style.overflowX = "hidden";
  11460. }
  11461. }
  11462. GetElementsByNameSet.add(element);
  11463. element.setAttribute("data-element-id", id);
  11464. element.disabled = this.data.readOnly;
  11465. element.name = this.data.fieldName;
  11466. element.tabIndex = DEFAULT_TAB_INDEX;
  11467. this._setRequired(element, this.data.required);
  11468. if (maxLen) {
  11469. element.maxLength = maxLen;
  11470. }
  11471. element.addEventListener("input", event => {
  11472. storage.setValue(id, {
  11473. value: event.target.value
  11474. });
  11475. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  11476. });
  11477. element.addEventListener("resetform", event => {
  11478. const defaultValue = this.data.defaultFieldValue ?? "";
  11479. element.value = elementData.userValue = defaultValue;
  11480. elementData.formattedValue = null;
  11481. });
  11482. let blurListener = event => {
  11483. const {
  11484. formattedValue
  11485. } = elementData;
  11486. if (formattedValue !== null && formattedValue !== undefined) {
  11487. event.target.value = formattedValue;
  11488. }
  11489. event.target.scrollLeft = 0;
  11490. };
  11491. if (this.enableScripting && this.hasJSActions) {
  11492. element.addEventListener("focus", event => {
  11493. const {
  11494. target
  11495. } = event;
  11496. if (elementData.userValue) {
  11497. target.value = elementData.userValue;
  11498. }
  11499. elementData.lastCommittedValue = target.value;
  11500. elementData.commitKey = 1;
  11501. });
  11502. element.addEventListener("updatefromsandbox", jsEvent => {
  11503. const actions = {
  11504. value(event) {
  11505. elementData.userValue = event.detail.value ?? "";
  11506. storage.setValue(id, {
  11507. value: elementData.userValue.toString()
  11508. });
  11509. event.target.value = elementData.userValue;
  11510. },
  11511. formattedValue(event) {
  11512. const {
  11513. formattedValue
  11514. } = event.detail;
  11515. elementData.formattedValue = formattedValue;
  11516. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  11517. event.target.value = formattedValue;
  11518. }
  11519. storage.setValue(id, {
  11520. formattedValue
  11521. });
  11522. },
  11523. selRange(event) {
  11524. event.target.setSelectionRange(...event.detail.selRange);
  11525. },
  11526. charLimit: event => {
  11527. const {
  11528. charLimit
  11529. } = event.detail;
  11530. const {
  11531. target
  11532. } = event;
  11533. if (charLimit === 0) {
  11534. target.removeAttribute("maxLength");
  11535. return;
  11536. }
  11537. target.setAttribute("maxLength", charLimit);
  11538. let value = elementData.userValue;
  11539. if (!value || value.length <= charLimit) {
  11540. return;
  11541. }
  11542. value = value.slice(0, charLimit);
  11543. target.value = elementData.userValue = value;
  11544. storage.setValue(id, {
  11545. value
  11546. });
  11547. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11548. source: this,
  11549. detail: {
  11550. id,
  11551. name: "Keystroke",
  11552. value,
  11553. willCommit: true,
  11554. commitKey: 1,
  11555. selStart: target.selectionStart,
  11556. selEnd: target.selectionEnd
  11557. }
  11558. });
  11559. }
  11560. };
  11561. this._dispatchEventFromSandbox(actions, jsEvent);
  11562. });
  11563. element.addEventListener("keydown", event => {
  11564. elementData.commitKey = 1;
  11565. let commitKey = -1;
  11566. if (event.key === "Escape") {
  11567. commitKey = 0;
  11568. } else if (event.key === "Enter" && !this.data.multiLine) {
  11569. commitKey = 2;
  11570. } else if (event.key === "Tab") {
  11571. elementData.commitKey = 3;
  11572. }
  11573. if (commitKey === -1) {
  11574. return;
  11575. }
  11576. const {
  11577. value
  11578. } = event.target;
  11579. if (elementData.lastCommittedValue === value) {
  11580. return;
  11581. }
  11582. elementData.lastCommittedValue = value;
  11583. elementData.userValue = value;
  11584. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11585. source: this,
  11586. detail: {
  11587. id,
  11588. name: "Keystroke",
  11589. value,
  11590. willCommit: true,
  11591. commitKey,
  11592. selStart: event.target.selectionStart,
  11593. selEnd: event.target.selectionEnd
  11594. }
  11595. });
  11596. });
  11597. const _blurListener = blurListener;
  11598. blurListener = null;
  11599. element.addEventListener("blur", event => {
  11600. if (!event.relatedTarget) {
  11601. return;
  11602. }
  11603. const {
  11604. value
  11605. } = event.target;
  11606. elementData.userValue = value;
  11607. if (elementData.lastCommittedValue !== value) {
  11608. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11609. source: this,
  11610. detail: {
  11611. id,
  11612. name: "Keystroke",
  11613. value,
  11614. willCommit: true,
  11615. commitKey: elementData.commitKey,
  11616. selStart: event.target.selectionStart,
  11617. selEnd: event.target.selectionEnd
  11618. }
  11619. });
  11620. }
  11621. _blurListener(event);
  11622. });
  11623. if (this.data.actions?.Keystroke) {
  11624. element.addEventListener("beforeinput", event => {
  11625. elementData.lastCommittedValue = null;
  11626. const {
  11627. data,
  11628. target
  11629. } = event;
  11630. const {
  11631. value,
  11632. selectionStart,
  11633. selectionEnd
  11634. } = target;
  11635. let selStart = selectionStart,
  11636. selEnd = selectionEnd;
  11637. switch (event.inputType) {
  11638. case "deleteWordBackward":
  11639. {
  11640. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  11641. if (match) {
  11642. selStart -= match[0].length;
  11643. }
  11644. break;
  11645. }
  11646. case "deleteWordForward":
  11647. {
  11648. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  11649. if (match) {
  11650. selEnd += match[0].length;
  11651. }
  11652. break;
  11653. }
  11654. case "deleteContentBackward":
  11655. if (selectionStart === selectionEnd) {
  11656. selStart -= 1;
  11657. }
  11658. break;
  11659. case "deleteContentForward":
  11660. if (selectionStart === selectionEnd) {
  11661. selEnd += 1;
  11662. }
  11663. break;
  11664. }
  11665. event.preventDefault();
  11666. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  11667. source: this,
  11668. detail: {
  11669. id,
  11670. name: "Keystroke",
  11671. value,
  11672. change: data || "",
  11673. willCommit: false,
  11674. selStart,
  11675. selEnd
  11676. }
  11677. });
  11678. });
  11679. }
  11680. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  11681. }
  11682. if (blurListener) {
  11683. element.addEventListener("blur", blurListener);
  11684. }
  11685. if (this.data.comb) {
  11686. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  11687. const combWidth = fieldWidth / maxLen;
  11688. element.classList.add("comb");
  11689. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  11690. }
  11691. } else {
  11692. element = document.createElement("div");
  11693. element.textContent = this.data.fieldValue;
  11694. element.style.verticalAlign = "middle";
  11695. element.style.display = "table-cell";
  11696. }
  11697. this._setTextStyle(element);
  11698. this._setBackgroundColor(element);
  11699. this._setDefaultPropertiesFromJS(element);
  11700. this.container.append(element);
  11701. return this.container;
  11702. }
  11703. }
  11704. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  11705. constructor(parameters) {
  11706. super(parameters, {
  11707. isRenderable: parameters.renderForms
  11708. });
  11709. }
  11710. render() {
  11711. const storage = this.annotationStorage;
  11712. const data = this.data;
  11713. const id = data.id;
  11714. let value = storage.getValue(id, {
  11715. value: data.exportValue === data.fieldValue
  11716. }).value;
  11717. if (typeof value === "string") {
  11718. value = value !== "Off";
  11719. storage.setValue(id, {
  11720. value
  11721. });
  11722. }
  11723. this.container.className = "buttonWidgetAnnotation checkBox";
  11724. const element = document.createElement("input");
  11725. GetElementsByNameSet.add(element);
  11726. element.setAttribute("data-element-id", id);
  11727. element.disabled = data.readOnly;
  11728. this._setRequired(element, this.data.required);
  11729. element.type = "checkbox";
  11730. element.name = data.fieldName;
  11731. if (value) {
  11732. element.setAttribute("checked", true);
  11733. }
  11734. element.setAttribute("exportValue", data.exportValue);
  11735. element.tabIndex = DEFAULT_TAB_INDEX;
  11736. element.addEventListener("change", event => {
  11737. const {
  11738. name,
  11739. checked
  11740. } = event.target;
  11741. for (const checkbox of this._getElementsByName(name, id)) {
  11742. const curChecked = checked && checkbox.exportValue === data.exportValue;
  11743. if (checkbox.domElement) {
  11744. checkbox.domElement.checked = curChecked;
  11745. }
  11746. storage.setValue(checkbox.id, {
  11747. value: curChecked
  11748. });
  11749. }
  11750. storage.setValue(id, {
  11751. value: checked
  11752. });
  11753. });
  11754. element.addEventListener("resetform", event => {
  11755. const defaultValue = data.defaultFieldValue || "Off";
  11756. event.target.checked = defaultValue === data.exportValue;
  11757. });
  11758. if (this.enableScripting && this.hasJSActions) {
  11759. element.addEventListener("updatefromsandbox", jsEvent => {
  11760. const actions = {
  11761. value(event) {
  11762. event.target.checked = event.detail.value !== "Off";
  11763. storage.setValue(id, {
  11764. value: event.target.checked
  11765. });
  11766. }
  11767. };
  11768. this._dispatchEventFromSandbox(actions, jsEvent);
  11769. });
  11770. 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);
  11771. }
  11772. this._setBackgroundColor(element);
  11773. this._setDefaultPropertiesFromJS(element);
  11774. this.container.append(element);
  11775. return this.container;
  11776. }
  11777. }
  11778. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  11779. constructor(parameters) {
  11780. super(parameters, {
  11781. isRenderable: parameters.renderForms
  11782. });
  11783. }
  11784. render() {
  11785. this.container.className = "buttonWidgetAnnotation radioButton";
  11786. const storage = this.annotationStorage;
  11787. const data = this.data;
  11788. const id = data.id;
  11789. let value = storage.getValue(id, {
  11790. value: data.fieldValue === data.buttonValue
  11791. }).value;
  11792. if (typeof value === "string") {
  11793. value = value !== data.buttonValue;
  11794. storage.setValue(id, {
  11795. value
  11796. });
  11797. }
  11798. const element = document.createElement("input");
  11799. GetElementsByNameSet.add(element);
  11800. element.setAttribute("data-element-id", id);
  11801. element.disabled = data.readOnly;
  11802. this._setRequired(element, this.data.required);
  11803. element.type = "radio";
  11804. element.name = data.fieldName;
  11805. if (value) {
  11806. element.setAttribute("checked", true);
  11807. }
  11808. element.tabIndex = DEFAULT_TAB_INDEX;
  11809. element.addEventListener("change", event => {
  11810. const {
  11811. name,
  11812. checked
  11813. } = event.target;
  11814. for (const radio of this._getElementsByName(name, id)) {
  11815. storage.setValue(radio.id, {
  11816. value: false
  11817. });
  11818. }
  11819. storage.setValue(id, {
  11820. value: checked
  11821. });
  11822. });
  11823. element.addEventListener("resetform", event => {
  11824. const defaultValue = data.defaultFieldValue;
  11825. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  11826. });
  11827. if (this.enableScripting && this.hasJSActions) {
  11828. const pdfButtonValue = data.buttonValue;
  11829. element.addEventListener("updatefromsandbox", jsEvent => {
  11830. const actions = {
  11831. value: event => {
  11832. const checked = pdfButtonValue === event.detail.value;
  11833. for (const radio of this._getElementsByName(event.target.name)) {
  11834. const curChecked = checked && radio.id === id;
  11835. if (radio.domElement) {
  11836. radio.domElement.checked = curChecked;
  11837. }
  11838. storage.setValue(radio.id, {
  11839. value: curChecked
  11840. });
  11841. }
  11842. }
  11843. };
  11844. this._dispatchEventFromSandbox(actions, jsEvent);
  11845. });
  11846. 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);
  11847. }
  11848. this._setBackgroundColor(element);
  11849. this._setDefaultPropertiesFromJS(element);
  11850. this.container.append(element);
  11851. return this.container;
  11852. }
  11853. }
  11854. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  11855. constructor(parameters) {
  11856. super(parameters, {
  11857. ignoreBorder: parameters.data.hasAppearance
  11858. });
  11859. }
  11860. render() {
  11861. const container = super.render();
  11862. container.className = "buttonWidgetAnnotation pushButton";
  11863. if (this.data.alternativeText) {
  11864. container.title = this.data.alternativeText;
  11865. }
  11866. const linkElement = container.lastChild;
  11867. if (this.enableScripting && this.hasJSActions && linkElement) {
  11868. this._setDefaultPropertiesFromJS(linkElement);
  11869. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  11870. this._dispatchEventFromSandbox({}, jsEvent);
  11871. });
  11872. }
  11873. return container;
  11874. }
  11875. }
  11876. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  11877. constructor(parameters) {
  11878. super(parameters, {
  11879. isRenderable: parameters.renderForms
  11880. });
  11881. }
  11882. render() {
  11883. this.container.className = "choiceWidgetAnnotation";
  11884. const storage = this.annotationStorage;
  11885. const id = this.data.id;
  11886. const storedData = storage.getValue(id, {
  11887. value: this.data.fieldValue
  11888. });
  11889. const selectElement = document.createElement("select");
  11890. GetElementsByNameSet.add(selectElement);
  11891. selectElement.setAttribute("data-element-id", id);
  11892. selectElement.disabled = this.data.readOnly;
  11893. this._setRequired(selectElement, this.data.required);
  11894. selectElement.name = this.data.fieldName;
  11895. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  11896. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  11897. if (!this.data.combo) {
  11898. selectElement.size = this.data.options.length;
  11899. if (this.data.multiSelect) {
  11900. selectElement.multiple = true;
  11901. }
  11902. }
  11903. selectElement.addEventListener("resetform", event => {
  11904. const defaultValue = this.data.defaultFieldValue;
  11905. for (const option of selectElement.options) {
  11906. option.selected = option.value === defaultValue;
  11907. }
  11908. });
  11909. for (const option of this.data.options) {
  11910. const optionElement = document.createElement("option");
  11911. optionElement.textContent = option.displayValue;
  11912. optionElement.value = option.exportValue;
  11913. if (storedData.value.includes(option.exportValue)) {
  11914. optionElement.setAttribute("selected", true);
  11915. addAnEmptyEntry = false;
  11916. }
  11917. selectElement.append(optionElement);
  11918. }
  11919. let removeEmptyEntry = null;
  11920. if (addAnEmptyEntry) {
  11921. const noneOptionElement = document.createElement("option");
  11922. noneOptionElement.value = " ";
  11923. noneOptionElement.setAttribute("hidden", true);
  11924. noneOptionElement.setAttribute("selected", true);
  11925. selectElement.prepend(noneOptionElement);
  11926. removeEmptyEntry = () => {
  11927. noneOptionElement.remove();
  11928. selectElement.removeEventListener("input", removeEmptyEntry);
  11929. removeEmptyEntry = null;
  11930. };
  11931. selectElement.addEventListener("input", removeEmptyEntry);
  11932. }
  11933. const getValue = isExport => {
  11934. const name = isExport ? "value" : "textContent";
  11935. const {
  11936. options,
  11937. multiple
  11938. } = selectElement;
  11939. if (!multiple) {
  11940. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  11941. }
  11942. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  11943. };
  11944. let selectedValues = getValue(false);
  11945. const getItems = event => {
  11946. const options = event.target.options;
  11947. return Array.prototype.map.call(options, option => {
  11948. return {
  11949. displayValue: option.textContent,
  11950. exportValue: option.value
  11951. };
  11952. });
  11953. };
  11954. if (this.enableScripting && this.hasJSActions) {
  11955. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  11956. const actions = {
  11957. value(event) {
  11958. removeEmptyEntry?.();
  11959. const value = event.detail.value;
  11960. const values = new Set(Array.isArray(value) ? value : [value]);
  11961. for (const option of selectElement.options) {
  11962. option.selected = values.has(option.value);
  11963. }
  11964. storage.setValue(id, {
  11965. value: getValue(true)
  11966. });
  11967. selectedValues = getValue(false);
  11968. },
  11969. multipleSelection(event) {
  11970. selectElement.multiple = true;
  11971. },
  11972. remove(event) {
  11973. const options = selectElement.options;
  11974. const index = event.detail.remove;
  11975. options[index].selected = false;
  11976. selectElement.remove(index);
  11977. if (options.length > 0) {
  11978. const i = Array.prototype.findIndex.call(options, option => option.selected);
  11979. if (i === -1) {
  11980. options[0].selected = true;
  11981. }
  11982. }
  11983. storage.setValue(id, {
  11984. value: getValue(true),
  11985. items: getItems(event)
  11986. });
  11987. selectedValues = getValue(false);
  11988. },
  11989. clear(event) {
  11990. while (selectElement.length !== 0) {
  11991. selectElement.remove(0);
  11992. }
  11993. storage.setValue(id, {
  11994. value: null,
  11995. items: []
  11996. });
  11997. selectedValues = getValue(false);
  11998. },
  11999. insert(event) {
  12000. const {
  12001. index,
  12002. displayValue,
  12003. exportValue
  12004. } = event.detail.insert;
  12005. const selectChild = selectElement.children[index];
  12006. const optionElement = document.createElement("option");
  12007. optionElement.textContent = displayValue;
  12008. optionElement.value = exportValue;
  12009. if (selectChild) {
  12010. selectChild.before(optionElement);
  12011. } else {
  12012. selectElement.append(optionElement);
  12013. }
  12014. storage.setValue(id, {
  12015. value: getValue(true),
  12016. items: getItems(event)
  12017. });
  12018. selectedValues = getValue(false);
  12019. },
  12020. items(event) {
  12021. const {
  12022. items
  12023. } = event.detail;
  12024. while (selectElement.length !== 0) {
  12025. selectElement.remove(0);
  12026. }
  12027. for (const item of items) {
  12028. const {
  12029. displayValue,
  12030. exportValue
  12031. } = item;
  12032. const optionElement = document.createElement("option");
  12033. optionElement.textContent = displayValue;
  12034. optionElement.value = exportValue;
  12035. selectElement.append(optionElement);
  12036. }
  12037. if (selectElement.options.length > 0) {
  12038. selectElement.options[0].selected = true;
  12039. }
  12040. storage.setValue(id, {
  12041. value: getValue(true),
  12042. items: getItems(event)
  12043. });
  12044. selectedValues = getValue(false);
  12045. },
  12046. indices(event) {
  12047. const indices = new Set(event.detail.indices);
  12048. for (const option of event.target.options) {
  12049. option.selected = indices.has(option.index);
  12050. }
  12051. storage.setValue(id, {
  12052. value: getValue(true)
  12053. });
  12054. selectedValues = getValue(false);
  12055. },
  12056. editable(event) {
  12057. event.target.disabled = !event.detail.editable;
  12058. }
  12059. };
  12060. this._dispatchEventFromSandbox(actions, jsEvent);
  12061. });
  12062. selectElement.addEventListener("input", event => {
  12063. const exportValue = getValue(true);
  12064. storage.setValue(id, {
  12065. value: exportValue
  12066. });
  12067. event.preventDefault();
  12068. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12069. source: this,
  12070. detail: {
  12071. id,
  12072. name: "Keystroke",
  12073. value: selectedValues,
  12074. changeEx: exportValue,
  12075. willCommit: false,
  12076. commitKey: 1,
  12077. keyDown: false
  12078. }
  12079. });
  12080. });
  12081. 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);
  12082. } else {
  12083. selectElement.addEventListener("input", function (event) {
  12084. storage.setValue(id, {
  12085. value: getValue(true)
  12086. });
  12087. });
  12088. }
  12089. if (this.data.combo) {
  12090. this._setTextStyle(selectElement);
  12091. } else {}
  12092. this._setBackgroundColor(selectElement);
  12093. this._setDefaultPropertiesFromJS(selectElement);
  12094. this.container.append(selectElement);
  12095. return this.container;
  12096. }
  12097. }
  12098. class PopupAnnotationElement extends AnnotationElement {
  12099. static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
  12100. constructor(parameters) {
  12101. const {
  12102. data
  12103. } = parameters;
  12104. const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  12105. super(parameters, {
  12106. isRenderable
  12107. });
  12108. }
  12109. render() {
  12110. this.container.className = "popupAnnotation";
  12111. const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
  12112. if (parentElements.length === 0) {
  12113. return this.container;
  12114. }
  12115. const popup = new PopupElement({
  12116. container: this.container,
  12117. trigger: Array.from(parentElements),
  12118. color: this.data.color,
  12119. titleObj: this.data.titleObj,
  12120. modificationDate: this.data.modificationDate,
  12121. contentsObj: this.data.contentsObj,
  12122. richText: this.data.richText
  12123. });
  12124. const page = this.page;
  12125. 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]]);
  12126. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  12127. const popupTop = rect[1];
  12128. const {
  12129. pageWidth,
  12130. pageHeight,
  12131. pageX,
  12132. pageY
  12133. } = this.viewport.rawDims;
  12134. this.container.style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
  12135. this.container.style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
  12136. this.container.append(popup.render());
  12137. return this.container;
  12138. }
  12139. }
  12140. class PopupElement {
  12141. constructor(parameters) {
  12142. this.container = parameters.container;
  12143. this.trigger = parameters.trigger;
  12144. this.color = parameters.color;
  12145. this.titleObj = parameters.titleObj;
  12146. this.modificationDate = parameters.modificationDate;
  12147. this.contentsObj = parameters.contentsObj;
  12148. this.richText = parameters.richText;
  12149. this.hideWrapper = parameters.hideWrapper || false;
  12150. this.pinned = false;
  12151. }
  12152. render() {
  12153. const BACKGROUND_ENLIGHT = 0.7;
  12154. const wrapper = document.createElement("div");
  12155. wrapper.className = "popupWrapper";
  12156. this.hideElement = this.hideWrapper ? wrapper : this.container;
  12157. this.hideElement.hidden = true;
  12158. const popup = document.createElement("div");
  12159. popup.className = "popup";
  12160. const color = this.color;
  12161. if (color) {
  12162. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  12163. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  12164. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  12165. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  12166. }
  12167. const title = document.createElement("h1");
  12168. title.dir = this.titleObj.dir;
  12169. title.textContent = this.titleObj.str;
  12170. popup.append(title);
  12171. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  12172. if (dateObject) {
  12173. const modificationDate = document.createElement("span");
  12174. modificationDate.className = "popupDate";
  12175. modificationDate.textContent = "{{date}}, {{time}}";
  12176. modificationDate.dataset.l10nId = "annotation_date_string";
  12177. modificationDate.dataset.l10nArgs = JSON.stringify({
  12178. date: dateObject.toLocaleDateString(),
  12179. time: dateObject.toLocaleTimeString()
  12180. });
  12181. popup.append(modificationDate);
  12182. }
  12183. if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
  12184. _xfa_layer.XfaLayer.render({
  12185. xfaHtml: this.richText.html,
  12186. intent: "richText",
  12187. div: popup
  12188. });
  12189. popup.lastChild.className = "richText popupContent";
  12190. } else {
  12191. const contents = this._formatContents(this.contentsObj);
  12192. popup.append(contents);
  12193. }
  12194. if (!Array.isArray(this.trigger)) {
  12195. this.trigger = [this.trigger];
  12196. }
  12197. for (const element of this.trigger) {
  12198. element.addEventListener("click", this._toggle.bind(this));
  12199. element.addEventListener("mouseover", this._show.bind(this, false));
  12200. element.addEventListener("mouseout", this._hide.bind(this, false));
  12201. }
  12202. popup.addEventListener("click", this._hide.bind(this, true));
  12203. wrapper.append(popup);
  12204. return wrapper;
  12205. }
  12206. _formatContents({
  12207. str,
  12208. dir
  12209. }) {
  12210. const p = document.createElement("p");
  12211. p.className = "popupContent";
  12212. p.dir = dir;
  12213. const lines = str.split(/(?:\r\n?|\n)/);
  12214. for (let i = 0, ii = lines.length; i < ii; ++i) {
  12215. const line = lines[i];
  12216. p.append(document.createTextNode(line));
  12217. if (i < ii - 1) {
  12218. p.append(document.createElement("br"));
  12219. }
  12220. }
  12221. return p;
  12222. }
  12223. _toggle() {
  12224. if (this.pinned) {
  12225. this._hide(true);
  12226. } else {
  12227. this._show(true);
  12228. }
  12229. }
  12230. _show(pin = false) {
  12231. if (pin) {
  12232. this.pinned = true;
  12233. }
  12234. if (this.hideElement.hidden) {
  12235. this.hideElement.hidden = false;
  12236. this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
  12237. }
  12238. }
  12239. _hide(unpin = true) {
  12240. if (unpin) {
  12241. this.pinned = false;
  12242. }
  12243. if (!this.hideElement.hidden && !this.pinned) {
  12244. this.hideElement.hidden = true;
  12245. this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
  12246. }
  12247. }
  12248. }
  12249. class FreeTextAnnotationElement extends AnnotationElement {
  12250. constructor(parameters) {
  12251. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12252. super(parameters, {
  12253. isRenderable,
  12254. ignoreBorder: true
  12255. });
  12256. this.textContent = parameters.data.textContent;
  12257. }
  12258. render() {
  12259. this.container.className = "freeTextAnnotation";
  12260. if (this.textContent) {
  12261. const content = document.createElement("div");
  12262. content.className = "annotationTextContent";
  12263. content.setAttribute("role", "comment");
  12264. for (const line of this.textContent) {
  12265. const lineSpan = document.createElement("span");
  12266. lineSpan.textContent = line;
  12267. content.append(lineSpan);
  12268. }
  12269. this.container.append(content);
  12270. }
  12271. if (!this.data.hasPopup) {
  12272. this._createPopup(null, this.data);
  12273. }
  12274. return this.container;
  12275. }
  12276. }
  12277. class LineAnnotationElement extends AnnotationElement {
  12278. constructor(parameters) {
  12279. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12280. super(parameters, {
  12281. isRenderable,
  12282. ignoreBorder: true
  12283. });
  12284. }
  12285. render() {
  12286. this.container.className = "lineAnnotation";
  12287. const data = this.data;
  12288. const {
  12289. width,
  12290. height
  12291. } = getRectDims(data.rect);
  12292. const svg = this.svgFactory.create(width, height, true);
  12293. const line = this.svgFactory.createElement("svg:line");
  12294. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  12295. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  12296. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  12297. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  12298. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  12299. line.setAttribute("stroke", "transparent");
  12300. line.setAttribute("fill", "transparent");
  12301. svg.append(line);
  12302. this.container.append(svg);
  12303. this._createPopup(line, data);
  12304. return this.container;
  12305. }
  12306. }
  12307. class SquareAnnotationElement extends AnnotationElement {
  12308. constructor(parameters) {
  12309. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12310. super(parameters, {
  12311. isRenderable,
  12312. ignoreBorder: true
  12313. });
  12314. }
  12315. render() {
  12316. this.container.className = "squareAnnotation";
  12317. const data = this.data;
  12318. const {
  12319. width,
  12320. height
  12321. } = getRectDims(data.rect);
  12322. const svg = this.svgFactory.create(width, height, true);
  12323. const borderWidth = data.borderStyle.width;
  12324. const square = this.svgFactory.createElement("svg:rect");
  12325. square.setAttribute("x", borderWidth / 2);
  12326. square.setAttribute("y", borderWidth / 2);
  12327. square.setAttribute("width", width - borderWidth);
  12328. square.setAttribute("height", height - borderWidth);
  12329. square.setAttribute("stroke-width", borderWidth || 1);
  12330. square.setAttribute("stroke", "transparent");
  12331. square.setAttribute("fill", "transparent");
  12332. svg.append(square);
  12333. this.container.append(svg);
  12334. this._createPopup(square, data);
  12335. return this.container;
  12336. }
  12337. }
  12338. class CircleAnnotationElement extends AnnotationElement {
  12339. constructor(parameters) {
  12340. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12341. super(parameters, {
  12342. isRenderable,
  12343. ignoreBorder: true
  12344. });
  12345. }
  12346. render() {
  12347. this.container.className = "circleAnnotation";
  12348. const data = this.data;
  12349. const {
  12350. width,
  12351. height
  12352. } = getRectDims(data.rect);
  12353. const svg = this.svgFactory.create(width, height, true);
  12354. const borderWidth = data.borderStyle.width;
  12355. const circle = this.svgFactory.createElement("svg:ellipse");
  12356. circle.setAttribute("cx", width / 2);
  12357. circle.setAttribute("cy", height / 2);
  12358. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  12359. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  12360. circle.setAttribute("stroke-width", borderWidth || 1);
  12361. circle.setAttribute("stroke", "transparent");
  12362. circle.setAttribute("fill", "transparent");
  12363. svg.append(circle);
  12364. this.container.append(svg);
  12365. this._createPopup(circle, data);
  12366. return this.container;
  12367. }
  12368. }
  12369. class PolylineAnnotationElement extends AnnotationElement {
  12370. constructor(parameters) {
  12371. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12372. super(parameters, {
  12373. isRenderable,
  12374. ignoreBorder: true
  12375. });
  12376. this.containerClassName = "polylineAnnotation";
  12377. this.svgElementName = "svg:polyline";
  12378. }
  12379. render() {
  12380. this.container.className = this.containerClassName;
  12381. const data = this.data;
  12382. const {
  12383. width,
  12384. height
  12385. } = getRectDims(data.rect);
  12386. const svg = this.svgFactory.create(width, height, true);
  12387. let points = [];
  12388. for (const coordinate of data.vertices) {
  12389. const x = coordinate.x - data.rect[0];
  12390. const y = data.rect[3] - coordinate.y;
  12391. points.push(x + "," + y);
  12392. }
  12393. points = points.join(" ");
  12394. const polyline = this.svgFactory.createElement(this.svgElementName);
  12395. polyline.setAttribute("points", points);
  12396. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  12397. polyline.setAttribute("stroke", "transparent");
  12398. polyline.setAttribute("fill", "transparent");
  12399. svg.append(polyline);
  12400. this.container.append(svg);
  12401. this._createPopup(polyline, data);
  12402. return this.container;
  12403. }
  12404. }
  12405. class PolygonAnnotationElement extends PolylineAnnotationElement {
  12406. constructor(parameters) {
  12407. super(parameters);
  12408. this.containerClassName = "polygonAnnotation";
  12409. this.svgElementName = "svg:polygon";
  12410. }
  12411. }
  12412. class CaretAnnotationElement extends AnnotationElement {
  12413. constructor(parameters) {
  12414. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12415. super(parameters, {
  12416. isRenderable,
  12417. ignoreBorder: true
  12418. });
  12419. }
  12420. render() {
  12421. this.container.className = "caretAnnotation";
  12422. if (!this.data.hasPopup) {
  12423. this._createPopup(null, this.data);
  12424. }
  12425. return this.container;
  12426. }
  12427. }
  12428. class InkAnnotationElement extends AnnotationElement {
  12429. constructor(parameters) {
  12430. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12431. super(parameters, {
  12432. isRenderable,
  12433. ignoreBorder: true
  12434. });
  12435. this.containerClassName = "inkAnnotation";
  12436. this.svgElementName = "svg:polyline";
  12437. }
  12438. render() {
  12439. this.container.className = this.containerClassName;
  12440. const data = this.data;
  12441. const {
  12442. width,
  12443. height
  12444. } = getRectDims(data.rect);
  12445. const svg = this.svgFactory.create(width, height, true);
  12446. for (const inkList of data.inkLists) {
  12447. let points = [];
  12448. for (const coordinate of inkList) {
  12449. const x = coordinate.x - data.rect[0];
  12450. const y = data.rect[3] - coordinate.y;
  12451. points.push(`${x},${y}`);
  12452. }
  12453. points = points.join(" ");
  12454. const polyline = this.svgFactory.createElement(this.svgElementName);
  12455. polyline.setAttribute("points", points);
  12456. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  12457. polyline.setAttribute("stroke", "transparent");
  12458. polyline.setAttribute("fill", "transparent");
  12459. this._createPopup(polyline, data);
  12460. svg.append(polyline);
  12461. }
  12462. this.container.append(svg);
  12463. return this.container;
  12464. }
  12465. }
  12466. class HighlightAnnotationElement extends AnnotationElement {
  12467. constructor(parameters) {
  12468. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12469. super(parameters, {
  12470. isRenderable,
  12471. ignoreBorder: true,
  12472. createQuadrilaterals: true
  12473. });
  12474. }
  12475. render() {
  12476. if (!this.data.hasPopup) {
  12477. this._createPopup(null, this.data);
  12478. }
  12479. if (this.quadrilaterals) {
  12480. return this._renderQuadrilaterals("highlightAnnotation");
  12481. }
  12482. this.container.className = "highlightAnnotation";
  12483. return this.container;
  12484. }
  12485. }
  12486. class UnderlineAnnotationElement extends AnnotationElement {
  12487. constructor(parameters) {
  12488. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12489. super(parameters, {
  12490. isRenderable,
  12491. ignoreBorder: true,
  12492. createQuadrilaterals: true
  12493. });
  12494. }
  12495. render() {
  12496. if (!this.data.hasPopup) {
  12497. this._createPopup(null, this.data);
  12498. }
  12499. if (this.quadrilaterals) {
  12500. return this._renderQuadrilaterals("underlineAnnotation");
  12501. }
  12502. this.container.className = "underlineAnnotation";
  12503. return this.container;
  12504. }
  12505. }
  12506. class SquigglyAnnotationElement extends AnnotationElement {
  12507. constructor(parameters) {
  12508. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12509. super(parameters, {
  12510. isRenderable,
  12511. ignoreBorder: true,
  12512. createQuadrilaterals: true
  12513. });
  12514. }
  12515. render() {
  12516. if (!this.data.hasPopup) {
  12517. this._createPopup(null, this.data);
  12518. }
  12519. if (this.quadrilaterals) {
  12520. return this._renderQuadrilaterals("squigglyAnnotation");
  12521. }
  12522. this.container.className = "squigglyAnnotation";
  12523. return this.container;
  12524. }
  12525. }
  12526. class StrikeOutAnnotationElement extends AnnotationElement {
  12527. constructor(parameters) {
  12528. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12529. super(parameters, {
  12530. isRenderable,
  12531. ignoreBorder: true,
  12532. createQuadrilaterals: true
  12533. });
  12534. }
  12535. render() {
  12536. if (!this.data.hasPopup) {
  12537. this._createPopup(null, this.data);
  12538. }
  12539. if (this.quadrilaterals) {
  12540. return this._renderQuadrilaterals("strikeoutAnnotation");
  12541. }
  12542. this.container.className = "strikeoutAnnotation";
  12543. return this.container;
  12544. }
  12545. }
  12546. class StampAnnotationElement extends AnnotationElement {
  12547. constructor(parameters) {
  12548. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12549. super(parameters, {
  12550. isRenderable,
  12551. ignoreBorder: true
  12552. });
  12553. }
  12554. render() {
  12555. this.container.className = "stampAnnotation";
  12556. if (!this.data.hasPopup) {
  12557. this._createPopup(null, this.data);
  12558. }
  12559. return this.container;
  12560. }
  12561. }
  12562. class FileAttachmentAnnotationElement extends AnnotationElement {
  12563. constructor(parameters) {
  12564. super(parameters, {
  12565. isRenderable: true
  12566. });
  12567. const {
  12568. filename,
  12569. content
  12570. } = this.data.file;
  12571. this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
  12572. this.content = content;
  12573. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  12574. source: this,
  12575. filename,
  12576. content
  12577. });
  12578. }
  12579. render() {
  12580. this.container.className = "fileAttachmentAnnotation";
  12581. let trigger;
  12582. if (this.data.hasAppearance) {
  12583. trigger = document.createElement("div");
  12584. } else {
  12585. trigger = document.createElement("img");
  12586. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"}.svg`;
  12587. }
  12588. trigger.className = "popupTriggerArea";
  12589. trigger.addEventListener("dblclick", this._download.bind(this));
  12590. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
  12591. this._createPopup(trigger, this.data);
  12592. }
  12593. this.container.append(trigger);
  12594. return this.container;
  12595. }
  12596. _download() {
  12597. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  12598. }
  12599. }
  12600. class AnnotationLayer {
  12601. static #appendElement(element, id, div, accessibilityManager) {
  12602. const contentElement = element.firstChild || element;
  12603. contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
  12604. div.append(element);
  12605. accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
  12606. }
  12607. static render(params) {
  12608. const {
  12609. annotations,
  12610. div,
  12611. viewport,
  12612. accessibilityManager
  12613. } = params;
  12614. (0, _display_utils.setLayerDimensions)(div, viewport);
  12615. const elementParams = {
  12616. data: null,
  12617. layer: div,
  12618. page: params.page,
  12619. viewport,
  12620. linkService: params.linkService,
  12621. downloadManager: params.downloadManager,
  12622. imageResourcesPath: params.imageResourcesPath || "",
  12623. renderForms: params.renderForms !== false,
  12624. svgFactory: new _display_utils.DOMSVGFactory(),
  12625. annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
  12626. enableScripting: params.enableScripting === true,
  12627. hasJSActions: params.hasJSActions,
  12628. fieldObjects: params.fieldObjects
  12629. };
  12630. let zIndex = 0;
  12631. for (const data of annotations) {
  12632. if (data.annotationType !== _util.AnnotationType.POPUP) {
  12633. const {
  12634. width,
  12635. height
  12636. } = getRectDims(data.rect);
  12637. if (width <= 0 || height <= 0) {
  12638. continue;
  12639. }
  12640. }
  12641. elementParams.data = data;
  12642. const element = AnnotationElementFactory.create(elementParams);
  12643. if (!element.isRenderable) {
  12644. continue;
  12645. }
  12646. const rendered = element.render();
  12647. if (data.hidden) {
  12648. rendered.style.visibility = "hidden";
  12649. }
  12650. if (Array.isArray(rendered)) {
  12651. for (const renderedElement of rendered) {
  12652. renderedElement.style.zIndex = zIndex++;
  12653. AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
  12654. }
  12655. } else {
  12656. rendered.style.zIndex = zIndex++;
  12657. if (element instanceof PopupAnnotationElement) {
  12658. div.prepend(rendered);
  12659. } else {
  12660. AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
  12661. }
  12662. }
  12663. }
  12664. this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
  12665. }
  12666. static update(params) {
  12667. const {
  12668. annotationCanvasMap,
  12669. div,
  12670. viewport
  12671. } = params;
  12672. (0, _display_utils.setLayerDimensions)(div, {
  12673. rotation: viewport.rotation
  12674. });
  12675. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  12676. div.hidden = false;
  12677. }
  12678. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  12679. if (!annotationCanvasMap) {
  12680. return;
  12681. }
  12682. for (const [id, canvas] of annotationCanvasMap) {
  12683. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  12684. if (!element) {
  12685. continue;
  12686. }
  12687. const {
  12688. firstChild
  12689. } = element;
  12690. if (!firstChild) {
  12691. element.append(canvas);
  12692. } else if (firstChild.nodeName === "CANVAS") {
  12693. firstChild.replaceWith(canvas);
  12694. } else {
  12695. firstChild.before(canvas);
  12696. }
  12697. }
  12698. annotationCanvasMap.clear();
  12699. }
  12700. }
  12701. exports.AnnotationLayer = AnnotationLayer;
  12702. /***/ }),
  12703. /* 28 */
  12704. /***/ ((__unused_webpack_module, exports) => {
  12705. Object.defineProperty(exports, "__esModule", ({
  12706. value: true
  12707. }));
  12708. exports.ColorConverters = void 0;
  12709. function makeColorComp(n) {
  12710. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  12711. }
  12712. class ColorConverters {
  12713. static CMYK_G([c, y, m, k]) {
  12714. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  12715. }
  12716. static G_CMYK([g]) {
  12717. return ["CMYK", 0, 0, 0, 1 - g];
  12718. }
  12719. static G_RGB([g]) {
  12720. return ["RGB", g, g, g];
  12721. }
  12722. static G_HTML([g]) {
  12723. const G = makeColorComp(g);
  12724. return `#${G}${G}${G}`;
  12725. }
  12726. static RGB_G([r, g, b]) {
  12727. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  12728. }
  12729. static RGB_HTML([r, g, b]) {
  12730. const R = makeColorComp(r);
  12731. const G = makeColorComp(g);
  12732. const B = makeColorComp(b);
  12733. return `#${R}${G}${B}`;
  12734. }
  12735. static T_HTML() {
  12736. return "#00000000";
  12737. }
  12738. static CMYK_RGB([c, y, m, k]) {
  12739. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  12740. }
  12741. static CMYK_HTML(components) {
  12742. const rgb = this.CMYK_RGB(components).slice(1);
  12743. return this.RGB_HTML(rgb);
  12744. }
  12745. static RGB_CMYK([r, g, b]) {
  12746. const c = 1 - r;
  12747. const m = 1 - g;
  12748. const y = 1 - b;
  12749. const k = Math.min(c, m, y);
  12750. return ["CMYK", c, m, y, k];
  12751. }
  12752. }
  12753. exports.ColorConverters = ColorConverters;
  12754. /***/ }),
  12755. /* 29 */
  12756. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12757. Object.defineProperty(exports, "__esModule", ({
  12758. value: true
  12759. }));
  12760. exports.XfaLayer = void 0;
  12761. var _xfa_text = __w_pdfjs_require__(19);
  12762. class XfaLayer {
  12763. static setupStorage(html, id, element, storage, intent) {
  12764. const storedData = storage.getValue(id, {
  12765. value: null
  12766. });
  12767. switch (element.name) {
  12768. case "textarea":
  12769. if (storedData.value !== null) {
  12770. html.textContent = storedData.value;
  12771. }
  12772. if (intent === "print") {
  12773. break;
  12774. }
  12775. html.addEventListener("input", event => {
  12776. storage.setValue(id, {
  12777. value: event.target.value
  12778. });
  12779. });
  12780. break;
  12781. case "input":
  12782. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  12783. if (storedData.value === element.attributes.xfaOn) {
  12784. html.setAttribute("checked", true);
  12785. } else if (storedData.value === element.attributes.xfaOff) {
  12786. html.removeAttribute("checked");
  12787. }
  12788. if (intent === "print") {
  12789. break;
  12790. }
  12791. html.addEventListener("change", event => {
  12792. storage.setValue(id, {
  12793. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  12794. });
  12795. });
  12796. } else {
  12797. if (storedData.value !== null) {
  12798. html.setAttribute("value", storedData.value);
  12799. }
  12800. if (intent === "print") {
  12801. break;
  12802. }
  12803. html.addEventListener("input", event => {
  12804. storage.setValue(id, {
  12805. value: event.target.value
  12806. });
  12807. });
  12808. }
  12809. break;
  12810. case "select":
  12811. if (storedData.value !== null) {
  12812. for (const option of element.children) {
  12813. if (option.attributes.value === storedData.value) {
  12814. option.attributes.selected = true;
  12815. }
  12816. }
  12817. }
  12818. html.addEventListener("input", event => {
  12819. const options = event.target.options;
  12820. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  12821. storage.setValue(id, {
  12822. value
  12823. });
  12824. });
  12825. break;
  12826. }
  12827. }
  12828. static setAttributes({
  12829. html,
  12830. element,
  12831. storage = null,
  12832. intent,
  12833. linkService
  12834. }) {
  12835. const {
  12836. attributes
  12837. } = element;
  12838. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  12839. if (attributes.type === "radio") {
  12840. attributes.name = `${attributes.name}-${intent}`;
  12841. }
  12842. for (const [key, value] of Object.entries(attributes)) {
  12843. if (value === null || value === undefined) {
  12844. continue;
  12845. }
  12846. switch (key) {
  12847. case "class":
  12848. if (value.length) {
  12849. html.setAttribute(key, value.join(" "));
  12850. }
  12851. break;
  12852. case "dataId":
  12853. break;
  12854. case "id":
  12855. html.setAttribute("data-element-id", value);
  12856. break;
  12857. case "style":
  12858. Object.assign(html.style, value);
  12859. break;
  12860. case "textContent":
  12861. html.textContent = value;
  12862. break;
  12863. default:
  12864. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  12865. html.setAttribute(key, value);
  12866. }
  12867. }
  12868. }
  12869. if (isHTMLAnchorElement) {
  12870. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  12871. }
  12872. if (storage && attributes.dataId) {
  12873. this.setupStorage(html, attributes.dataId, element, storage);
  12874. }
  12875. }
  12876. static render(parameters) {
  12877. const storage = parameters.annotationStorage;
  12878. const linkService = parameters.linkService;
  12879. const root = parameters.xfaHtml;
  12880. const intent = parameters.intent || "display";
  12881. const rootHtml = document.createElement(root.name);
  12882. if (root.attributes) {
  12883. this.setAttributes({
  12884. html: rootHtml,
  12885. element: root,
  12886. intent,
  12887. linkService
  12888. });
  12889. }
  12890. const stack = [[root, -1, rootHtml]];
  12891. const rootDiv = parameters.div;
  12892. rootDiv.append(rootHtml);
  12893. if (parameters.viewport) {
  12894. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12895. rootDiv.style.transform = transform;
  12896. }
  12897. if (intent !== "richText") {
  12898. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  12899. }
  12900. const textDivs = [];
  12901. while (stack.length > 0) {
  12902. const [parent, i, html] = stack.at(-1);
  12903. if (i + 1 === parent.children.length) {
  12904. stack.pop();
  12905. continue;
  12906. }
  12907. const child = parent.children[++stack.at(-1)[1]];
  12908. if (child === null) {
  12909. continue;
  12910. }
  12911. const {
  12912. name
  12913. } = child;
  12914. if (name === "#text") {
  12915. const node = document.createTextNode(child.value);
  12916. textDivs.push(node);
  12917. html.append(node);
  12918. continue;
  12919. }
  12920. let childHtml;
  12921. if (child?.attributes?.xmlns) {
  12922. childHtml = document.createElementNS(child.attributes.xmlns, name);
  12923. } else {
  12924. childHtml = document.createElement(name);
  12925. }
  12926. html.append(childHtml);
  12927. if (child.attributes) {
  12928. this.setAttributes({
  12929. html: childHtml,
  12930. element: child,
  12931. storage,
  12932. intent,
  12933. linkService
  12934. });
  12935. }
  12936. if (child.children && child.children.length > 0) {
  12937. stack.push([child, -1, childHtml]);
  12938. } else if (child.value) {
  12939. const node = document.createTextNode(child.value);
  12940. if (_xfa_text.XfaText.shouldBuildText(name)) {
  12941. textDivs.push(node);
  12942. }
  12943. childHtml.append(node);
  12944. }
  12945. }
  12946. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  12947. el.setAttribute("readOnly", true);
  12948. }
  12949. return {
  12950. textDivs
  12951. };
  12952. }
  12953. static update(parameters) {
  12954. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  12955. parameters.div.style.transform = transform;
  12956. parameters.div.hidden = false;
  12957. }
  12958. }
  12959. exports.XfaLayer = XfaLayer;
  12960. /***/ }),
  12961. /* 30 */
  12962. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12963. Object.defineProperty(exports, "__esModule", ({
  12964. value: true
  12965. }));
  12966. exports.SVGGraphics = void 0;
  12967. var _display_utils = __w_pdfjs_require__(6);
  12968. var _util = __w_pdfjs_require__(1);
  12969. var _is_node = __w_pdfjs_require__(10);
  12970. let SVGGraphics = class {
  12971. constructor() {
  12972. (0, _util.unreachable)("Not implemented: SVGGraphics");
  12973. }
  12974. };
  12975. exports.SVGGraphics = SVGGraphics;
  12976. {
  12977. const SVG_DEFAULTS = {
  12978. fontStyle: "normal",
  12979. fontWeight: "normal",
  12980. fillColor: "#000000"
  12981. };
  12982. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  12983. const XLINK_NS = "http://www.w3.org/1999/xlink";
  12984. const LINE_CAP_STYLES = ["butt", "round", "square"];
  12985. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  12986. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  12987. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  12988. return URL.createObjectURL(new Blob([data], {
  12989. type: contentType
  12990. }));
  12991. }
  12992. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  12993. let buffer = `data:${contentType};base64,`;
  12994. for (let i = 0, ii = data.length; i < ii; i += 3) {
  12995. const b1 = data[i] & 0xff;
  12996. const b2 = data[i + 1] & 0xff;
  12997. const b3 = data[i + 2] & 0xff;
  12998. const d1 = b1 >> 2,
  12999. d2 = (b1 & 3) << 4 | b2 >> 4;
  13000. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  13001. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  13002. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  13003. }
  13004. return buffer;
  13005. };
  13006. const convertImgDataToPng = function () {
  13007. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  13008. const CHUNK_WRAPPER_SIZE = 12;
  13009. const crcTable = new Int32Array(256);
  13010. for (let i = 0; i < 256; i++) {
  13011. let c = i;
  13012. for (let h = 0; h < 8; h++) {
  13013. if (c & 1) {
  13014. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  13015. } else {
  13016. c = c >> 1 & 0x7fffffff;
  13017. }
  13018. }
  13019. crcTable[i] = c;
  13020. }
  13021. function crc32(data, start, end) {
  13022. let crc = -1;
  13023. for (let i = start; i < end; i++) {
  13024. const a = (crc ^ data[i]) & 0xff;
  13025. const b = crcTable[a];
  13026. crc = crc >>> 8 ^ b;
  13027. }
  13028. return crc ^ -1;
  13029. }
  13030. function writePngChunk(type, body, data, offset) {
  13031. let p = offset;
  13032. const len = body.length;
  13033. data[p] = len >> 24 & 0xff;
  13034. data[p + 1] = len >> 16 & 0xff;
  13035. data[p + 2] = len >> 8 & 0xff;
  13036. data[p + 3] = len & 0xff;
  13037. p += 4;
  13038. data[p] = type.charCodeAt(0) & 0xff;
  13039. data[p + 1] = type.charCodeAt(1) & 0xff;
  13040. data[p + 2] = type.charCodeAt(2) & 0xff;
  13041. data[p + 3] = type.charCodeAt(3) & 0xff;
  13042. p += 4;
  13043. data.set(body, p);
  13044. p += body.length;
  13045. const crc = crc32(data, offset + 4, p);
  13046. data[p] = crc >> 24 & 0xff;
  13047. data[p + 1] = crc >> 16 & 0xff;
  13048. data[p + 2] = crc >> 8 & 0xff;
  13049. data[p + 3] = crc & 0xff;
  13050. }
  13051. function adler32(data, start, end) {
  13052. let a = 1;
  13053. let b = 0;
  13054. for (let i = start; i < end; ++i) {
  13055. a = (a + (data[i] & 0xff)) % 65521;
  13056. b = (b + a) % 65521;
  13057. }
  13058. return b << 16 | a;
  13059. }
  13060. function deflateSync(literals) {
  13061. if (!_is_node.isNodeJS) {
  13062. return deflateSyncUncompressed(literals);
  13063. }
  13064. try {
  13065. let input;
  13066. if (parseInt(process.versions.node) >= 8) {
  13067. input = literals;
  13068. } else {
  13069. input = Buffer.from(literals);
  13070. }
  13071. const output = require("zlib").deflateSync(input, {
  13072. level: 9
  13073. });
  13074. return output instanceof Uint8Array ? output : new Uint8Array(output);
  13075. } catch (e) {
  13076. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  13077. }
  13078. return deflateSyncUncompressed(literals);
  13079. }
  13080. function deflateSyncUncompressed(literals) {
  13081. let len = literals.length;
  13082. const maxBlockLength = 0xffff;
  13083. const deflateBlocks = Math.ceil(len / maxBlockLength);
  13084. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  13085. let pi = 0;
  13086. idat[pi++] = 0x78;
  13087. idat[pi++] = 0x9c;
  13088. let pos = 0;
  13089. while (len > maxBlockLength) {
  13090. idat[pi++] = 0x00;
  13091. idat[pi++] = 0xff;
  13092. idat[pi++] = 0xff;
  13093. idat[pi++] = 0x00;
  13094. idat[pi++] = 0x00;
  13095. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  13096. pi += maxBlockLength;
  13097. pos += maxBlockLength;
  13098. len -= maxBlockLength;
  13099. }
  13100. idat[pi++] = 0x01;
  13101. idat[pi++] = len & 0xff;
  13102. idat[pi++] = len >> 8 & 0xff;
  13103. idat[pi++] = ~len & 0xffff & 0xff;
  13104. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  13105. idat.set(literals.subarray(pos), pi);
  13106. pi += literals.length - pos;
  13107. const adler = adler32(literals, 0, literals.length);
  13108. idat[pi++] = adler >> 24 & 0xff;
  13109. idat[pi++] = adler >> 16 & 0xff;
  13110. idat[pi++] = adler >> 8 & 0xff;
  13111. idat[pi++] = adler & 0xff;
  13112. return idat;
  13113. }
  13114. function encode(imgData, kind, forceDataSchema, isMask) {
  13115. const width = imgData.width;
  13116. const height = imgData.height;
  13117. let bitDepth, colorType, lineSize;
  13118. const bytes = imgData.data;
  13119. switch (kind) {
  13120. case _util.ImageKind.GRAYSCALE_1BPP:
  13121. colorType = 0;
  13122. bitDepth = 1;
  13123. lineSize = width + 7 >> 3;
  13124. break;
  13125. case _util.ImageKind.RGB_24BPP:
  13126. colorType = 2;
  13127. bitDepth = 8;
  13128. lineSize = width * 3;
  13129. break;
  13130. case _util.ImageKind.RGBA_32BPP:
  13131. colorType = 6;
  13132. bitDepth = 8;
  13133. lineSize = width * 4;
  13134. break;
  13135. default:
  13136. throw new Error("invalid format");
  13137. }
  13138. const literals = new Uint8Array((1 + lineSize) * height);
  13139. let offsetLiterals = 0,
  13140. offsetBytes = 0;
  13141. for (let y = 0; y < height; ++y) {
  13142. literals[offsetLiterals++] = 0;
  13143. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  13144. offsetBytes += lineSize;
  13145. offsetLiterals += lineSize;
  13146. }
  13147. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  13148. offsetLiterals = 0;
  13149. for (let y = 0; y < height; y++) {
  13150. offsetLiterals++;
  13151. for (let i = 0; i < lineSize; i++) {
  13152. literals[offsetLiterals++] ^= 0xff;
  13153. }
  13154. }
  13155. }
  13156. 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]);
  13157. const idat = deflateSync(literals);
  13158. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  13159. const data = new Uint8Array(pngLength);
  13160. let offset = 0;
  13161. data.set(PNG_HEADER, offset);
  13162. offset += PNG_HEADER.length;
  13163. writePngChunk("IHDR", ihdr, data, offset);
  13164. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  13165. writePngChunk("IDATA", idat, data, offset);
  13166. offset += CHUNK_WRAPPER_SIZE + idat.length;
  13167. writePngChunk("IEND", new Uint8Array(0), data, offset);
  13168. return createObjectURL(data, "image/png", forceDataSchema);
  13169. }
  13170. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  13171. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  13172. return encode(imgData, kind, forceDataSchema, isMask);
  13173. };
  13174. }();
  13175. class SVGExtraState {
  13176. constructor() {
  13177. this.fontSizeScale = 1;
  13178. this.fontWeight = SVG_DEFAULTS.fontWeight;
  13179. this.fontSize = 0;
  13180. this.textMatrix = _util.IDENTITY_MATRIX;
  13181. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  13182. this.leading = 0;
  13183. this.textRenderingMode = _util.TextRenderingMode.FILL;
  13184. this.textMatrixScale = 1;
  13185. this.x = 0;
  13186. this.y = 0;
  13187. this.lineX = 0;
  13188. this.lineY = 0;
  13189. this.charSpacing = 0;
  13190. this.wordSpacing = 0;
  13191. this.textHScale = 1;
  13192. this.textRise = 0;
  13193. this.fillColor = SVG_DEFAULTS.fillColor;
  13194. this.strokeColor = "#000000";
  13195. this.fillAlpha = 1;
  13196. this.strokeAlpha = 1;
  13197. this.lineWidth = 1;
  13198. this.lineJoin = "";
  13199. this.lineCap = "";
  13200. this.miterLimit = 0;
  13201. this.dashArray = [];
  13202. this.dashPhase = 0;
  13203. this.dependencies = [];
  13204. this.activeClipUrl = null;
  13205. this.clipGroup = null;
  13206. this.maskId = "";
  13207. }
  13208. clone() {
  13209. return Object.create(this);
  13210. }
  13211. setCurrentPoint(x, y) {
  13212. this.x = x;
  13213. this.y = y;
  13214. }
  13215. }
  13216. function opListToTree(opList) {
  13217. let opTree = [];
  13218. const tmp = [];
  13219. for (const opListElement of opList) {
  13220. if (opListElement.fn === "save") {
  13221. opTree.push({
  13222. fnId: 92,
  13223. fn: "group",
  13224. items: []
  13225. });
  13226. tmp.push(opTree);
  13227. opTree = opTree.at(-1).items;
  13228. continue;
  13229. }
  13230. if (opListElement.fn === "restore") {
  13231. opTree = tmp.pop();
  13232. } else {
  13233. opTree.push(opListElement);
  13234. }
  13235. }
  13236. return opTree;
  13237. }
  13238. function pf(value) {
  13239. if (Number.isInteger(value)) {
  13240. return value.toString();
  13241. }
  13242. const s = value.toFixed(10);
  13243. let i = s.length - 1;
  13244. if (s[i] !== "0") {
  13245. return s;
  13246. }
  13247. do {
  13248. i--;
  13249. } while (s[i] === "0");
  13250. return s.substring(0, s[i] === "." ? i : i + 1);
  13251. }
  13252. function pm(m) {
  13253. if (m[4] === 0 && m[5] === 0) {
  13254. if (m[1] === 0 && m[2] === 0) {
  13255. if (m[0] === 1 && m[3] === 1) {
  13256. return "";
  13257. }
  13258. return `scale(${pf(m[0])} ${pf(m[3])})`;
  13259. }
  13260. if (m[0] === m[3] && m[1] === -m[2]) {
  13261. const a = Math.acos(m[0]) * 180 / Math.PI;
  13262. return `rotate(${pf(a)})`;
  13263. }
  13264. } else {
  13265. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  13266. return `translate(${pf(m[4])} ${pf(m[5])})`;
  13267. }
  13268. }
  13269. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  13270. }
  13271. let clipCount = 0;
  13272. let maskCount = 0;
  13273. let shadingCount = 0;
  13274. exports.SVGGraphics = SVGGraphics = class {
  13275. constructor(commonObjs, objs, forceDataSchema = false) {
  13276. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  13277. this.svgFactory = new _display_utils.DOMSVGFactory();
  13278. this.current = new SVGExtraState();
  13279. this.transformMatrix = _util.IDENTITY_MATRIX;
  13280. this.transformStack = [];
  13281. this.extraStack = [];
  13282. this.commonObjs = commonObjs;
  13283. this.objs = objs;
  13284. this.pendingClip = null;
  13285. this.pendingEOFill = false;
  13286. this.embedFonts = false;
  13287. this.embeddedFonts = Object.create(null);
  13288. this.cssStyle = null;
  13289. this.forceDataSchema = !!forceDataSchema;
  13290. this._operatorIdMapping = [];
  13291. for (const op in _util.OPS) {
  13292. this._operatorIdMapping[_util.OPS[op]] = op;
  13293. }
  13294. }
  13295. getObject(data, fallback = null) {
  13296. if (typeof data === "string") {
  13297. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  13298. }
  13299. return fallback;
  13300. }
  13301. save() {
  13302. this.transformStack.push(this.transformMatrix);
  13303. const old = this.current;
  13304. this.extraStack.push(old);
  13305. this.current = old.clone();
  13306. }
  13307. restore() {
  13308. this.transformMatrix = this.transformStack.pop();
  13309. this.current = this.extraStack.pop();
  13310. this.pendingClip = null;
  13311. this.tgrp = null;
  13312. }
  13313. group(items) {
  13314. this.save();
  13315. this.executeOpTree(items);
  13316. this.restore();
  13317. }
  13318. loadDependencies(operatorList) {
  13319. const fnArray = operatorList.fnArray;
  13320. const argsArray = operatorList.argsArray;
  13321. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13322. if (fnArray[i] !== _util.OPS.dependency) {
  13323. continue;
  13324. }
  13325. for (const obj of argsArray[i]) {
  13326. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  13327. const promise = new Promise(resolve => {
  13328. objsPool.get(obj, resolve);
  13329. });
  13330. this.current.dependencies.push(promise);
  13331. }
  13332. }
  13333. return Promise.all(this.current.dependencies);
  13334. }
  13335. transform(a, b, c, d, e, f) {
  13336. const transformMatrix = [a, b, c, d, e, f];
  13337. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  13338. this.tgrp = null;
  13339. }
  13340. getSVG(operatorList, viewport) {
  13341. this.viewport = viewport;
  13342. const svgElement = this._initialize(viewport);
  13343. return this.loadDependencies(operatorList).then(() => {
  13344. this.transformMatrix = _util.IDENTITY_MATRIX;
  13345. this.executeOpTree(this.convertOpList(operatorList));
  13346. return svgElement;
  13347. });
  13348. }
  13349. convertOpList(operatorList) {
  13350. const operatorIdMapping = this._operatorIdMapping;
  13351. const argsArray = operatorList.argsArray;
  13352. const fnArray = operatorList.fnArray;
  13353. const opList = [];
  13354. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  13355. const fnId = fnArray[i];
  13356. opList.push({
  13357. fnId,
  13358. fn: operatorIdMapping[fnId],
  13359. args: argsArray[i]
  13360. });
  13361. }
  13362. return opListToTree(opList);
  13363. }
  13364. executeOpTree(opTree) {
  13365. for (const opTreeElement of opTree) {
  13366. const fn = opTreeElement.fn;
  13367. const fnId = opTreeElement.fnId;
  13368. const args = opTreeElement.args;
  13369. switch (fnId | 0) {
  13370. case _util.OPS.beginText:
  13371. this.beginText();
  13372. break;
  13373. case _util.OPS.dependency:
  13374. break;
  13375. case _util.OPS.setLeading:
  13376. this.setLeading(args);
  13377. break;
  13378. case _util.OPS.setLeadingMoveText:
  13379. this.setLeadingMoveText(args[0], args[1]);
  13380. break;
  13381. case _util.OPS.setFont:
  13382. this.setFont(args);
  13383. break;
  13384. case _util.OPS.showText:
  13385. this.showText(args[0]);
  13386. break;
  13387. case _util.OPS.showSpacedText:
  13388. this.showText(args[0]);
  13389. break;
  13390. case _util.OPS.endText:
  13391. this.endText();
  13392. break;
  13393. case _util.OPS.moveText:
  13394. this.moveText(args[0], args[1]);
  13395. break;
  13396. case _util.OPS.setCharSpacing:
  13397. this.setCharSpacing(args[0]);
  13398. break;
  13399. case _util.OPS.setWordSpacing:
  13400. this.setWordSpacing(args[0]);
  13401. break;
  13402. case _util.OPS.setHScale:
  13403. this.setHScale(args[0]);
  13404. break;
  13405. case _util.OPS.setTextMatrix:
  13406. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  13407. break;
  13408. case _util.OPS.setTextRise:
  13409. this.setTextRise(args[0]);
  13410. break;
  13411. case _util.OPS.setTextRenderingMode:
  13412. this.setTextRenderingMode(args[0]);
  13413. break;
  13414. case _util.OPS.setLineWidth:
  13415. this.setLineWidth(args[0]);
  13416. break;
  13417. case _util.OPS.setLineJoin:
  13418. this.setLineJoin(args[0]);
  13419. break;
  13420. case _util.OPS.setLineCap:
  13421. this.setLineCap(args[0]);
  13422. break;
  13423. case _util.OPS.setMiterLimit:
  13424. this.setMiterLimit(args[0]);
  13425. break;
  13426. case _util.OPS.setFillRGBColor:
  13427. this.setFillRGBColor(args[0], args[1], args[2]);
  13428. break;
  13429. case _util.OPS.setStrokeRGBColor:
  13430. this.setStrokeRGBColor(args[0], args[1], args[2]);
  13431. break;
  13432. case _util.OPS.setStrokeColorN:
  13433. this.setStrokeColorN(args);
  13434. break;
  13435. case _util.OPS.setFillColorN:
  13436. this.setFillColorN(args);
  13437. break;
  13438. case _util.OPS.shadingFill:
  13439. this.shadingFill(args[0]);
  13440. break;
  13441. case _util.OPS.setDash:
  13442. this.setDash(args[0], args[1]);
  13443. break;
  13444. case _util.OPS.setRenderingIntent:
  13445. this.setRenderingIntent(args[0]);
  13446. break;
  13447. case _util.OPS.setFlatness:
  13448. this.setFlatness(args[0]);
  13449. break;
  13450. case _util.OPS.setGState:
  13451. this.setGState(args[0]);
  13452. break;
  13453. case _util.OPS.fill:
  13454. this.fill();
  13455. break;
  13456. case _util.OPS.eoFill:
  13457. this.eoFill();
  13458. break;
  13459. case _util.OPS.stroke:
  13460. this.stroke();
  13461. break;
  13462. case _util.OPS.fillStroke:
  13463. this.fillStroke();
  13464. break;
  13465. case _util.OPS.eoFillStroke:
  13466. this.eoFillStroke();
  13467. break;
  13468. case _util.OPS.clip:
  13469. this.clip("nonzero");
  13470. break;
  13471. case _util.OPS.eoClip:
  13472. this.clip("evenodd");
  13473. break;
  13474. case _util.OPS.paintSolidColorImageMask:
  13475. this.paintSolidColorImageMask();
  13476. break;
  13477. case _util.OPS.paintImageXObject:
  13478. this.paintImageXObject(args[0]);
  13479. break;
  13480. case _util.OPS.paintInlineImageXObject:
  13481. this.paintInlineImageXObject(args[0]);
  13482. break;
  13483. case _util.OPS.paintImageMaskXObject:
  13484. this.paintImageMaskXObject(args[0]);
  13485. break;
  13486. case _util.OPS.paintFormXObjectBegin:
  13487. this.paintFormXObjectBegin(args[0], args[1]);
  13488. break;
  13489. case _util.OPS.paintFormXObjectEnd:
  13490. this.paintFormXObjectEnd();
  13491. break;
  13492. case _util.OPS.closePath:
  13493. this.closePath();
  13494. break;
  13495. case _util.OPS.closeStroke:
  13496. this.closeStroke();
  13497. break;
  13498. case _util.OPS.closeFillStroke:
  13499. this.closeFillStroke();
  13500. break;
  13501. case _util.OPS.closeEOFillStroke:
  13502. this.closeEOFillStroke();
  13503. break;
  13504. case _util.OPS.nextLine:
  13505. this.nextLine();
  13506. break;
  13507. case _util.OPS.transform:
  13508. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  13509. break;
  13510. case _util.OPS.constructPath:
  13511. this.constructPath(args[0], args[1]);
  13512. break;
  13513. case _util.OPS.endPath:
  13514. this.endPath();
  13515. break;
  13516. case 92:
  13517. this.group(opTreeElement.items);
  13518. break;
  13519. default:
  13520. (0, _util.warn)(`Unimplemented operator ${fn}`);
  13521. break;
  13522. }
  13523. }
  13524. }
  13525. setWordSpacing(wordSpacing) {
  13526. this.current.wordSpacing = wordSpacing;
  13527. }
  13528. setCharSpacing(charSpacing) {
  13529. this.current.charSpacing = charSpacing;
  13530. }
  13531. nextLine() {
  13532. this.moveText(0, this.current.leading);
  13533. }
  13534. setTextMatrix(a, b, c, d, e, f) {
  13535. const current = this.current;
  13536. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  13537. current.textMatrixScale = Math.hypot(a, b);
  13538. current.x = current.lineX = 0;
  13539. current.y = current.lineY = 0;
  13540. current.xcoords = [];
  13541. current.ycoords = [];
  13542. current.tspan = this.svgFactory.createElement("svg:tspan");
  13543. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13544. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13545. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13546. current.txtElement = this.svgFactory.createElement("svg:text");
  13547. current.txtElement.append(current.tspan);
  13548. }
  13549. beginText() {
  13550. const current = this.current;
  13551. current.x = current.lineX = 0;
  13552. current.y = current.lineY = 0;
  13553. current.textMatrix = _util.IDENTITY_MATRIX;
  13554. current.lineMatrix = _util.IDENTITY_MATRIX;
  13555. current.textMatrixScale = 1;
  13556. current.tspan = this.svgFactory.createElement("svg:tspan");
  13557. current.txtElement = this.svgFactory.createElement("svg:text");
  13558. current.txtgrp = this.svgFactory.createElement("svg:g");
  13559. current.xcoords = [];
  13560. current.ycoords = [];
  13561. }
  13562. moveText(x, y) {
  13563. const current = this.current;
  13564. current.x = current.lineX += x;
  13565. current.y = current.lineY += y;
  13566. current.xcoords = [];
  13567. current.ycoords = [];
  13568. current.tspan = this.svgFactory.createElement("svg:tspan");
  13569. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13570. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13571. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13572. }
  13573. showText(glyphs) {
  13574. const current = this.current;
  13575. const font = current.font;
  13576. const fontSize = current.fontSize;
  13577. if (fontSize === 0) {
  13578. return;
  13579. }
  13580. const fontSizeScale = current.fontSizeScale;
  13581. const charSpacing = current.charSpacing;
  13582. const wordSpacing = current.wordSpacing;
  13583. const fontDirection = current.fontDirection;
  13584. const textHScale = current.textHScale * fontDirection;
  13585. const vertical = font.vertical;
  13586. const spacingDir = vertical ? 1 : -1;
  13587. const defaultVMetrics = font.defaultVMetrics;
  13588. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  13589. let x = 0;
  13590. for (const glyph of glyphs) {
  13591. if (glyph === null) {
  13592. x += fontDirection * wordSpacing;
  13593. continue;
  13594. } else if (typeof glyph === "number") {
  13595. x += spacingDir * glyph * fontSize / 1000;
  13596. continue;
  13597. }
  13598. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  13599. const character = glyph.fontChar;
  13600. let scaledX, scaledY;
  13601. let width = glyph.width;
  13602. if (vertical) {
  13603. let vx;
  13604. const vmetric = glyph.vmetric || defaultVMetrics;
  13605. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  13606. vx = -vx * widthAdvanceScale;
  13607. const vy = vmetric[2] * widthAdvanceScale;
  13608. width = vmetric ? -vmetric[0] : width;
  13609. scaledX = vx / fontSizeScale;
  13610. scaledY = (x + vy) / fontSizeScale;
  13611. } else {
  13612. scaledX = x / fontSizeScale;
  13613. scaledY = 0;
  13614. }
  13615. if (glyph.isInFont || font.missingFile) {
  13616. current.xcoords.push(current.x + scaledX);
  13617. if (vertical) {
  13618. current.ycoords.push(-current.y + scaledY);
  13619. }
  13620. current.tspan.textContent += character;
  13621. } else {}
  13622. let charWidth;
  13623. if (vertical) {
  13624. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  13625. } else {
  13626. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  13627. }
  13628. x += charWidth;
  13629. }
  13630. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  13631. if (vertical) {
  13632. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  13633. } else {
  13634. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13635. }
  13636. if (vertical) {
  13637. current.y -= x;
  13638. } else {
  13639. current.x += x * textHScale;
  13640. }
  13641. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  13642. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  13643. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  13644. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  13645. }
  13646. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  13647. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  13648. }
  13649. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  13650. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13651. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  13652. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  13653. }
  13654. if (current.fillAlpha < 1) {
  13655. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  13656. }
  13657. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  13658. current.tspan.setAttributeNS(null, "fill", "transparent");
  13659. } else {
  13660. current.tspan.setAttributeNS(null, "fill", "none");
  13661. }
  13662. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  13663. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  13664. this._setStrokeAttributes(current.tspan, lineWidthScale);
  13665. }
  13666. let textMatrix = current.textMatrix;
  13667. if (current.textRise !== 0) {
  13668. textMatrix = textMatrix.slice();
  13669. textMatrix[5] += current.textRise;
  13670. }
  13671. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  13672. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  13673. current.txtElement.append(current.tspan);
  13674. current.txtgrp.append(current.txtElement);
  13675. this._ensureTransformGroup().append(current.txtElement);
  13676. }
  13677. setLeadingMoveText(x, y) {
  13678. this.setLeading(-y);
  13679. this.moveText(x, y);
  13680. }
  13681. addFontStyle(fontObj) {
  13682. if (!fontObj.data) {
  13683. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  13684. }
  13685. if (!this.cssStyle) {
  13686. this.cssStyle = this.svgFactory.createElement("svg:style");
  13687. this.cssStyle.setAttributeNS(null, "type", "text/css");
  13688. this.defs.append(this.cssStyle);
  13689. }
  13690. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  13691. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  13692. }
  13693. setFont(details) {
  13694. const current = this.current;
  13695. const fontObj = this.commonObjs.get(details[0]);
  13696. let size = details[1];
  13697. current.font = fontObj;
  13698. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  13699. this.addFontStyle(fontObj);
  13700. this.embeddedFonts[fontObj.loadedName] = fontObj;
  13701. }
  13702. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  13703. let bold = "normal";
  13704. if (fontObj.black) {
  13705. bold = "900";
  13706. } else if (fontObj.bold) {
  13707. bold = "bold";
  13708. }
  13709. const italic = fontObj.italic ? "italic" : "normal";
  13710. if (size < 0) {
  13711. size = -size;
  13712. current.fontDirection = -1;
  13713. } else {
  13714. current.fontDirection = 1;
  13715. }
  13716. current.fontSize = size;
  13717. current.fontFamily = fontObj.loadedName;
  13718. current.fontWeight = bold;
  13719. current.fontStyle = italic;
  13720. current.tspan = this.svgFactory.createElement("svg:tspan");
  13721. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  13722. current.xcoords = [];
  13723. current.ycoords = [];
  13724. }
  13725. endText() {
  13726. const current = this.current;
  13727. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  13728. current.element = current.txtElement;
  13729. this.clip("nonzero");
  13730. this.endPath();
  13731. }
  13732. }
  13733. setLineWidth(width) {
  13734. if (width > 0) {
  13735. this.current.lineWidth = width;
  13736. }
  13737. }
  13738. setLineCap(style) {
  13739. this.current.lineCap = LINE_CAP_STYLES[style];
  13740. }
  13741. setLineJoin(style) {
  13742. this.current.lineJoin = LINE_JOIN_STYLES[style];
  13743. }
  13744. setMiterLimit(limit) {
  13745. this.current.miterLimit = limit;
  13746. }
  13747. setStrokeAlpha(strokeAlpha) {
  13748. this.current.strokeAlpha = strokeAlpha;
  13749. }
  13750. setStrokeRGBColor(r, g, b) {
  13751. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  13752. }
  13753. setFillAlpha(fillAlpha) {
  13754. this.current.fillAlpha = fillAlpha;
  13755. }
  13756. setFillRGBColor(r, g, b) {
  13757. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  13758. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  13759. this.current.xcoords = [];
  13760. this.current.ycoords = [];
  13761. }
  13762. setStrokeColorN(args) {
  13763. this.current.strokeColor = this._makeColorN_Pattern(args);
  13764. }
  13765. setFillColorN(args) {
  13766. this.current.fillColor = this._makeColorN_Pattern(args);
  13767. }
  13768. shadingFill(args) {
  13769. const width = this.viewport.width;
  13770. const height = this.viewport.height;
  13771. const inv = _util.Util.inverseTransform(this.transformMatrix);
  13772. const bl = _util.Util.applyTransform([0, 0], inv);
  13773. const br = _util.Util.applyTransform([0, height], inv);
  13774. const ul = _util.Util.applyTransform([width, 0], inv);
  13775. const ur = _util.Util.applyTransform([width, height], inv);
  13776. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  13777. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  13778. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  13779. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  13780. const rect = this.svgFactory.createElement("svg:rect");
  13781. rect.setAttributeNS(null, "x", x0);
  13782. rect.setAttributeNS(null, "y", y0);
  13783. rect.setAttributeNS(null, "width", x1 - x0);
  13784. rect.setAttributeNS(null, "height", y1 - y0);
  13785. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  13786. if (this.current.fillAlpha < 1) {
  13787. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  13788. }
  13789. this._ensureTransformGroup().append(rect);
  13790. }
  13791. _makeColorN_Pattern(args) {
  13792. if (args[0] === "TilingPattern") {
  13793. return this._makeTilingPattern(args);
  13794. }
  13795. return this._makeShadingPattern(args);
  13796. }
  13797. _makeTilingPattern(args) {
  13798. const color = args[1];
  13799. const operatorList = args[2];
  13800. const matrix = args[3] || _util.IDENTITY_MATRIX;
  13801. const [x0, y0, x1, y1] = args[4];
  13802. const xstep = args[5];
  13803. const ystep = args[6];
  13804. const paintType = args[7];
  13805. const tilingId = `shading${shadingCount++}`;
  13806. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  13807. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  13808. const txstep = xstep * xscale;
  13809. const tystep = ystep * yscale;
  13810. const tiling = this.svgFactory.createElement("svg:pattern");
  13811. tiling.setAttributeNS(null, "id", tilingId);
  13812. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  13813. tiling.setAttributeNS(null, "width", txstep);
  13814. tiling.setAttributeNS(null, "height", tystep);
  13815. tiling.setAttributeNS(null, "x", `${tx0}`);
  13816. tiling.setAttributeNS(null, "y", `${ty0}`);
  13817. const svg = this.svg;
  13818. const transformMatrix = this.transformMatrix;
  13819. const fillColor = this.current.fillColor;
  13820. const strokeColor = this.current.strokeColor;
  13821. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  13822. this.svg = bbox;
  13823. this.transformMatrix = matrix;
  13824. if (paintType === 2) {
  13825. const cssColor = _util.Util.makeHexColor(...color);
  13826. this.current.fillColor = cssColor;
  13827. this.current.strokeColor = cssColor;
  13828. }
  13829. this.executeOpTree(this.convertOpList(operatorList));
  13830. this.svg = svg;
  13831. this.transformMatrix = transformMatrix;
  13832. this.current.fillColor = fillColor;
  13833. this.current.strokeColor = strokeColor;
  13834. tiling.append(bbox.childNodes[0]);
  13835. this.defs.append(tiling);
  13836. return `url(#${tilingId})`;
  13837. }
  13838. _makeShadingPattern(args) {
  13839. if (typeof args === "string") {
  13840. args = this.objs.get(args);
  13841. }
  13842. switch (args[0]) {
  13843. case "RadialAxial":
  13844. const shadingId = `shading${shadingCount++}`;
  13845. const colorStops = args[3];
  13846. let gradient;
  13847. switch (args[1]) {
  13848. case "axial":
  13849. const point0 = args[4];
  13850. const point1 = args[5];
  13851. gradient = this.svgFactory.createElement("svg:linearGradient");
  13852. gradient.setAttributeNS(null, "id", shadingId);
  13853. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13854. gradient.setAttributeNS(null, "x1", point0[0]);
  13855. gradient.setAttributeNS(null, "y1", point0[1]);
  13856. gradient.setAttributeNS(null, "x2", point1[0]);
  13857. gradient.setAttributeNS(null, "y2", point1[1]);
  13858. break;
  13859. case "radial":
  13860. const focalPoint = args[4];
  13861. const circlePoint = args[5];
  13862. const focalRadius = args[6];
  13863. const circleRadius = args[7];
  13864. gradient = this.svgFactory.createElement("svg:radialGradient");
  13865. gradient.setAttributeNS(null, "id", shadingId);
  13866. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  13867. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  13868. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  13869. gradient.setAttributeNS(null, "r", circleRadius);
  13870. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  13871. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  13872. gradient.setAttributeNS(null, "fr", focalRadius);
  13873. break;
  13874. default:
  13875. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  13876. }
  13877. for (const colorStop of colorStops) {
  13878. const stop = this.svgFactory.createElement("svg:stop");
  13879. stop.setAttributeNS(null, "offset", colorStop[0]);
  13880. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  13881. gradient.append(stop);
  13882. }
  13883. this.defs.append(gradient);
  13884. return `url(#${shadingId})`;
  13885. case "Mesh":
  13886. (0, _util.warn)("Unimplemented pattern Mesh");
  13887. return null;
  13888. case "Dummy":
  13889. return "hotpink";
  13890. default:
  13891. throw new Error(`Unknown IR type: ${args[0]}`);
  13892. }
  13893. }
  13894. setDash(dashArray, dashPhase) {
  13895. this.current.dashArray = dashArray;
  13896. this.current.dashPhase = dashPhase;
  13897. }
  13898. constructPath(ops, args) {
  13899. const current = this.current;
  13900. let x = current.x,
  13901. y = current.y;
  13902. let d = [];
  13903. let j = 0;
  13904. for (const op of ops) {
  13905. switch (op | 0) {
  13906. case _util.OPS.rectangle:
  13907. x = args[j++];
  13908. y = args[j++];
  13909. const width = args[j++];
  13910. const height = args[j++];
  13911. const xw = x + width;
  13912. const yh = y + height;
  13913. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  13914. break;
  13915. case _util.OPS.moveTo:
  13916. x = args[j++];
  13917. y = args[j++];
  13918. d.push("M", pf(x), pf(y));
  13919. break;
  13920. case _util.OPS.lineTo:
  13921. x = args[j++];
  13922. y = args[j++];
  13923. d.push("L", pf(x), pf(y));
  13924. break;
  13925. case _util.OPS.curveTo:
  13926. x = args[j + 4];
  13927. y = args[j + 5];
  13928. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  13929. j += 6;
  13930. break;
  13931. case _util.OPS.curveTo2:
  13932. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  13933. x = args[j + 2];
  13934. y = args[j + 3];
  13935. j += 4;
  13936. break;
  13937. case _util.OPS.curveTo3:
  13938. x = args[j + 2];
  13939. y = args[j + 3];
  13940. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  13941. j += 4;
  13942. break;
  13943. case _util.OPS.closePath:
  13944. d.push("Z");
  13945. break;
  13946. }
  13947. }
  13948. d = d.join(" ");
  13949. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  13950. d = current.path.getAttributeNS(null, "d") + d;
  13951. } else {
  13952. current.path = this.svgFactory.createElement("svg:path");
  13953. this._ensureTransformGroup().append(current.path);
  13954. }
  13955. current.path.setAttributeNS(null, "d", d);
  13956. current.path.setAttributeNS(null, "fill", "none");
  13957. current.element = current.path;
  13958. current.setCurrentPoint(x, y);
  13959. }
  13960. endPath() {
  13961. const current = this.current;
  13962. current.path = null;
  13963. if (!this.pendingClip) {
  13964. return;
  13965. }
  13966. if (!current.element) {
  13967. this.pendingClip = null;
  13968. return;
  13969. }
  13970. const clipId = `clippath${clipCount++}`;
  13971. const clipPath = this.svgFactory.createElement("svg:clipPath");
  13972. clipPath.setAttributeNS(null, "id", clipId);
  13973. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  13974. const clipElement = current.element.cloneNode(true);
  13975. if (this.pendingClip === "evenodd") {
  13976. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  13977. } else {
  13978. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  13979. }
  13980. this.pendingClip = null;
  13981. clipPath.append(clipElement);
  13982. this.defs.append(clipPath);
  13983. if (current.activeClipUrl) {
  13984. current.clipGroup = null;
  13985. for (const prev of this.extraStack) {
  13986. prev.clipGroup = null;
  13987. }
  13988. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  13989. }
  13990. current.activeClipUrl = `url(#${clipId})`;
  13991. this.tgrp = null;
  13992. }
  13993. clip(type) {
  13994. this.pendingClip = type;
  13995. }
  13996. closePath() {
  13997. const current = this.current;
  13998. if (current.path) {
  13999. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  14000. current.path.setAttributeNS(null, "d", d);
  14001. }
  14002. }
  14003. setLeading(leading) {
  14004. this.current.leading = -leading;
  14005. }
  14006. setTextRise(textRise) {
  14007. this.current.textRise = textRise;
  14008. }
  14009. setTextRenderingMode(textRenderingMode) {
  14010. this.current.textRenderingMode = textRenderingMode;
  14011. }
  14012. setHScale(scale) {
  14013. this.current.textHScale = scale / 100;
  14014. }
  14015. setRenderingIntent(intent) {}
  14016. setFlatness(flatness) {}
  14017. setGState(states) {
  14018. for (const [key, value] of states) {
  14019. switch (key) {
  14020. case "LW":
  14021. this.setLineWidth(value);
  14022. break;
  14023. case "LC":
  14024. this.setLineCap(value);
  14025. break;
  14026. case "LJ":
  14027. this.setLineJoin(value);
  14028. break;
  14029. case "ML":
  14030. this.setMiterLimit(value);
  14031. break;
  14032. case "D":
  14033. this.setDash(value[0], value[1]);
  14034. break;
  14035. case "RI":
  14036. this.setRenderingIntent(value);
  14037. break;
  14038. case "FL":
  14039. this.setFlatness(value);
  14040. break;
  14041. case "Font":
  14042. this.setFont(value);
  14043. break;
  14044. case "CA":
  14045. this.setStrokeAlpha(value);
  14046. break;
  14047. case "ca":
  14048. this.setFillAlpha(value);
  14049. break;
  14050. default:
  14051. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  14052. break;
  14053. }
  14054. }
  14055. }
  14056. fill() {
  14057. const current = this.current;
  14058. if (current.element) {
  14059. current.element.setAttributeNS(null, "fill", current.fillColor);
  14060. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  14061. this.endPath();
  14062. }
  14063. }
  14064. stroke() {
  14065. const current = this.current;
  14066. if (current.element) {
  14067. this._setStrokeAttributes(current.element);
  14068. current.element.setAttributeNS(null, "fill", "none");
  14069. this.endPath();
  14070. }
  14071. }
  14072. _setStrokeAttributes(element, lineWidthScale = 1) {
  14073. const current = this.current;
  14074. let dashArray = current.dashArray;
  14075. if (lineWidthScale !== 1 && dashArray.length > 0) {
  14076. dashArray = dashArray.map(function (value) {
  14077. return lineWidthScale * value;
  14078. });
  14079. }
  14080. element.setAttributeNS(null, "stroke", current.strokeColor);
  14081. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  14082. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  14083. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  14084. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  14085. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  14086. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  14087. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  14088. }
  14089. eoFill() {
  14090. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  14091. this.fill();
  14092. }
  14093. fillStroke() {
  14094. this.stroke();
  14095. this.fill();
  14096. }
  14097. eoFillStroke() {
  14098. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  14099. this.fillStroke();
  14100. }
  14101. closeStroke() {
  14102. this.closePath();
  14103. this.stroke();
  14104. }
  14105. closeFillStroke() {
  14106. this.closePath();
  14107. this.fillStroke();
  14108. }
  14109. closeEOFillStroke() {
  14110. this.closePath();
  14111. this.eoFillStroke();
  14112. }
  14113. paintSolidColorImageMask() {
  14114. const rect = this.svgFactory.createElement("svg:rect");
  14115. rect.setAttributeNS(null, "x", "0");
  14116. rect.setAttributeNS(null, "y", "0");
  14117. rect.setAttributeNS(null, "width", "1px");
  14118. rect.setAttributeNS(null, "height", "1px");
  14119. rect.setAttributeNS(null, "fill", this.current.fillColor);
  14120. this._ensureTransformGroup().append(rect);
  14121. }
  14122. paintImageXObject(objId) {
  14123. const imgData = this.getObject(objId);
  14124. if (!imgData) {
  14125. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  14126. return;
  14127. }
  14128. this.paintInlineImageXObject(imgData);
  14129. }
  14130. paintInlineImageXObject(imgData, mask) {
  14131. const width = imgData.width;
  14132. const height = imgData.height;
  14133. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  14134. const cliprect = this.svgFactory.createElement("svg:rect");
  14135. cliprect.setAttributeNS(null, "x", "0");
  14136. cliprect.setAttributeNS(null, "y", "0");
  14137. cliprect.setAttributeNS(null, "width", pf(width));
  14138. cliprect.setAttributeNS(null, "height", pf(height));
  14139. this.current.element = cliprect;
  14140. this.clip("nonzero");
  14141. const imgEl = this.svgFactory.createElement("svg:image");
  14142. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  14143. imgEl.setAttributeNS(null, "x", "0");
  14144. imgEl.setAttributeNS(null, "y", pf(-height));
  14145. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  14146. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  14147. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  14148. if (mask) {
  14149. mask.append(imgEl);
  14150. } else {
  14151. this._ensureTransformGroup().append(imgEl);
  14152. }
  14153. }
  14154. paintImageMaskXObject(img) {
  14155. const imgData = this.getObject(img.data, img);
  14156. if (imgData.bitmap) {
  14157. (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
  14158. return;
  14159. }
  14160. const current = this.current;
  14161. const width = imgData.width;
  14162. const height = imgData.height;
  14163. const fillColor = current.fillColor;
  14164. current.maskId = `mask${maskCount++}`;
  14165. const mask = this.svgFactory.createElement("svg:mask");
  14166. mask.setAttributeNS(null, "id", current.maskId);
  14167. const rect = this.svgFactory.createElement("svg:rect");
  14168. rect.setAttributeNS(null, "x", "0");
  14169. rect.setAttributeNS(null, "y", "0");
  14170. rect.setAttributeNS(null, "width", pf(width));
  14171. rect.setAttributeNS(null, "height", pf(height));
  14172. rect.setAttributeNS(null, "fill", fillColor);
  14173. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  14174. this.defs.append(mask);
  14175. this._ensureTransformGroup().append(rect);
  14176. this.paintInlineImageXObject(imgData, mask);
  14177. }
  14178. paintFormXObjectBegin(matrix, bbox) {
  14179. if (Array.isArray(matrix) && matrix.length === 6) {
  14180. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  14181. }
  14182. if (bbox) {
  14183. const width = bbox[2] - bbox[0];
  14184. const height = bbox[3] - bbox[1];
  14185. const cliprect = this.svgFactory.createElement("svg:rect");
  14186. cliprect.setAttributeNS(null, "x", bbox[0]);
  14187. cliprect.setAttributeNS(null, "y", bbox[1]);
  14188. cliprect.setAttributeNS(null, "width", pf(width));
  14189. cliprect.setAttributeNS(null, "height", pf(height));
  14190. this.current.element = cliprect;
  14191. this.clip("nonzero");
  14192. this.endPath();
  14193. }
  14194. }
  14195. paintFormXObjectEnd() {}
  14196. _initialize(viewport) {
  14197. const svg = this.svgFactory.create(viewport.width, viewport.height);
  14198. const definitions = this.svgFactory.createElement("svg:defs");
  14199. svg.append(definitions);
  14200. this.defs = definitions;
  14201. const rootGroup = this.svgFactory.createElement("svg:g");
  14202. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  14203. svg.append(rootGroup);
  14204. this.svg = rootGroup;
  14205. return svg;
  14206. }
  14207. _ensureClipGroup() {
  14208. if (!this.current.clipGroup) {
  14209. const clipGroup = this.svgFactory.createElement("svg:g");
  14210. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  14211. this.svg.append(clipGroup);
  14212. this.current.clipGroup = clipGroup;
  14213. }
  14214. return this.current.clipGroup;
  14215. }
  14216. _ensureTransformGroup() {
  14217. if (!this.tgrp) {
  14218. this.tgrp = this.svgFactory.createElement("svg:g");
  14219. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  14220. if (this.current.activeClipUrl) {
  14221. this._ensureClipGroup().append(this.tgrp);
  14222. } else {
  14223. this.svg.append(this.tgrp);
  14224. }
  14225. }
  14226. return this.tgrp;
  14227. }
  14228. };
  14229. }
  14230. /***/ }),
  14231. /* 31 */
  14232. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14233. Object.defineProperty(exports, "__esModule", ({
  14234. value: true
  14235. }));
  14236. exports.PDFNodeStream = void 0;
  14237. var _util = __w_pdfjs_require__(1);
  14238. var _network_utils = __w_pdfjs_require__(32);
  14239. ;
  14240. const fs = require("fs");
  14241. const http = require("http");
  14242. const https = require("https");
  14243. const url = require("url");
  14244. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  14245. function parseUrl(sourceUrl) {
  14246. const parsedUrl = url.parse(sourceUrl);
  14247. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  14248. return parsedUrl;
  14249. }
  14250. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  14251. return url.parse(`file:///${sourceUrl}`);
  14252. }
  14253. if (!parsedUrl.host) {
  14254. parsedUrl.protocol = "file:";
  14255. }
  14256. return parsedUrl;
  14257. }
  14258. class PDFNodeStream {
  14259. constructor(source) {
  14260. this.source = source;
  14261. this.url = parseUrl(source.url);
  14262. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  14263. this.isFsUrl = this.url.protocol === "file:";
  14264. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  14265. this._fullRequestReader = null;
  14266. this._rangeRequestReaders = [];
  14267. }
  14268. get _progressiveDataLength() {
  14269. return this._fullRequestReader?._loaded ?? 0;
  14270. }
  14271. getFullReader() {
  14272. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  14273. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  14274. return this._fullRequestReader;
  14275. }
  14276. getRangeReader(start, end) {
  14277. if (end <= this._progressiveDataLength) {
  14278. return null;
  14279. }
  14280. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  14281. this._rangeRequestReaders.push(rangeReader);
  14282. return rangeReader;
  14283. }
  14284. cancelAllRequests(reason) {
  14285. this._fullRequestReader?.cancel(reason);
  14286. for (const reader of this._rangeRequestReaders.slice(0)) {
  14287. reader.cancel(reason);
  14288. }
  14289. }
  14290. }
  14291. exports.PDFNodeStream = PDFNodeStream;
  14292. class BaseFullReader {
  14293. constructor(stream) {
  14294. this._url = stream.url;
  14295. this._done = false;
  14296. this._storedError = null;
  14297. this.onProgress = null;
  14298. const source = stream.source;
  14299. this._contentLength = source.length;
  14300. this._loaded = 0;
  14301. this._filename = null;
  14302. this._disableRange = source.disableRange || false;
  14303. this._rangeChunkSize = source.rangeChunkSize;
  14304. if (!this._rangeChunkSize && !this._disableRange) {
  14305. this._disableRange = true;
  14306. }
  14307. this._isStreamingSupported = !source.disableStream;
  14308. this._isRangeSupported = !source.disableRange;
  14309. this._readableStream = null;
  14310. this._readCapability = (0, _util.createPromiseCapability)();
  14311. this._headersCapability = (0, _util.createPromiseCapability)();
  14312. }
  14313. get headersReady() {
  14314. return this._headersCapability.promise;
  14315. }
  14316. get filename() {
  14317. return this._filename;
  14318. }
  14319. get contentLength() {
  14320. return this._contentLength;
  14321. }
  14322. get isRangeSupported() {
  14323. return this._isRangeSupported;
  14324. }
  14325. get isStreamingSupported() {
  14326. return this._isStreamingSupported;
  14327. }
  14328. async read() {
  14329. await this._readCapability.promise;
  14330. if (this._done) {
  14331. return {
  14332. value: undefined,
  14333. done: true
  14334. };
  14335. }
  14336. if (this._storedError) {
  14337. throw this._storedError;
  14338. }
  14339. const chunk = this._readableStream.read();
  14340. if (chunk === null) {
  14341. this._readCapability = (0, _util.createPromiseCapability)();
  14342. return this.read();
  14343. }
  14344. this._loaded += chunk.length;
  14345. this.onProgress?.({
  14346. loaded: this._loaded,
  14347. total: this._contentLength
  14348. });
  14349. const buffer = new Uint8Array(chunk).buffer;
  14350. return {
  14351. value: buffer,
  14352. done: false
  14353. };
  14354. }
  14355. cancel(reason) {
  14356. if (!this._readableStream) {
  14357. this._error(reason);
  14358. return;
  14359. }
  14360. this._readableStream.destroy(reason);
  14361. }
  14362. _error(reason) {
  14363. this._storedError = reason;
  14364. this._readCapability.resolve();
  14365. }
  14366. _setReadableStream(readableStream) {
  14367. this._readableStream = readableStream;
  14368. readableStream.on("readable", () => {
  14369. this._readCapability.resolve();
  14370. });
  14371. readableStream.on("end", () => {
  14372. readableStream.destroy();
  14373. this._done = true;
  14374. this._readCapability.resolve();
  14375. });
  14376. readableStream.on("error", reason => {
  14377. this._error(reason);
  14378. });
  14379. if (!this._isStreamingSupported && this._isRangeSupported) {
  14380. this._error(new _util.AbortException("streaming is disabled"));
  14381. }
  14382. if (this._storedError) {
  14383. this._readableStream.destroy(this._storedError);
  14384. }
  14385. }
  14386. }
  14387. class BaseRangeReader {
  14388. constructor(stream) {
  14389. this._url = stream.url;
  14390. this._done = false;
  14391. this._storedError = null;
  14392. this.onProgress = null;
  14393. this._loaded = 0;
  14394. this._readableStream = null;
  14395. this._readCapability = (0, _util.createPromiseCapability)();
  14396. const source = stream.source;
  14397. this._isStreamingSupported = !source.disableStream;
  14398. }
  14399. get isStreamingSupported() {
  14400. return this._isStreamingSupported;
  14401. }
  14402. async read() {
  14403. await this._readCapability.promise;
  14404. if (this._done) {
  14405. return {
  14406. value: undefined,
  14407. done: true
  14408. };
  14409. }
  14410. if (this._storedError) {
  14411. throw this._storedError;
  14412. }
  14413. const chunk = this._readableStream.read();
  14414. if (chunk === null) {
  14415. this._readCapability = (0, _util.createPromiseCapability)();
  14416. return this.read();
  14417. }
  14418. this._loaded += chunk.length;
  14419. this.onProgress?.({
  14420. loaded: this._loaded
  14421. });
  14422. const buffer = new Uint8Array(chunk).buffer;
  14423. return {
  14424. value: buffer,
  14425. done: false
  14426. };
  14427. }
  14428. cancel(reason) {
  14429. if (!this._readableStream) {
  14430. this._error(reason);
  14431. return;
  14432. }
  14433. this._readableStream.destroy(reason);
  14434. }
  14435. _error(reason) {
  14436. this._storedError = reason;
  14437. this._readCapability.resolve();
  14438. }
  14439. _setReadableStream(readableStream) {
  14440. this._readableStream = readableStream;
  14441. readableStream.on("readable", () => {
  14442. this._readCapability.resolve();
  14443. });
  14444. readableStream.on("end", () => {
  14445. readableStream.destroy();
  14446. this._done = true;
  14447. this._readCapability.resolve();
  14448. });
  14449. readableStream.on("error", reason => {
  14450. this._error(reason);
  14451. });
  14452. if (this._storedError) {
  14453. this._readableStream.destroy(this._storedError);
  14454. }
  14455. }
  14456. }
  14457. function createRequestOptions(parsedUrl, headers) {
  14458. return {
  14459. protocol: parsedUrl.protocol,
  14460. auth: parsedUrl.auth,
  14461. host: parsedUrl.hostname,
  14462. port: parsedUrl.port,
  14463. path: parsedUrl.path,
  14464. method: "GET",
  14465. headers
  14466. };
  14467. }
  14468. class PDFNodeStreamFullReader extends BaseFullReader {
  14469. constructor(stream) {
  14470. super(stream);
  14471. const handleResponse = response => {
  14472. if (response.statusCode === 404) {
  14473. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14474. this._storedError = error;
  14475. this._headersCapability.reject(error);
  14476. return;
  14477. }
  14478. this._headersCapability.resolve();
  14479. this._setReadableStream(response);
  14480. const getResponseHeader = name => {
  14481. return this._readableStream.headers[name.toLowerCase()];
  14482. };
  14483. const {
  14484. allowRangeRequests,
  14485. suggestedLength
  14486. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14487. getResponseHeader,
  14488. isHttp: stream.isHttp,
  14489. rangeChunkSize: this._rangeChunkSize,
  14490. disableRange: this._disableRange
  14491. });
  14492. this._isRangeSupported = allowRangeRequests;
  14493. this._contentLength = suggestedLength || this._contentLength;
  14494. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  14495. };
  14496. this._request = null;
  14497. if (this._url.protocol === "http:") {
  14498. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14499. } else {
  14500. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  14501. }
  14502. this._request.on("error", reason => {
  14503. this._storedError = reason;
  14504. this._headersCapability.reject(reason);
  14505. });
  14506. this._request.end();
  14507. }
  14508. }
  14509. class PDFNodeStreamRangeReader extends BaseRangeReader {
  14510. constructor(stream, start, end) {
  14511. super(stream);
  14512. this._httpHeaders = {};
  14513. for (const property in stream.httpHeaders) {
  14514. const value = stream.httpHeaders[property];
  14515. if (value === undefined) {
  14516. continue;
  14517. }
  14518. this._httpHeaders[property] = value;
  14519. }
  14520. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  14521. const handleResponse = response => {
  14522. if (response.statusCode === 404) {
  14523. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  14524. this._storedError = error;
  14525. return;
  14526. }
  14527. this._setReadableStream(response);
  14528. };
  14529. this._request = null;
  14530. if (this._url.protocol === "http:") {
  14531. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14532. } else {
  14533. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  14534. }
  14535. this._request.on("error", reason => {
  14536. this._storedError = reason;
  14537. });
  14538. this._request.end();
  14539. }
  14540. }
  14541. class PDFNodeStreamFsFullReader extends BaseFullReader {
  14542. constructor(stream) {
  14543. super(stream);
  14544. let path = decodeURIComponent(this._url.path);
  14545. if (fileUriRegex.test(this._url.href)) {
  14546. path = path.replace(/^\//, "");
  14547. }
  14548. fs.lstat(path, (error, stat) => {
  14549. if (error) {
  14550. if (error.code === "ENOENT") {
  14551. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  14552. }
  14553. this._storedError = error;
  14554. this._headersCapability.reject(error);
  14555. return;
  14556. }
  14557. this._contentLength = stat.size;
  14558. this._setReadableStream(fs.createReadStream(path));
  14559. this._headersCapability.resolve();
  14560. });
  14561. }
  14562. }
  14563. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  14564. constructor(stream, start, end) {
  14565. super(stream);
  14566. let path = decodeURIComponent(this._url.path);
  14567. if (fileUriRegex.test(this._url.href)) {
  14568. path = path.replace(/^\//, "");
  14569. }
  14570. this._setReadableStream(fs.createReadStream(path, {
  14571. start,
  14572. end: end - 1
  14573. }));
  14574. }
  14575. }
  14576. /***/ }),
  14577. /* 32 */
  14578. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14579. Object.defineProperty(exports, "__esModule", ({
  14580. value: true
  14581. }));
  14582. exports.createResponseStatusError = createResponseStatusError;
  14583. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  14584. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  14585. exports.validateResponseStatus = validateResponseStatus;
  14586. var _util = __w_pdfjs_require__(1);
  14587. var _content_disposition = __w_pdfjs_require__(33);
  14588. var _display_utils = __w_pdfjs_require__(6);
  14589. function validateRangeRequestCapabilities({
  14590. getResponseHeader,
  14591. isHttp,
  14592. rangeChunkSize,
  14593. disableRange
  14594. }) {
  14595. const returnValues = {
  14596. allowRangeRequests: false,
  14597. suggestedLength: undefined
  14598. };
  14599. const length = parseInt(getResponseHeader("Content-Length"), 10);
  14600. if (!Number.isInteger(length)) {
  14601. return returnValues;
  14602. }
  14603. returnValues.suggestedLength = length;
  14604. if (length <= 2 * rangeChunkSize) {
  14605. return returnValues;
  14606. }
  14607. if (disableRange || !isHttp) {
  14608. return returnValues;
  14609. }
  14610. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  14611. return returnValues;
  14612. }
  14613. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  14614. if (contentEncoding !== "identity") {
  14615. return returnValues;
  14616. }
  14617. returnValues.allowRangeRequests = true;
  14618. return returnValues;
  14619. }
  14620. function extractFilenameFromHeader(getResponseHeader) {
  14621. const contentDisposition = getResponseHeader("Content-Disposition");
  14622. if (contentDisposition) {
  14623. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  14624. if (filename.includes("%")) {
  14625. try {
  14626. filename = decodeURIComponent(filename);
  14627. } catch (ex) {}
  14628. }
  14629. if ((0, _display_utils.isPdfFile)(filename)) {
  14630. return filename;
  14631. }
  14632. }
  14633. return null;
  14634. }
  14635. function createResponseStatusError(status, url) {
  14636. if (status === 404 || status === 0 && url.startsWith("file:")) {
  14637. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  14638. }
  14639. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  14640. }
  14641. function validateResponseStatus(status) {
  14642. return status === 200 || status === 206;
  14643. }
  14644. /***/ }),
  14645. /* 33 */
  14646. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14647. Object.defineProperty(exports, "__esModule", ({
  14648. value: true
  14649. }));
  14650. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  14651. var _util = __w_pdfjs_require__(1);
  14652. function getFilenameFromContentDispositionHeader(contentDisposition) {
  14653. let needsEncodingFixup = true;
  14654. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  14655. if (tmp) {
  14656. tmp = tmp[1];
  14657. let filename = rfc2616unquote(tmp);
  14658. filename = unescape(filename);
  14659. filename = rfc5987decode(filename);
  14660. filename = rfc2047decode(filename);
  14661. return fixupEncoding(filename);
  14662. }
  14663. tmp = rfc2231getparam(contentDisposition);
  14664. if (tmp) {
  14665. const filename = rfc2047decode(tmp);
  14666. return fixupEncoding(filename);
  14667. }
  14668. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  14669. if (tmp) {
  14670. tmp = tmp[1];
  14671. let filename = rfc2616unquote(tmp);
  14672. filename = rfc2047decode(filename);
  14673. return fixupEncoding(filename);
  14674. }
  14675. function toParamRegExp(attributePattern, flags) {
  14676. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  14677. }
  14678. function textdecode(encoding, value) {
  14679. if (encoding) {
  14680. if (!/^[\x00-\xFF]+$/.test(value)) {
  14681. return value;
  14682. }
  14683. try {
  14684. const decoder = new TextDecoder(encoding, {
  14685. fatal: true
  14686. });
  14687. const buffer = (0, _util.stringToBytes)(value);
  14688. value = decoder.decode(buffer);
  14689. needsEncodingFixup = false;
  14690. } catch (e) {}
  14691. }
  14692. return value;
  14693. }
  14694. function fixupEncoding(value) {
  14695. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  14696. value = textdecode("utf-8", value);
  14697. if (needsEncodingFixup) {
  14698. value = textdecode("iso-8859-1", value);
  14699. }
  14700. }
  14701. return value;
  14702. }
  14703. function rfc2231getparam(contentDispositionStr) {
  14704. const matches = [];
  14705. let match;
  14706. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  14707. while ((match = iter.exec(contentDispositionStr)) !== null) {
  14708. let [, n, quot, part] = match;
  14709. n = parseInt(n, 10);
  14710. if (n in matches) {
  14711. if (n === 0) {
  14712. break;
  14713. }
  14714. continue;
  14715. }
  14716. matches[n] = [quot, part];
  14717. }
  14718. const parts = [];
  14719. for (let n = 0; n < matches.length; ++n) {
  14720. if (!(n in matches)) {
  14721. break;
  14722. }
  14723. let [quot, part] = matches[n];
  14724. part = rfc2616unquote(part);
  14725. if (quot) {
  14726. part = unescape(part);
  14727. if (n === 0) {
  14728. part = rfc5987decode(part);
  14729. }
  14730. }
  14731. parts.push(part);
  14732. }
  14733. return parts.join("");
  14734. }
  14735. function rfc2616unquote(value) {
  14736. if (value.startsWith('"')) {
  14737. const parts = value.slice(1).split('\\"');
  14738. for (let i = 0; i < parts.length; ++i) {
  14739. const quotindex = parts[i].indexOf('"');
  14740. if (quotindex !== -1) {
  14741. parts[i] = parts[i].slice(0, quotindex);
  14742. parts.length = i + 1;
  14743. }
  14744. parts[i] = parts[i].replace(/\\(.)/g, "$1");
  14745. }
  14746. value = parts.join('"');
  14747. }
  14748. return value;
  14749. }
  14750. function rfc5987decode(extvalue) {
  14751. const encodingend = extvalue.indexOf("'");
  14752. if (encodingend === -1) {
  14753. return extvalue;
  14754. }
  14755. const encoding = extvalue.slice(0, encodingend);
  14756. const langvalue = extvalue.slice(encodingend + 1);
  14757. const value = langvalue.replace(/^[^']*'/, "");
  14758. return textdecode(encoding, value);
  14759. }
  14760. function rfc2047decode(value) {
  14761. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  14762. return value;
  14763. }
  14764. return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  14765. if (encoding === "q" || encoding === "Q") {
  14766. text = text.replace(/_/g, " ");
  14767. text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  14768. return String.fromCharCode(parseInt(hex, 16));
  14769. });
  14770. return textdecode(charset, text);
  14771. }
  14772. try {
  14773. text = atob(text);
  14774. } catch (e) {}
  14775. return textdecode(charset, text);
  14776. });
  14777. }
  14778. return "";
  14779. }
  14780. /***/ }),
  14781. /* 34 */
  14782. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14783. Object.defineProperty(exports, "__esModule", ({
  14784. value: true
  14785. }));
  14786. exports.PDFNetworkStream = void 0;
  14787. var _util = __w_pdfjs_require__(1);
  14788. var _network_utils = __w_pdfjs_require__(32);
  14789. ;
  14790. const OK_RESPONSE = 200;
  14791. const PARTIAL_CONTENT_RESPONSE = 206;
  14792. function getArrayBuffer(xhr) {
  14793. const data = xhr.response;
  14794. if (typeof data !== "string") {
  14795. return data;
  14796. }
  14797. const array = (0, _util.stringToBytes)(data);
  14798. return array.buffer;
  14799. }
  14800. class NetworkManager {
  14801. constructor(url, args = {}) {
  14802. this.url = url;
  14803. this.isHttp = /^https?:/i.test(url);
  14804. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  14805. this.withCredentials = args.withCredentials || false;
  14806. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  14807. return new XMLHttpRequest();
  14808. };
  14809. this.currXhrId = 0;
  14810. this.pendingRequests = Object.create(null);
  14811. }
  14812. requestRange(begin, end, listeners) {
  14813. const args = {
  14814. begin,
  14815. end
  14816. };
  14817. for (const prop in listeners) {
  14818. args[prop] = listeners[prop];
  14819. }
  14820. return this.request(args);
  14821. }
  14822. requestFull(listeners) {
  14823. return this.request(listeners);
  14824. }
  14825. request(args) {
  14826. const xhr = this.getXhr();
  14827. const xhrId = this.currXhrId++;
  14828. const pendingRequest = this.pendingRequests[xhrId] = {
  14829. xhr
  14830. };
  14831. xhr.open("GET", this.url);
  14832. xhr.withCredentials = this.withCredentials;
  14833. for (const property in this.httpHeaders) {
  14834. const value = this.httpHeaders[property];
  14835. if (value === undefined) {
  14836. continue;
  14837. }
  14838. xhr.setRequestHeader(property, value);
  14839. }
  14840. if (this.isHttp && "begin" in args && "end" in args) {
  14841. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  14842. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  14843. } else {
  14844. pendingRequest.expectedStatus = OK_RESPONSE;
  14845. }
  14846. xhr.responseType = "arraybuffer";
  14847. if (args.onError) {
  14848. xhr.onerror = function (evt) {
  14849. args.onError(xhr.status);
  14850. };
  14851. }
  14852. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  14853. xhr.onprogress = this.onProgress.bind(this, xhrId);
  14854. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  14855. pendingRequest.onDone = args.onDone;
  14856. pendingRequest.onError = args.onError;
  14857. pendingRequest.onProgress = args.onProgress;
  14858. xhr.send(null);
  14859. return xhrId;
  14860. }
  14861. onProgress(xhrId, evt) {
  14862. const pendingRequest = this.pendingRequests[xhrId];
  14863. if (!pendingRequest) {
  14864. return;
  14865. }
  14866. pendingRequest.onProgress?.(evt);
  14867. }
  14868. onStateChange(xhrId, evt) {
  14869. const pendingRequest = this.pendingRequests[xhrId];
  14870. if (!pendingRequest) {
  14871. return;
  14872. }
  14873. const xhr = pendingRequest.xhr;
  14874. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  14875. pendingRequest.onHeadersReceived();
  14876. delete pendingRequest.onHeadersReceived;
  14877. }
  14878. if (xhr.readyState !== 4) {
  14879. return;
  14880. }
  14881. if (!(xhrId in this.pendingRequests)) {
  14882. return;
  14883. }
  14884. delete this.pendingRequests[xhrId];
  14885. if (xhr.status === 0 && this.isHttp) {
  14886. pendingRequest.onError?.(xhr.status);
  14887. return;
  14888. }
  14889. const xhrStatus = xhr.status || OK_RESPONSE;
  14890. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  14891. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  14892. pendingRequest.onError?.(xhr.status);
  14893. return;
  14894. }
  14895. const chunk = getArrayBuffer(xhr);
  14896. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  14897. const rangeHeader = xhr.getResponseHeader("Content-Range");
  14898. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  14899. pendingRequest.onDone({
  14900. begin: parseInt(matches[1], 10),
  14901. chunk
  14902. });
  14903. } else if (chunk) {
  14904. pendingRequest.onDone({
  14905. begin: 0,
  14906. chunk
  14907. });
  14908. } else {
  14909. pendingRequest.onError?.(xhr.status);
  14910. }
  14911. }
  14912. getRequestXhr(xhrId) {
  14913. return this.pendingRequests[xhrId].xhr;
  14914. }
  14915. isPendingRequest(xhrId) {
  14916. return xhrId in this.pendingRequests;
  14917. }
  14918. abortRequest(xhrId) {
  14919. const xhr = this.pendingRequests[xhrId].xhr;
  14920. delete this.pendingRequests[xhrId];
  14921. xhr.abort();
  14922. }
  14923. }
  14924. class PDFNetworkStream {
  14925. constructor(source) {
  14926. this._source = source;
  14927. this._manager = new NetworkManager(source.url, {
  14928. httpHeaders: source.httpHeaders,
  14929. withCredentials: source.withCredentials
  14930. });
  14931. this._rangeChunkSize = source.rangeChunkSize;
  14932. this._fullRequestReader = null;
  14933. this._rangeRequestReaders = [];
  14934. }
  14935. _onRangeRequestReaderClosed(reader) {
  14936. const i = this._rangeRequestReaders.indexOf(reader);
  14937. if (i >= 0) {
  14938. this._rangeRequestReaders.splice(i, 1);
  14939. }
  14940. }
  14941. getFullReader() {
  14942. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  14943. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  14944. return this._fullRequestReader;
  14945. }
  14946. getRangeReader(begin, end) {
  14947. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  14948. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  14949. this._rangeRequestReaders.push(reader);
  14950. return reader;
  14951. }
  14952. cancelAllRequests(reason) {
  14953. this._fullRequestReader?.cancel(reason);
  14954. for (const reader of this._rangeRequestReaders.slice(0)) {
  14955. reader.cancel(reason);
  14956. }
  14957. }
  14958. }
  14959. exports.PDFNetworkStream = PDFNetworkStream;
  14960. class PDFNetworkStreamFullRequestReader {
  14961. constructor(manager, source) {
  14962. this._manager = manager;
  14963. const args = {
  14964. onHeadersReceived: this._onHeadersReceived.bind(this),
  14965. onDone: this._onDone.bind(this),
  14966. onError: this._onError.bind(this),
  14967. onProgress: this._onProgress.bind(this)
  14968. };
  14969. this._url = source.url;
  14970. this._fullRequestId = manager.requestFull(args);
  14971. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  14972. this._disableRange = source.disableRange || false;
  14973. this._contentLength = source.length;
  14974. this._rangeChunkSize = source.rangeChunkSize;
  14975. if (!this._rangeChunkSize && !this._disableRange) {
  14976. this._disableRange = true;
  14977. }
  14978. this._isStreamingSupported = false;
  14979. this._isRangeSupported = false;
  14980. this._cachedChunks = [];
  14981. this._requests = [];
  14982. this._done = false;
  14983. this._storedError = undefined;
  14984. this._filename = null;
  14985. this.onProgress = null;
  14986. }
  14987. _onHeadersReceived() {
  14988. const fullRequestXhrId = this._fullRequestId;
  14989. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  14990. const getResponseHeader = name => {
  14991. return fullRequestXhr.getResponseHeader(name);
  14992. };
  14993. const {
  14994. allowRangeRequests,
  14995. suggestedLength
  14996. } = (0, _network_utils.validateRangeRequestCapabilities)({
  14997. getResponseHeader,
  14998. isHttp: this._manager.isHttp,
  14999. rangeChunkSize: this._rangeChunkSize,
  15000. disableRange: this._disableRange
  15001. });
  15002. if (allowRangeRequests) {
  15003. this._isRangeSupported = true;
  15004. }
  15005. this._contentLength = suggestedLength || this._contentLength;
  15006. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15007. if (this._isRangeSupported) {
  15008. this._manager.abortRequest(fullRequestXhrId);
  15009. }
  15010. this._headersReceivedCapability.resolve();
  15011. }
  15012. _onDone(data) {
  15013. if (data) {
  15014. if (this._requests.length > 0) {
  15015. const requestCapability = this._requests.shift();
  15016. requestCapability.resolve({
  15017. value: data.chunk,
  15018. done: false
  15019. });
  15020. } else {
  15021. this._cachedChunks.push(data.chunk);
  15022. }
  15023. }
  15024. this._done = true;
  15025. if (this._cachedChunks.length > 0) {
  15026. return;
  15027. }
  15028. for (const requestCapability of this._requests) {
  15029. requestCapability.resolve({
  15030. value: undefined,
  15031. done: true
  15032. });
  15033. }
  15034. this._requests.length = 0;
  15035. }
  15036. _onError(status) {
  15037. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  15038. this._headersReceivedCapability.reject(this._storedError);
  15039. for (const requestCapability of this._requests) {
  15040. requestCapability.reject(this._storedError);
  15041. }
  15042. this._requests.length = 0;
  15043. this._cachedChunks.length = 0;
  15044. }
  15045. _onProgress(evt) {
  15046. this.onProgress?.({
  15047. loaded: evt.loaded,
  15048. total: evt.lengthComputable ? evt.total : this._contentLength
  15049. });
  15050. }
  15051. get filename() {
  15052. return this._filename;
  15053. }
  15054. get isRangeSupported() {
  15055. return this._isRangeSupported;
  15056. }
  15057. get isStreamingSupported() {
  15058. return this._isStreamingSupported;
  15059. }
  15060. get contentLength() {
  15061. return this._contentLength;
  15062. }
  15063. get headersReady() {
  15064. return this._headersReceivedCapability.promise;
  15065. }
  15066. async read() {
  15067. if (this._storedError) {
  15068. throw this._storedError;
  15069. }
  15070. if (this._cachedChunks.length > 0) {
  15071. const chunk = this._cachedChunks.shift();
  15072. return {
  15073. value: chunk,
  15074. done: false
  15075. };
  15076. }
  15077. if (this._done) {
  15078. return {
  15079. value: undefined,
  15080. done: true
  15081. };
  15082. }
  15083. const requestCapability = (0, _util.createPromiseCapability)();
  15084. this._requests.push(requestCapability);
  15085. return requestCapability.promise;
  15086. }
  15087. cancel(reason) {
  15088. this._done = true;
  15089. this._headersReceivedCapability.reject(reason);
  15090. for (const requestCapability of this._requests) {
  15091. requestCapability.resolve({
  15092. value: undefined,
  15093. done: true
  15094. });
  15095. }
  15096. this._requests.length = 0;
  15097. if (this._manager.isPendingRequest(this._fullRequestId)) {
  15098. this._manager.abortRequest(this._fullRequestId);
  15099. }
  15100. this._fullRequestReader = null;
  15101. }
  15102. }
  15103. class PDFNetworkStreamRangeRequestReader {
  15104. constructor(manager, begin, end) {
  15105. this._manager = manager;
  15106. const args = {
  15107. onDone: this._onDone.bind(this),
  15108. onError: this._onError.bind(this),
  15109. onProgress: this._onProgress.bind(this)
  15110. };
  15111. this._url = manager.url;
  15112. this._requestId = manager.requestRange(begin, end, args);
  15113. this._requests = [];
  15114. this._queuedChunk = null;
  15115. this._done = false;
  15116. this._storedError = undefined;
  15117. this.onProgress = null;
  15118. this.onClosed = null;
  15119. }
  15120. _close() {
  15121. this.onClosed?.(this);
  15122. }
  15123. _onDone(data) {
  15124. const chunk = data.chunk;
  15125. if (this._requests.length > 0) {
  15126. const requestCapability = this._requests.shift();
  15127. requestCapability.resolve({
  15128. value: chunk,
  15129. done: false
  15130. });
  15131. } else {
  15132. this._queuedChunk = chunk;
  15133. }
  15134. this._done = true;
  15135. for (const requestCapability of this._requests) {
  15136. requestCapability.resolve({
  15137. value: undefined,
  15138. done: true
  15139. });
  15140. }
  15141. this._requests.length = 0;
  15142. this._close();
  15143. }
  15144. _onError(status) {
  15145. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  15146. for (const requestCapability of this._requests) {
  15147. requestCapability.reject(this._storedError);
  15148. }
  15149. this._requests.length = 0;
  15150. this._queuedChunk = null;
  15151. }
  15152. _onProgress(evt) {
  15153. if (!this.isStreamingSupported) {
  15154. this.onProgress?.({
  15155. loaded: evt.loaded
  15156. });
  15157. }
  15158. }
  15159. get isStreamingSupported() {
  15160. return false;
  15161. }
  15162. async read() {
  15163. if (this._storedError) {
  15164. throw this._storedError;
  15165. }
  15166. if (this._queuedChunk !== null) {
  15167. const chunk = this._queuedChunk;
  15168. this._queuedChunk = null;
  15169. return {
  15170. value: chunk,
  15171. done: false
  15172. };
  15173. }
  15174. if (this._done) {
  15175. return {
  15176. value: undefined,
  15177. done: true
  15178. };
  15179. }
  15180. const requestCapability = (0, _util.createPromiseCapability)();
  15181. this._requests.push(requestCapability);
  15182. return requestCapability.promise;
  15183. }
  15184. cancel(reason) {
  15185. this._done = true;
  15186. for (const requestCapability of this._requests) {
  15187. requestCapability.resolve({
  15188. value: undefined,
  15189. done: true
  15190. });
  15191. }
  15192. this._requests.length = 0;
  15193. if (this._manager.isPendingRequest(this._requestId)) {
  15194. this._manager.abortRequest(this._requestId);
  15195. }
  15196. this._close();
  15197. }
  15198. }
  15199. /***/ }),
  15200. /* 35 */
  15201. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  15202. Object.defineProperty(exports, "__esModule", ({
  15203. value: true
  15204. }));
  15205. exports.PDFFetchStream = void 0;
  15206. var _util = __w_pdfjs_require__(1);
  15207. var _network_utils = __w_pdfjs_require__(32);
  15208. ;
  15209. function createFetchOptions(headers, withCredentials, abortController) {
  15210. return {
  15211. method: "GET",
  15212. headers,
  15213. signal: abortController.signal,
  15214. mode: "cors",
  15215. credentials: withCredentials ? "include" : "same-origin",
  15216. redirect: "follow"
  15217. };
  15218. }
  15219. function createHeaders(httpHeaders) {
  15220. const headers = new Headers();
  15221. for (const property in httpHeaders) {
  15222. const value = httpHeaders[property];
  15223. if (value === undefined) {
  15224. continue;
  15225. }
  15226. headers.append(property, value);
  15227. }
  15228. return headers;
  15229. }
  15230. class PDFFetchStream {
  15231. constructor(source) {
  15232. this.source = source;
  15233. this.isHttp = /^https?:/i.test(source.url);
  15234. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  15235. this._fullRequestReader = null;
  15236. this._rangeRequestReaders = [];
  15237. }
  15238. get _progressiveDataLength() {
  15239. return this._fullRequestReader?._loaded ?? 0;
  15240. }
  15241. getFullReader() {
  15242. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  15243. this._fullRequestReader = new PDFFetchStreamReader(this);
  15244. return this._fullRequestReader;
  15245. }
  15246. getRangeReader(begin, end) {
  15247. if (end <= this._progressiveDataLength) {
  15248. return null;
  15249. }
  15250. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  15251. this._rangeRequestReaders.push(reader);
  15252. return reader;
  15253. }
  15254. cancelAllRequests(reason) {
  15255. this._fullRequestReader?.cancel(reason);
  15256. for (const reader of this._rangeRequestReaders.slice(0)) {
  15257. reader.cancel(reason);
  15258. }
  15259. }
  15260. }
  15261. exports.PDFFetchStream = PDFFetchStream;
  15262. class PDFFetchStreamReader {
  15263. constructor(stream) {
  15264. this._stream = stream;
  15265. this._reader = null;
  15266. this._loaded = 0;
  15267. this._filename = null;
  15268. const source = stream.source;
  15269. this._withCredentials = source.withCredentials || false;
  15270. this._contentLength = source.length;
  15271. this._headersCapability = (0, _util.createPromiseCapability)();
  15272. this._disableRange = source.disableRange || false;
  15273. this._rangeChunkSize = source.rangeChunkSize;
  15274. if (!this._rangeChunkSize && !this._disableRange) {
  15275. this._disableRange = true;
  15276. }
  15277. this._abortController = new AbortController();
  15278. this._isStreamingSupported = !source.disableStream;
  15279. this._isRangeSupported = !source.disableRange;
  15280. this._headers = createHeaders(this._stream.httpHeaders);
  15281. const url = source.url;
  15282. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15283. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15284. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15285. }
  15286. this._reader = response.body.getReader();
  15287. this._headersCapability.resolve();
  15288. const getResponseHeader = name => {
  15289. return response.headers.get(name);
  15290. };
  15291. const {
  15292. allowRangeRequests,
  15293. suggestedLength
  15294. } = (0, _network_utils.validateRangeRequestCapabilities)({
  15295. getResponseHeader,
  15296. isHttp: this._stream.isHttp,
  15297. rangeChunkSize: this._rangeChunkSize,
  15298. disableRange: this._disableRange
  15299. });
  15300. this._isRangeSupported = allowRangeRequests;
  15301. this._contentLength = suggestedLength || this._contentLength;
  15302. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  15303. if (!this._isStreamingSupported && this._isRangeSupported) {
  15304. this.cancel(new _util.AbortException("Streaming is disabled."));
  15305. }
  15306. }).catch(this._headersCapability.reject);
  15307. this.onProgress = null;
  15308. }
  15309. get headersReady() {
  15310. return this._headersCapability.promise;
  15311. }
  15312. get filename() {
  15313. return this._filename;
  15314. }
  15315. get contentLength() {
  15316. return this._contentLength;
  15317. }
  15318. get isRangeSupported() {
  15319. return this._isRangeSupported;
  15320. }
  15321. get isStreamingSupported() {
  15322. return this._isStreamingSupported;
  15323. }
  15324. async read() {
  15325. await this._headersCapability.promise;
  15326. const {
  15327. value,
  15328. done
  15329. } = await this._reader.read();
  15330. if (done) {
  15331. return {
  15332. value,
  15333. done
  15334. };
  15335. }
  15336. this._loaded += value.byteLength;
  15337. this.onProgress?.({
  15338. loaded: this._loaded,
  15339. total: this._contentLength
  15340. });
  15341. const buffer = new Uint8Array(value).buffer;
  15342. return {
  15343. value: buffer,
  15344. done: false
  15345. };
  15346. }
  15347. cancel(reason) {
  15348. this._reader?.cancel(reason);
  15349. this._abortController.abort();
  15350. }
  15351. }
  15352. class PDFFetchStreamRangeReader {
  15353. constructor(stream, begin, end) {
  15354. this._stream = stream;
  15355. this._reader = null;
  15356. this._loaded = 0;
  15357. const source = stream.source;
  15358. this._withCredentials = source.withCredentials || false;
  15359. this._readCapability = (0, _util.createPromiseCapability)();
  15360. this._isStreamingSupported = !source.disableStream;
  15361. this._abortController = new AbortController();
  15362. this._headers = createHeaders(this._stream.httpHeaders);
  15363. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  15364. const url = source.url;
  15365. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  15366. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  15367. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  15368. }
  15369. this._readCapability.resolve();
  15370. this._reader = response.body.getReader();
  15371. }).catch(this._readCapability.reject);
  15372. this.onProgress = null;
  15373. }
  15374. get isStreamingSupported() {
  15375. return this._isStreamingSupported;
  15376. }
  15377. async read() {
  15378. await this._readCapability.promise;
  15379. const {
  15380. value,
  15381. done
  15382. } = await this._reader.read();
  15383. if (done) {
  15384. return {
  15385. value,
  15386. done
  15387. };
  15388. }
  15389. this._loaded += value.byteLength;
  15390. this.onProgress?.({
  15391. loaded: this._loaded
  15392. });
  15393. const buffer = new Uint8Array(value).buffer;
  15394. return {
  15395. value: buffer,
  15396. done: false
  15397. };
  15398. }
  15399. cancel(reason) {
  15400. this._reader?.cancel(reason);
  15401. this._abortController.abort();
  15402. }
  15403. }
  15404. /***/ })
  15405. /******/ ]);
  15406. /************************************************************************/
  15407. /******/ // The module cache
  15408. /******/ var __webpack_module_cache__ = {};
  15409. /******/
  15410. /******/ // The require function
  15411. /******/ function __w_pdfjs_require__(moduleId) {
  15412. /******/ // Check if module is in cache
  15413. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  15414. /******/ if (cachedModule !== undefined) {
  15415. /******/ return cachedModule.exports;
  15416. /******/ }
  15417. /******/ // Create a new module (and put it into the cache)
  15418. /******/ var module = __webpack_module_cache__[moduleId] = {
  15419. /******/ // no module.id needed
  15420. /******/ // no module.loaded needed
  15421. /******/ exports: {}
  15422. /******/ };
  15423. /******/
  15424. /******/ // Execute the module function
  15425. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  15426. /******/
  15427. /******/ // Return the exports of the module
  15428. /******/ return module.exports;
  15429. /******/ }
  15430. /******/
  15431. /************************************************************************/
  15432. var __webpack_exports__ = {};
  15433. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  15434. (() => {
  15435. var exports = __webpack_exports__;
  15436. Object.defineProperty(exports, "__esModule", ({
  15437. value: true
  15438. }));
  15439. Object.defineProperty(exports, "AbortException", ({
  15440. enumerable: true,
  15441. get: function () {
  15442. return _util.AbortException;
  15443. }
  15444. }));
  15445. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  15446. enumerable: true,
  15447. get: function () {
  15448. return _annotation_editor_layer.AnnotationEditorLayer;
  15449. }
  15450. }));
  15451. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  15452. enumerable: true,
  15453. get: function () {
  15454. return _util.AnnotationEditorParamsType;
  15455. }
  15456. }));
  15457. Object.defineProperty(exports, "AnnotationEditorType", ({
  15458. enumerable: true,
  15459. get: function () {
  15460. return _util.AnnotationEditorType;
  15461. }
  15462. }));
  15463. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  15464. enumerable: true,
  15465. get: function () {
  15466. return _tools.AnnotationEditorUIManager;
  15467. }
  15468. }));
  15469. Object.defineProperty(exports, "AnnotationLayer", ({
  15470. enumerable: true,
  15471. get: function () {
  15472. return _annotation_layer.AnnotationLayer;
  15473. }
  15474. }));
  15475. Object.defineProperty(exports, "AnnotationMode", ({
  15476. enumerable: true,
  15477. get: function () {
  15478. return _util.AnnotationMode;
  15479. }
  15480. }));
  15481. Object.defineProperty(exports, "CMapCompressionType", ({
  15482. enumerable: true,
  15483. get: function () {
  15484. return _util.CMapCompressionType;
  15485. }
  15486. }));
  15487. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  15488. enumerable: true,
  15489. get: function () {
  15490. return _worker_options.GlobalWorkerOptions;
  15491. }
  15492. }));
  15493. Object.defineProperty(exports, "InvalidPDFException", ({
  15494. enumerable: true,
  15495. get: function () {
  15496. return _util.InvalidPDFException;
  15497. }
  15498. }));
  15499. Object.defineProperty(exports, "MissingPDFException", ({
  15500. enumerable: true,
  15501. get: function () {
  15502. return _util.MissingPDFException;
  15503. }
  15504. }));
  15505. Object.defineProperty(exports, "OPS", ({
  15506. enumerable: true,
  15507. get: function () {
  15508. return _util.OPS;
  15509. }
  15510. }));
  15511. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  15512. enumerable: true,
  15513. get: function () {
  15514. return _api.PDFDataRangeTransport;
  15515. }
  15516. }));
  15517. Object.defineProperty(exports, "PDFDateString", ({
  15518. enumerable: true,
  15519. get: function () {
  15520. return _display_utils.PDFDateString;
  15521. }
  15522. }));
  15523. Object.defineProperty(exports, "PDFWorker", ({
  15524. enumerable: true,
  15525. get: function () {
  15526. return _api.PDFWorker;
  15527. }
  15528. }));
  15529. Object.defineProperty(exports, "PasswordResponses", ({
  15530. enumerable: true,
  15531. get: function () {
  15532. return _util.PasswordResponses;
  15533. }
  15534. }));
  15535. Object.defineProperty(exports, "PermissionFlag", ({
  15536. enumerable: true,
  15537. get: function () {
  15538. return _util.PermissionFlag;
  15539. }
  15540. }));
  15541. Object.defineProperty(exports, "PixelsPerInch", ({
  15542. enumerable: true,
  15543. get: function () {
  15544. return _display_utils.PixelsPerInch;
  15545. }
  15546. }));
  15547. Object.defineProperty(exports, "RenderingCancelledException", ({
  15548. enumerable: true,
  15549. get: function () {
  15550. return _display_utils.RenderingCancelledException;
  15551. }
  15552. }));
  15553. Object.defineProperty(exports, "SVGGraphics", ({
  15554. enumerable: true,
  15555. get: function () {
  15556. return _svg.SVGGraphics;
  15557. }
  15558. }));
  15559. Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  15560. enumerable: true,
  15561. get: function () {
  15562. return _util.UNSUPPORTED_FEATURES;
  15563. }
  15564. }));
  15565. Object.defineProperty(exports, "UnexpectedResponseException", ({
  15566. enumerable: true,
  15567. get: function () {
  15568. return _util.UnexpectedResponseException;
  15569. }
  15570. }));
  15571. Object.defineProperty(exports, "Util", ({
  15572. enumerable: true,
  15573. get: function () {
  15574. return _util.Util;
  15575. }
  15576. }));
  15577. Object.defineProperty(exports, "VerbosityLevel", ({
  15578. enumerable: true,
  15579. get: function () {
  15580. return _util.VerbosityLevel;
  15581. }
  15582. }));
  15583. Object.defineProperty(exports, "XfaLayer", ({
  15584. enumerable: true,
  15585. get: function () {
  15586. return _xfa_layer.XfaLayer;
  15587. }
  15588. }));
  15589. Object.defineProperty(exports, "build", ({
  15590. enumerable: true,
  15591. get: function () {
  15592. return _api.build;
  15593. }
  15594. }));
  15595. Object.defineProperty(exports, "createPromiseCapability", ({
  15596. enumerable: true,
  15597. get: function () {
  15598. return _util.createPromiseCapability;
  15599. }
  15600. }));
  15601. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  15602. enumerable: true,
  15603. get: function () {
  15604. return _util.createValidAbsoluteUrl;
  15605. }
  15606. }));
  15607. Object.defineProperty(exports, "getDocument", ({
  15608. enumerable: true,
  15609. get: function () {
  15610. return _api.getDocument;
  15611. }
  15612. }));
  15613. Object.defineProperty(exports, "getFilenameFromUrl", ({
  15614. enumerable: true,
  15615. get: function () {
  15616. return _display_utils.getFilenameFromUrl;
  15617. }
  15618. }));
  15619. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  15620. enumerable: true,
  15621. get: function () {
  15622. return _display_utils.getPdfFilenameFromUrl;
  15623. }
  15624. }));
  15625. Object.defineProperty(exports, "getXfaPageViewport", ({
  15626. enumerable: true,
  15627. get: function () {
  15628. return _display_utils.getXfaPageViewport;
  15629. }
  15630. }));
  15631. Object.defineProperty(exports, "isDataScheme", ({
  15632. enumerable: true,
  15633. get: function () {
  15634. return _display_utils.isDataScheme;
  15635. }
  15636. }));
  15637. Object.defineProperty(exports, "isPdfFile", ({
  15638. enumerable: true,
  15639. get: function () {
  15640. return _display_utils.isPdfFile;
  15641. }
  15642. }));
  15643. Object.defineProperty(exports, "loadScript", ({
  15644. enumerable: true,
  15645. get: function () {
  15646. return _display_utils.loadScript;
  15647. }
  15648. }));
  15649. Object.defineProperty(exports, "renderTextLayer", ({
  15650. enumerable: true,
  15651. get: function () {
  15652. return _text_layer.renderTextLayer;
  15653. }
  15654. }));
  15655. Object.defineProperty(exports, "setLayerDimensions", ({
  15656. enumerable: true,
  15657. get: function () {
  15658. return _display_utils.setLayerDimensions;
  15659. }
  15660. }));
  15661. Object.defineProperty(exports, "shadow", ({
  15662. enumerable: true,
  15663. get: function () {
  15664. return _util.shadow;
  15665. }
  15666. }));
  15667. Object.defineProperty(exports, "updateTextLayer", ({
  15668. enumerable: true,
  15669. get: function () {
  15670. return _text_layer.updateTextLayer;
  15671. }
  15672. }));
  15673. Object.defineProperty(exports, "version", ({
  15674. enumerable: true,
  15675. get: function () {
  15676. return _api.version;
  15677. }
  15678. }));
  15679. var _util = __w_pdfjs_require__(1);
  15680. var _api = __w_pdfjs_require__(2);
  15681. var _display_utils = __w_pdfjs_require__(6);
  15682. var _text_layer = __w_pdfjs_require__(21);
  15683. var _annotation_editor_layer = __w_pdfjs_require__(22);
  15684. var _tools = __w_pdfjs_require__(5);
  15685. var _annotation_layer = __w_pdfjs_require__(27);
  15686. var _worker_options = __w_pdfjs_require__(14);
  15687. var _is_node = __w_pdfjs_require__(10);
  15688. var _svg = __w_pdfjs_require__(30);
  15689. var _xfa_layer = __w_pdfjs_require__(29);
  15690. const pdfjsVersion = '3.2.141';
  15691. const pdfjsBuild = '35ca6ab31';
  15692. {
  15693. if (_is_node.isNodeJS) {
  15694. const {
  15695. PDFNodeStream
  15696. } = __w_pdfjs_require__(31);
  15697. (0, _api.setPDFNetworkStreamFactory)(params => {
  15698. return new PDFNodeStream(params);
  15699. });
  15700. } else {
  15701. const {
  15702. PDFNetworkStream
  15703. } = __w_pdfjs_require__(34);
  15704. const {
  15705. PDFFetchStream
  15706. } = __w_pdfjs_require__(35);
  15707. (0, _api.setPDFNetworkStreamFactory)(params => {
  15708. if ((0, _display_utils.isValidFetchUrl)(params.url)) {
  15709. return new PDFFetchStream(params);
  15710. }
  15711. return new PDFNetworkStream(params);
  15712. });
  15713. }
  15714. }
  15715. })();
  15716. /******/ return __webpack_exports__;
  15717. /******/ })()
  15718. ;
  15719. });
  15720. //# sourceMappingURL=pdf.js.map