pdf.js 495 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2023 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. (function webpackUniversalModuleDefinition(root, factory) {
  23. if(typeof exports === 'object' && typeof module === 'object')
  24. module.exports = 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.TextRenderingMode = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.MAX_IMAGE_SIZE_TO_CACHE = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.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.assert = assert;
  43. exports.bytesToString = bytesToString;
  44. exports.createPromiseCapability = createPromiseCapability;
  45. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  46. exports.getModificationDate = getModificationDate;
  47. exports.getVerbosityLevel = getVerbosityLevel;
  48. exports.info = info;
  49. exports.isArrayBuffer = isArrayBuffer;
  50. exports.isArrayEqual = isArrayEqual;
  51. exports.objectFromMap = objectFromMap;
  52. exports.objectSize = objectSize;
  53. exports.setVerbosityLevel = setVerbosityLevel;
  54. exports.shadow = shadow;
  55. exports.string32 = string32;
  56. exports.stringToBytes = stringToBytes;
  57. exports.stringToPDFString = stringToPDFString;
  58. exports.stringToUTF8String = stringToUTF8String;
  59. exports.unreachable = unreachable;
  60. exports.utf8StringToString = utf8StringToString;
  61. exports.warn = warn;
  62. ;
  63. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  64. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  65. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  66. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  67. const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
  68. exports.MAX_IMAGE_SIZE_TO_CACHE = MAX_IMAGE_SIZE_TO_CACHE;
  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 VerbosityLevel = {
  267. ERRORS: 0,
  268. WARNINGS: 1,
  269. INFOS: 5
  270. };
  271. exports.VerbosityLevel = VerbosityLevel;
  272. const CMapCompressionType = {
  273. NONE: 0,
  274. BINARY: 1
  275. };
  276. exports.CMapCompressionType = CMapCompressionType;
  277. const OPS = {
  278. dependency: 1,
  279. setLineWidth: 2,
  280. setLineCap: 3,
  281. setLineJoin: 4,
  282. setMiterLimit: 5,
  283. setDash: 6,
  284. setRenderingIntent: 7,
  285. setFlatness: 8,
  286. setGState: 9,
  287. save: 10,
  288. restore: 11,
  289. transform: 12,
  290. moveTo: 13,
  291. lineTo: 14,
  292. curveTo: 15,
  293. curveTo2: 16,
  294. curveTo3: 17,
  295. closePath: 18,
  296. rectangle: 19,
  297. stroke: 20,
  298. closeStroke: 21,
  299. fill: 22,
  300. eoFill: 23,
  301. fillStroke: 24,
  302. eoFillStroke: 25,
  303. closeFillStroke: 26,
  304. closeEOFillStroke: 27,
  305. endPath: 28,
  306. clip: 29,
  307. eoClip: 30,
  308. beginText: 31,
  309. endText: 32,
  310. setCharSpacing: 33,
  311. setWordSpacing: 34,
  312. setHScale: 35,
  313. setLeading: 36,
  314. setFont: 37,
  315. setTextRenderingMode: 38,
  316. setTextRise: 39,
  317. moveText: 40,
  318. setLeadingMoveText: 41,
  319. setTextMatrix: 42,
  320. nextLine: 43,
  321. showText: 44,
  322. showSpacedText: 45,
  323. nextLineShowText: 46,
  324. nextLineSetSpacingShowText: 47,
  325. setCharWidth: 48,
  326. setCharWidthAndBounds: 49,
  327. setStrokeColorSpace: 50,
  328. setFillColorSpace: 51,
  329. setStrokeColor: 52,
  330. setStrokeColorN: 53,
  331. setFillColor: 54,
  332. setFillColorN: 55,
  333. setStrokeGray: 56,
  334. setFillGray: 57,
  335. setStrokeRGBColor: 58,
  336. setFillRGBColor: 59,
  337. setStrokeCMYKColor: 60,
  338. setFillCMYKColor: 61,
  339. shadingFill: 62,
  340. beginInlineImage: 63,
  341. beginImageData: 64,
  342. endInlineImage: 65,
  343. paintXObject: 66,
  344. markPoint: 67,
  345. markPointProps: 68,
  346. beginMarkedContent: 69,
  347. beginMarkedContentProps: 70,
  348. endMarkedContent: 71,
  349. beginCompat: 72,
  350. endCompat: 73,
  351. paintFormXObjectBegin: 74,
  352. paintFormXObjectEnd: 75,
  353. beginGroup: 76,
  354. endGroup: 77,
  355. beginAnnotation: 80,
  356. endAnnotation: 81,
  357. paintImageMaskXObject: 83,
  358. paintImageMaskXObjectGroup: 84,
  359. paintImageXObject: 85,
  360. paintInlineImageXObject: 86,
  361. paintInlineImageXObjectGroup: 87,
  362. paintImageXObjectRepeat: 88,
  363. paintImageMaskXObjectRepeat: 89,
  364. paintSolidColorImageMask: 90,
  365. constructPath: 91
  366. };
  367. exports.OPS = OPS;
  368. const PasswordResponses = {
  369. NEED_PASSWORD: 1,
  370. INCORRECT_PASSWORD: 2
  371. };
  372. exports.PasswordResponses = PasswordResponses;
  373. let verbosity = VerbosityLevel.WARNINGS;
  374. function setVerbosityLevel(level) {
  375. if (Number.isInteger(level)) {
  376. verbosity = level;
  377. }
  378. }
  379. function getVerbosityLevel() {
  380. return verbosity;
  381. }
  382. function info(msg) {
  383. if (verbosity >= VerbosityLevel.INFOS) {
  384. console.log(`Info: ${msg}`);
  385. }
  386. }
  387. function warn(msg) {
  388. if (verbosity >= VerbosityLevel.WARNINGS) {
  389. console.log(`Warning: ${msg}`);
  390. }
  391. }
  392. function unreachable(msg) {
  393. throw new Error(msg);
  394. }
  395. function assert(cond, msg) {
  396. if (!cond) {
  397. unreachable(msg);
  398. }
  399. }
  400. function _isValidProtocol(url) {
  401. if (!url) {
  402. return false;
  403. }
  404. switch (url.protocol) {
  405. case "http:":
  406. case "https:":
  407. case "ftp:":
  408. case "mailto:":
  409. case "tel:":
  410. return true;
  411. default:
  412. return false;
  413. }
  414. }
  415. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  416. if (!url) {
  417. return null;
  418. }
  419. try {
  420. if (options && typeof url === "string") {
  421. if (options.addDefaultProtocol && url.startsWith("www.")) {
  422. const dots = url.match(/\./g);
  423. if (dots && dots.length >= 2) {
  424. url = `http://${url}`;
  425. }
  426. }
  427. if (options.tryConvertEncoding) {
  428. try {
  429. url = stringToUTF8String(url);
  430. } catch (ex) {}
  431. }
  432. }
  433. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  434. if (_isValidProtocol(absoluteUrl)) {
  435. return absoluteUrl;
  436. }
  437. } catch (ex) {}
  438. return null;
  439. }
  440. function shadow(obj, prop, value, nonSerializable = false) {
  441. Object.defineProperty(obj, prop, {
  442. value,
  443. enumerable: !nonSerializable,
  444. configurable: true,
  445. writable: false
  446. });
  447. return value;
  448. }
  449. const BaseException = function BaseExceptionClosure() {
  450. function BaseException(message, name) {
  451. if (this.constructor === BaseException) {
  452. unreachable("Cannot initialize BaseException.");
  453. }
  454. this.message = message;
  455. this.name = name;
  456. }
  457. BaseException.prototype = new Error();
  458. BaseException.constructor = BaseException;
  459. return BaseException;
  460. }();
  461. exports.BaseException = BaseException;
  462. class PasswordException extends BaseException {
  463. constructor(msg, code) {
  464. super(msg, "PasswordException");
  465. this.code = code;
  466. }
  467. }
  468. exports.PasswordException = PasswordException;
  469. class UnknownErrorException extends BaseException {
  470. constructor(msg, details) {
  471. super(msg, "UnknownErrorException");
  472. this.details = details;
  473. }
  474. }
  475. exports.UnknownErrorException = UnknownErrorException;
  476. class InvalidPDFException extends BaseException {
  477. constructor(msg) {
  478. super(msg, "InvalidPDFException");
  479. }
  480. }
  481. exports.InvalidPDFException = InvalidPDFException;
  482. class MissingPDFException extends BaseException {
  483. constructor(msg) {
  484. super(msg, "MissingPDFException");
  485. }
  486. }
  487. exports.MissingPDFException = MissingPDFException;
  488. class UnexpectedResponseException extends BaseException {
  489. constructor(msg, status) {
  490. super(msg, "UnexpectedResponseException");
  491. this.status = status;
  492. }
  493. }
  494. exports.UnexpectedResponseException = UnexpectedResponseException;
  495. class FormatError extends BaseException {
  496. constructor(msg) {
  497. super(msg, "FormatError");
  498. }
  499. }
  500. exports.FormatError = FormatError;
  501. class AbortException extends BaseException {
  502. constructor(msg) {
  503. super(msg, "AbortException");
  504. }
  505. }
  506. exports.AbortException = AbortException;
  507. function bytesToString(bytes) {
  508. if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
  509. unreachable("Invalid argument for bytesToString");
  510. }
  511. const length = bytes.length;
  512. const MAX_ARGUMENT_COUNT = 8192;
  513. if (length < MAX_ARGUMENT_COUNT) {
  514. return String.fromCharCode.apply(null, bytes);
  515. }
  516. const strBuf = [];
  517. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  518. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  519. const chunk = bytes.subarray(i, chunkEnd);
  520. strBuf.push(String.fromCharCode.apply(null, chunk));
  521. }
  522. return strBuf.join("");
  523. }
  524. function stringToBytes(str) {
  525. if (typeof str !== "string") {
  526. unreachable("Invalid argument for stringToBytes");
  527. }
  528. const length = str.length;
  529. const bytes = new Uint8Array(length);
  530. for (let i = 0; i < length; ++i) {
  531. bytes[i] = str.charCodeAt(i) & 0xff;
  532. }
  533. return bytes;
  534. }
  535. function string32(value) {
  536. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  537. }
  538. function objectSize(obj) {
  539. return Object.keys(obj).length;
  540. }
  541. function objectFromMap(map) {
  542. const obj = Object.create(null);
  543. for (const [key, value] of map) {
  544. obj[key] = value;
  545. }
  546. return obj;
  547. }
  548. function isLittleEndian() {
  549. const buffer8 = new Uint8Array(4);
  550. buffer8[0] = 1;
  551. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  552. return view32[0] === 1;
  553. }
  554. function isEvalSupported() {
  555. try {
  556. new Function("");
  557. return true;
  558. } catch (e) {
  559. return false;
  560. }
  561. }
  562. class FeatureTest {
  563. static get isLittleEndian() {
  564. return shadow(this, "isLittleEndian", isLittleEndian());
  565. }
  566. static get isEvalSupported() {
  567. return shadow(this, "isEvalSupported", isEvalSupported());
  568. }
  569. static get isOffscreenCanvasSupported() {
  570. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  571. }
  572. static get platform() {
  573. if (typeof navigator === "undefined") {
  574. return shadow(this, "platform", {
  575. isWin: false,
  576. isMac: false
  577. });
  578. }
  579. return shadow(this, "platform", {
  580. isWin: navigator.platform.includes("Win"),
  581. isMac: navigator.platform.includes("Mac")
  582. });
  583. }
  584. }
  585. exports.FeatureTest = FeatureTest;
  586. const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
  587. class Util {
  588. static makeHexColor(r, g, b) {
  589. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  590. }
  591. static scaleMinMax(transform, minMax) {
  592. let temp;
  593. if (transform[0]) {
  594. if (transform[0] < 0) {
  595. temp = minMax[0];
  596. minMax[0] = minMax[1];
  597. minMax[1] = temp;
  598. }
  599. minMax[0] *= transform[0];
  600. minMax[1] *= transform[0];
  601. if (transform[3] < 0) {
  602. temp = minMax[2];
  603. minMax[2] = minMax[3];
  604. minMax[3] = temp;
  605. }
  606. minMax[2] *= transform[3];
  607. minMax[3] *= transform[3];
  608. } else {
  609. temp = minMax[0];
  610. minMax[0] = minMax[2];
  611. minMax[2] = temp;
  612. temp = minMax[1];
  613. minMax[1] = minMax[3];
  614. minMax[3] = temp;
  615. if (transform[1] < 0) {
  616. temp = minMax[2];
  617. minMax[2] = minMax[3];
  618. minMax[3] = temp;
  619. }
  620. minMax[2] *= transform[1];
  621. minMax[3] *= transform[1];
  622. if (transform[2] < 0) {
  623. temp = minMax[0];
  624. minMax[0] = minMax[1];
  625. minMax[1] = temp;
  626. }
  627. minMax[0] *= transform[2];
  628. minMax[1] *= transform[2];
  629. }
  630. minMax[0] += transform[4];
  631. minMax[1] += transform[4];
  632. minMax[2] += transform[5];
  633. minMax[3] += transform[5];
  634. }
  635. static transform(m1, m2) {
  636. 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]];
  637. }
  638. static applyTransform(p, m) {
  639. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  640. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  641. return [xt, yt];
  642. }
  643. static applyInverseTransform(p, m) {
  644. const d = m[0] * m[3] - m[1] * m[2];
  645. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  646. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  647. return [xt, yt];
  648. }
  649. static getAxialAlignedBoundingBox(r, m) {
  650. const p1 = Util.applyTransform(r, m);
  651. const p2 = Util.applyTransform(r.slice(2, 4), m);
  652. const p3 = Util.applyTransform([r[0], r[3]], m);
  653. const p4 = Util.applyTransform([r[2], r[1]], m);
  654. 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])];
  655. }
  656. static inverseTransform(m) {
  657. const d = m[0] * m[3] - m[1] * m[2];
  658. 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];
  659. }
  660. static singularValueDecompose2dScale(m) {
  661. const transpose = [m[0], m[2], m[1], m[3]];
  662. const a = m[0] * transpose[0] + m[1] * transpose[2];
  663. const b = m[0] * transpose[1] + m[1] * transpose[3];
  664. const c = m[2] * transpose[0] + m[3] * transpose[2];
  665. const d = m[2] * transpose[1] + m[3] * transpose[3];
  666. const first = (a + d) / 2;
  667. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  668. const sx = first + second || 1;
  669. const sy = first - second || 1;
  670. return [Math.sqrt(sx), Math.sqrt(sy)];
  671. }
  672. static normalizeRect(rect) {
  673. const r = rect.slice(0);
  674. if (rect[0] > rect[2]) {
  675. r[0] = rect[2];
  676. r[2] = rect[0];
  677. }
  678. if (rect[1] > rect[3]) {
  679. r[1] = rect[3];
  680. r[3] = rect[1];
  681. }
  682. return r;
  683. }
  684. static intersect(rect1, rect2) {
  685. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  686. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  687. if (xLow > xHigh) {
  688. return null;
  689. }
  690. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  691. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  692. if (yLow > yHigh) {
  693. return null;
  694. }
  695. return [xLow, yLow, xHigh, yHigh];
  696. }
  697. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
  698. const tvalues = [],
  699. bounds = [[], []];
  700. let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  701. for (let i = 0; i < 2; ++i) {
  702. if (i === 0) {
  703. b = 6 * x0 - 12 * x1 + 6 * x2;
  704. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  705. c = 3 * x1 - 3 * x0;
  706. } else {
  707. b = 6 * y0 - 12 * y1 + 6 * y2;
  708. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  709. c = 3 * y1 - 3 * y0;
  710. }
  711. if (Math.abs(a) < 1e-12) {
  712. if (Math.abs(b) < 1e-12) {
  713. continue;
  714. }
  715. t = -c / b;
  716. if (0 < t && t < 1) {
  717. tvalues.push(t);
  718. }
  719. continue;
  720. }
  721. b2ac = b * b - 4 * c * a;
  722. sqrtb2ac = Math.sqrt(b2ac);
  723. if (b2ac < 0) {
  724. continue;
  725. }
  726. t1 = (-b + sqrtb2ac) / (2 * a);
  727. if (0 < t1 && t1 < 1) {
  728. tvalues.push(t1);
  729. }
  730. t2 = (-b - sqrtb2ac) / (2 * a);
  731. if (0 < t2 && t2 < 1) {
  732. tvalues.push(t2);
  733. }
  734. }
  735. let j = tvalues.length,
  736. mt;
  737. const jlen = j;
  738. while (j--) {
  739. t = tvalues[j];
  740. mt = 1 - t;
  741. bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
  742. bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
  743. }
  744. bounds[0][jlen] = x0;
  745. bounds[1][jlen] = y0;
  746. bounds[0][jlen + 1] = x3;
  747. bounds[1][jlen + 1] = y3;
  748. bounds[0].length = bounds[1].length = jlen + 2;
  749. return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  750. }
  751. }
  752. exports.Util = Util;
  753. 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];
  754. function stringToPDFString(str) {
  755. if (str[0] >= "\xEF") {
  756. let encoding;
  757. if (str[0] === "\xFE" && str[1] === "\xFF") {
  758. encoding = "utf-16be";
  759. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  760. encoding = "utf-16le";
  761. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  762. encoding = "utf-8";
  763. }
  764. if (encoding) {
  765. try {
  766. const decoder = new TextDecoder(encoding, {
  767. fatal: true
  768. });
  769. const buffer = stringToBytes(str);
  770. return decoder.decode(buffer);
  771. } catch (ex) {
  772. warn(`stringToPDFString: "${ex}".`);
  773. }
  774. }
  775. }
  776. const strBuf = [];
  777. for (let i = 0, ii = str.length; i < ii; i++) {
  778. const code = PDFStringTranslateTable[str.charCodeAt(i)];
  779. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  780. }
  781. return strBuf.join("");
  782. }
  783. function stringToUTF8String(str) {
  784. return decodeURIComponent(escape(str));
  785. }
  786. function utf8StringToString(str) {
  787. return unescape(encodeURIComponent(str));
  788. }
  789. function isArrayBuffer(v) {
  790. return typeof v === "object" && v !== null && v.byteLength !== undefined;
  791. }
  792. function isArrayEqual(arr1, arr2) {
  793. if (arr1.length !== arr2.length) {
  794. return false;
  795. }
  796. for (let i = 0, ii = arr1.length; i < ii; i++) {
  797. if (arr1[i] !== arr2[i]) {
  798. return false;
  799. }
  800. }
  801. return true;
  802. }
  803. function getModificationDate(date = new Date()) {
  804. 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")];
  805. return buffer.join("");
  806. }
  807. function createPromiseCapability() {
  808. const capability = Object.create(null);
  809. let isSettled = false;
  810. Object.defineProperty(capability, "settled", {
  811. get() {
  812. return isSettled;
  813. }
  814. });
  815. capability.promise = new Promise(function (resolve, reject) {
  816. capability.resolve = function (data) {
  817. isSettled = true;
  818. resolve(data);
  819. };
  820. capability.reject = function (reason) {
  821. isSettled = true;
  822. reject(reason);
  823. };
  824. });
  825. return capability;
  826. }
  827. /***/ }),
  828. /* 2 */
  829. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  830. Object.defineProperty(exports, "__esModule", ({
  831. value: true
  832. }));
  833. exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultFilterFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
  834. exports.getDocument = getDocument;
  835. exports.version = void 0;
  836. var _util = __w_pdfjs_require__(1);
  837. var _annotation_storage = __w_pdfjs_require__(3);
  838. var _display_utils = __w_pdfjs_require__(6);
  839. var _font_loader = __w_pdfjs_require__(9);
  840. var _canvas = __w_pdfjs_require__(11);
  841. var _worker_options = __w_pdfjs_require__(14);
  842. var _is_node = __w_pdfjs_require__(10);
  843. var _message_handler = __w_pdfjs_require__(15);
  844. var _metadata = __w_pdfjs_require__(16);
  845. var _optional_content_config = __w_pdfjs_require__(17);
  846. var _transport_stream = __w_pdfjs_require__(18);
  847. var _xfa_text = __w_pdfjs_require__(19);
  848. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  849. const RENDERING_CANCELLED_TIMEOUT = 100;
  850. const DELAYED_CLEANUP_TIMEOUT = 5000;
  851. let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
  852. exports.DefaultCanvasFactory = DefaultCanvasFactory;
  853. let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
  854. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
  855. let DefaultFilterFactory = _display_utils.DOMFilterFactory;
  856. exports.DefaultFilterFactory = DefaultFilterFactory;
  857. let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
  858. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
  859. if (_is_node.isNodeJS) {
  860. const {
  861. NodeCanvasFactory,
  862. NodeCMapReaderFactory,
  863. NodeFilterFactory,
  864. NodeStandardFontDataFactory
  865. } = __w_pdfjs_require__(20);
  866. exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  867. exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  868. exports.DefaultFilterFactory = DefaultFilterFactory = NodeFilterFactory;
  869. exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
  870. }
  871. let createPDFNetworkStream;
  872. {
  873. if (_is_node.isNodeJS) {
  874. const {
  875. PDFNodeStream
  876. } = __w_pdfjs_require__(21);
  877. createPDFNetworkStream = params => {
  878. return new PDFNodeStream(params);
  879. };
  880. } else {
  881. const {
  882. PDFNetworkStream
  883. } = __w_pdfjs_require__(24);
  884. const {
  885. PDFFetchStream
  886. } = __w_pdfjs_require__(25);
  887. createPDFNetworkStream = params => {
  888. return (0, _display_utils.isValidFetchUrl)(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params);
  889. };
  890. }
  891. }
  892. function getDocument(src) {
  893. if (typeof src === "string" || src instanceof URL) {
  894. src = {
  895. url: src
  896. };
  897. } else if ((0, _util.isArrayBuffer)(src)) {
  898. src = {
  899. data: src
  900. };
  901. }
  902. if (typeof src !== "object") {
  903. throw new Error("Invalid parameter in getDocument, need parameter object.");
  904. }
  905. if (!src.url && !src.data && !src.range) {
  906. throw new Error("Invalid parameter object: need either .data, .range or .url");
  907. }
  908. const task = new PDFDocumentLoadingTask();
  909. const {
  910. docId
  911. } = task;
  912. const url = src.url ? getUrlProp(src.url) : null;
  913. const data = src.data ? getDataProp(src.data) : null;
  914. const httpHeaders = src.httpHeaders || null;
  915. const withCredentials = src.withCredentials === true;
  916. const password = src.password ?? null;
  917. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  918. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  919. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  920. const verbosity = src.verbosity;
  921. const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null;
  922. const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  923. const cMapPacked = src.cMapPacked !== false;
  924. const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  925. const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  926. const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  927. const ignoreErrors = src.stopAtErrors !== true;
  928. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  929. const isEvalSupported = src.isEvalSupported !== false;
  930. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_is_node.isNodeJS;
  931. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  932. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _is_node.isNodeJS;
  933. const fontExtraProperties = src.fontExtraProperties === true;
  934. const enableXfa = src.enableXfa === true;
  935. const ownerDocument = src.ownerDocument || globalThis.document;
  936. const disableRange = src.disableRange === true;
  937. const disableStream = src.disableStream === true;
  938. const disableAutoFetch = src.disableAutoFetch === true;
  939. const pdfBug = src.pdfBug === true;
  940. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  941. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_is_node.isNodeJS && !disableFontFace;
  942. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI);
  943. const canvasFactory = src.canvasFactory || new DefaultCanvasFactory({
  944. ownerDocument
  945. });
  946. const filterFactory = src.filterFactory || new DefaultFilterFactory({
  947. docId,
  948. ownerDocument
  949. });
  950. const styleElement = null;
  951. (0, _util.setVerbosityLevel)(verbosity);
  952. const transportFactory = {
  953. canvasFactory,
  954. filterFactory
  955. };
  956. if (!useWorkerFetch) {
  957. transportFactory.cMapReaderFactory = new CMapReaderFactory({
  958. baseUrl: cMapUrl,
  959. isCompressed: cMapPacked
  960. });
  961. transportFactory.standardFontDataFactory = new StandardFontDataFactory({
  962. baseUrl: standardFontDataUrl
  963. });
  964. }
  965. if (!worker) {
  966. const workerParams = {
  967. verbosity,
  968. port: _worker_options.GlobalWorkerOptions.workerPort
  969. };
  970. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  971. task._worker = worker;
  972. }
  973. const fetchDocParams = {
  974. docId,
  975. apiVersion: '3.5.141',
  976. data,
  977. password,
  978. disableAutoFetch,
  979. rangeChunkSize,
  980. length,
  981. docBaseUrl,
  982. enableXfa,
  983. evaluatorOptions: {
  984. maxImageSize,
  985. disableFontFace,
  986. ignoreErrors,
  987. isEvalSupported,
  988. isOffscreenCanvasSupported,
  989. canvasMaxAreaInBytes,
  990. fontExtraProperties,
  991. useSystemFonts,
  992. cMapUrl: useWorkerFetch ? cMapUrl : null,
  993. standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
  994. }
  995. };
  996. const transportParams = {
  997. ignoreErrors,
  998. isEvalSupported,
  999. disableFontFace,
  1000. fontExtraProperties,
  1001. enableXfa,
  1002. ownerDocument,
  1003. disableAutoFetch,
  1004. pdfBug,
  1005. styleElement
  1006. };
  1007. worker.promise.then(function () {
  1008. if (task.destroyed) {
  1009. throw new Error("Loading aborted");
  1010. }
  1011. const workerIdPromise = _fetchDocument(worker, fetchDocParams);
  1012. const networkStreamPromise = new Promise(function (resolve) {
  1013. let networkStream;
  1014. if (rangeTransport) {
  1015. networkStream = new _transport_stream.PDFDataTransportStream({
  1016. length,
  1017. initialData: rangeTransport.initialData,
  1018. progressiveDone: rangeTransport.progressiveDone,
  1019. contentDispositionFilename: rangeTransport.contentDispositionFilename,
  1020. disableRange,
  1021. disableStream
  1022. }, rangeTransport);
  1023. } else if (!data) {
  1024. networkStream = createPDFNetworkStream({
  1025. url,
  1026. length,
  1027. httpHeaders,
  1028. withCredentials,
  1029. rangeChunkSize,
  1030. disableRange,
  1031. disableStream
  1032. });
  1033. }
  1034. resolve(networkStream);
  1035. });
  1036. return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
  1037. if (task.destroyed) {
  1038. throw new Error("Loading aborted");
  1039. }
  1040. const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
  1041. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  1042. task._transport = transport;
  1043. messageHandler.send("Ready", null);
  1044. });
  1045. }).catch(task._capability.reject);
  1046. return task;
  1047. }
  1048. async function _fetchDocument(worker, source) {
  1049. if (worker.destroyed) {
  1050. throw new Error("Worker was destroyed");
  1051. }
  1052. const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null);
  1053. if (worker.destroyed) {
  1054. throw new Error("Worker was destroyed");
  1055. }
  1056. return workerId;
  1057. }
  1058. function getUrlProp(val) {
  1059. if (val instanceof URL) {
  1060. return val.href;
  1061. }
  1062. try {
  1063. return new URL(val, window.location).href;
  1064. } catch (ex) {
  1065. if (_is_node.isNodeJS && typeof val === "string") {
  1066. return val;
  1067. }
  1068. }
  1069. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  1070. }
  1071. function getDataProp(val) {
  1072. if (_is_node.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  1073. (0, _display_utils.deprecated)("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  1074. return new Uint8Array(val);
  1075. }
  1076. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  1077. return val;
  1078. }
  1079. if (typeof val === "string") {
  1080. return (0, _util.stringToBytes)(val);
  1081. }
  1082. if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) {
  1083. return new Uint8Array(val);
  1084. }
  1085. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  1086. }
  1087. class PDFDocumentLoadingTask {
  1088. static #docId = 0;
  1089. constructor() {
  1090. this._capability = (0, _util.createPromiseCapability)();
  1091. this._transport = null;
  1092. this._worker = null;
  1093. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  1094. this.destroyed = false;
  1095. this.onPassword = null;
  1096. this.onProgress = null;
  1097. }
  1098. get promise() {
  1099. return this._capability.promise;
  1100. }
  1101. async destroy() {
  1102. this.destroyed = true;
  1103. await this._transport?.destroy();
  1104. this._transport = null;
  1105. if (this._worker) {
  1106. this._worker.destroy();
  1107. this._worker = null;
  1108. }
  1109. }
  1110. }
  1111. exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
  1112. class PDFDataRangeTransport {
  1113. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  1114. this.length = length;
  1115. this.initialData = initialData;
  1116. this.progressiveDone = progressiveDone;
  1117. this.contentDispositionFilename = contentDispositionFilename;
  1118. this._rangeListeners = [];
  1119. this._progressListeners = [];
  1120. this._progressiveReadListeners = [];
  1121. this._progressiveDoneListeners = [];
  1122. this._readyCapability = (0, _util.createPromiseCapability)();
  1123. }
  1124. addRangeListener(listener) {
  1125. this._rangeListeners.push(listener);
  1126. }
  1127. addProgressListener(listener) {
  1128. this._progressListeners.push(listener);
  1129. }
  1130. addProgressiveReadListener(listener) {
  1131. this._progressiveReadListeners.push(listener);
  1132. }
  1133. addProgressiveDoneListener(listener) {
  1134. this._progressiveDoneListeners.push(listener);
  1135. }
  1136. onDataRange(begin, chunk) {
  1137. for (const listener of this._rangeListeners) {
  1138. listener(begin, chunk);
  1139. }
  1140. }
  1141. onDataProgress(loaded, total) {
  1142. this._readyCapability.promise.then(() => {
  1143. for (const listener of this._progressListeners) {
  1144. listener(loaded, total);
  1145. }
  1146. });
  1147. }
  1148. onDataProgressiveRead(chunk) {
  1149. this._readyCapability.promise.then(() => {
  1150. for (const listener of this._progressiveReadListeners) {
  1151. listener(chunk);
  1152. }
  1153. });
  1154. }
  1155. onDataProgressiveDone() {
  1156. this._readyCapability.promise.then(() => {
  1157. for (const listener of this._progressiveDoneListeners) {
  1158. listener();
  1159. }
  1160. });
  1161. }
  1162. transportReady() {
  1163. this._readyCapability.resolve();
  1164. }
  1165. requestDataRange(begin, end) {
  1166. (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  1167. }
  1168. abort() {}
  1169. }
  1170. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  1171. class PDFDocumentProxy {
  1172. constructor(pdfInfo, transport) {
  1173. this._pdfInfo = pdfInfo;
  1174. this._transport = transport;
  1175. }
  1176. get annotationStorage() {
  1177. return this._transport.annotationStorage;
  1178. }
  1179. get filterFactory() {
  1180. return this._transport.filterFactory;
  1181. }
  1182. get numPages() {
  1183. return this._pdfInfo.numPages;
  1184. }
  1185. get fingerprints() {
  1186. return this._pdfInfo.fingerprints;
  1187. }
  1188. get isPureXfa() {
  1189. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1190. }
  1191. get allXfaHtml() {
  1192. return this._transport._htmlForXfa;
  1193. }
  1194. getPage(pageNumber) {
  1195. return this._transport.getPage(pageNumber);
  1196. }
  1197. getPageIndex(ref) {
  1198. return this._transport.getPageIndex(ref);
  1199. }
  1200. getDestinations() {
  1201. return this._transport.getDestinations();
  1202. }
  1203. getDestination(id) {
  1204. return this._transport.getDestination(id);
  1205. }
  1206. getPageLabels() {
  1207. return this._transport.getPageLabels();
  1208. }
  1209. getPageLayout() {
  1210. return this._transport.getPageLayout();
  1211. }
  1212. getPageMode() {
  1213. return this._transport.getPageMode();
  1214. }
  1215. getViewerPreferences() {
  1216. return this._transport.getViewerPreferences();
  1217. }
  1218. getOpenAction() {
  1219. return this._transport.getOpenAction();
  1220. }
  1221. getAttachments() {
  1222. return this._transport.getAttachments();
  1223. }
  1224. getJavaScript() {
  1225. return this._transport.getJavaScript();
  1226. }
  1227. getJSActions() {
  1228. return this._transport.getDocJSActions();
  1229. }
  1230. getOutline() {
  1231. return this._transport.getOutline();
  1232. }
  1233. getOptionalContentConfig() {
  1234. return this._transport.getOptionalContentConfig();
  1235. }
  1236. getPermissions() {
  1237. return this._transport.getPermissions();
  1238. }
  1239. getMetadata() {
  1240. return this._transport.getMetadata();
  1241. }
  1242. getMarkInfo() {
  1243. return this._transport.getMarkInfo();
  1244. }
  1245. getData() {
  1246. return this._transport.getData();
  1247. }
  1248. saveDocument() {
  1249. return this._transport.saveDocument();
  1250. }
  1251. getDownloadInfo() {
  1252. return this._transport.downloadInfoCapability.promise;
  1253. }
  1254. cleanup(keepLoadedFonts = false) {
  1255. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  1256. }
  1257. destroy() {
  1258. return this.loadingTask.destroy();
  1259. }
  1260. get loadingParams() {
  1261. return this._transport.loadingParams;
  1262. }
  1263. get loadingTask() {
  1264. return this._transport.loadingTask;
  1265. }
  1266. getFieldObjects() {
  1267. return this._transport.getFieldObjects();
  1268. }
  1269. hasJSActions() {
  1270. return this._transport.hasJSActions();
  1271. }
  1272. getCalculationOrderIds() {
  1273. return this._transport.getCalculationOrderIds();
  1274. }
  1275. }
  1276. exports.PDFDocumentProxy = PDFDocumentProxy;
  1277. class PDFPageProxy {
  1278. #delayedCleanupTimeout = null;
  1279. #pendingCleanup = false;
  1280. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  1281. this._pageIndex = pageIndex;
  1282. this._pageInfo = pageInfo;
  1283. this._transport = transport;
  1284. this._stats = pdfBug ? new _display_utils.StatTimer() : null;
  1285. this._pdfBug = pdfBug;
  1286. this.commonObjs = transport.commonObjs;
  1287. this.objs = new PDFObjects();
  1288. this._maybeCleanupAfterRender = false;
  1289. this._intentStates = new Map();
  1290. this.destroyed = false;
  1291. }
  1292. get pageNumber() {
  1293. return this._pageIndex + 1;
  1294. }
  1295. get rotate() {
  1296. return this._pageInfo.rotate;
  1297. }
  1298. get ref() {
  1299. return this._pageInfo.ref;
  1300. }
  1301. get userUnit() {
  1302. return this._pageInfo.userUnit;
  1303. }
  1304. get view() {
  1305. return this._pageInfo.view;
  1306. }
  1307. getViewport({
  1308. scale,
  1309. rotation = this.rotate,
  1310. offsetX = 0,
  1311. offsetY = 0,
  1312. dontFlip = false
  1313. } = {}) {
  1314. return new _display_utils.PageViewport({
  1315. viewBox: this.view,
  1316. scale,
  1317. rotation,
  1318. offsetX,
  1319. offsetY,
  1320. dontFlip
  1321. });
  1322. }
  1323. getAnnotations({
  1324. intent = "display"
  1325. } = {}) {
  1326. const intentArgs = this._transport.getRenderingIntent(intent);
  1327. return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  1328. }
  1329. getJSActions() {
  1330. return this._transport.getPageJSActions(this._pageIndex);
  1331. }
  1332. get isPureXfa() {
  1333. return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  1334. }
  1335. async getXfa() {
  1336. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  1337. }
  1338. render({
  1339. canvasContext,
  1340. viewport,
  1341. intent = "display",
  1342. annotationMode = _util.AnnotationMode.ENABLE,
  1343. transform = null,
  1344. background = null,
  1345. optionalContentConfigPromise = null,
  1346. annotationCanvasMap = null,
  1347. pageColors = null,
  1348. printAnnotationStorage = null
  1349. }) {
  1350. if (arguments[0]?.canvasFactory) {
  1351. throw new Error("render no longer accepts the `canvasFactory`-option, " + "please pass it to the `getDocument`-function instead.");
  1352. }
  1353. this._stats?.time("Overall");
  1354. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
  1355. this.#pendingCleanup = false;
  1356. this.#abortDelayedCleanup();
  1357. if (!optionalContentConfigPromise) {
  1358. optionalContentConfigPromise = this._transport.getOptionalContentConfig();
  1359. }
  1360. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1361. if (!intentState) {
  1362. intentState = Object.create(null);
  1363. this._intentStates.set(intentArgs.cacheKey, intentState);
  1364. }
  1365. if (intentState.streamReaderCancelTimeout) {
  1366. clearTimeout(intentState.streamReaderCancelTimeout);
  1367. intentState.streamReaderCancelTimeout = null;
  1368. }
  1369. const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
  1370. if (!intentState.displayReadyCapability) {
  1371. intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
  1372. intentState.operatorList = {
  1373. fnArray: [],
  1374. argsArray: [],
  1375. lastChunk: false,
  1376. separateAnnots: null
  1377. };
  1378. this._stats?.time("Page Request");
  1379. this._pumpOperatorList(intentArgs);
  1380. }
  1381. const complete = error => {
  1382. intentState.renderTasks.delete(internalRenderTask);
  1383. if (this._maybeCleanupAfterRender || intentPrint) {
  1384. this.#pendingCleanup = true;
  1385. }
  1386. this.#tryCleanup(!intentPrint);
  1387. if (error) {
  1388. internalRenderTask.capability.reject(error);
  1389. this._abortOperatorList({
  1390. intentState,
  1391. reason: error instanceof Error ? error : new Error(error)
  1392. });
  1393. } else {
  1394. internalRenderTask.capability.resolve();
  1395. }
  1396. this._stats?.timeEnd("Rendering");
  1397. this._stats?.timeEnd("Overall");
  1398. };
  1399. const internalRenderTask = new InternalRenderTask({
  1400. callback: complete,
  1401. params: {
  1402. canvasContext,
  1403. viewport,
  1404. transform,
  1405. background
  1406. },
  1407. objs: this.objs,
  1408. commonObjs: this.commonObjs,
  1409. annotationCanvasMap,
  1410. operatorList: intentState.operatorList,
  1411. pageIndex: this._pageIndex,
  1412. canvasFactory: this._transport.canvasFactory,
  1413. filterFactory: this._transport.filterFactory,
  1414. useRequestAnimationFrame: !intentPrint,
  1415. pdfBug: this._pdfBug,
  1416. pageColors
  1417. });
  1418. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  1419. const renderTask = internalRenderTask.task;
  1420. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  1421. if (this.#pendingCleanup) {
  1422. complete();
  1423. return;
  1424. }
  1425. this._stats?.time("Rendering");
  1426. internalRenderTask.initializeGraphics({
  1427. transparency,
  1428. optionalContentConfig
  1429. });
  1430. internalRenderTask.operatorListChanged();
  1431. }).catch(complete);
  1432. return renderTask;
  1433. }
  1434. getOperatorList({
  1435. intent = "display",
  1436. annotationMode = _util.AnnotationMode.ENABLE,
  1437. printAnnotationStorage = null
  1438. } = {}) {
  1439. function operatorListChanged() {
  1440. if (intentState.operatorList.lastChunk) {
  1441. intentState.opListReadCapability.resolve(intentState.operatorList);
  1442. intentState.renderTasks.delete(opListTask);
  1443. }
  1444. }
  1445. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
  1446. let intentState = this._intentStates.get(intentArgs.cacheKey);
  1447. if (!intentState) {
  1448. intentState = Object.create(null);
  1449. this._intentStates.set(intentArgs.cacheKey, intentState);
  1450. }
  1451. let opListTask;
  1452. if (!intentState.opListReadCapability) {
  1453. opListTask = Object.create(null);
  1454. opListTask.operatorListChanged = operatorListChanged;
  1455. intentState.opListReadCapability = (0, _util.createPromiseCapability)();
  1456. (intentState.renderTasks ||= new Set()).add(opListTask);
  1457. intentState.operatorList = {
  1458. fnArray: [],
  1459. argsArray: [],
  1460. lastChunk: false,
  1461. separateAnnots: null
  1462. };
  1463. this._stats?.time("Page Request");
  1464. this._pumpOperatorList(intentArgs);
  1465. }
  1466. return intentState.opListReadCapability.promise;
  1467. }
  1468. streamTextContent({
  1469. includeMarkedContent = false
  1470. } = {}) {
  1471. const TEXT_CONTENT_CHUNK_SIZE = 100;
  1472. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  1473. pageIndex: this._pageIndex,
  1474. includeMarkedContent: includeMarkedContent === true
  1475. }, {
  1476. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  1477. size(textContent) {
  1478. return textContent.items.length;
  1479. }
  1480. });
  1481. }
  1482. getTextContent(params = {}) {
  1483. if (this._transport._htmlForXfa) {
  1484. return this.getXfa().then(xfa => {
  1485. return _xfa_text.XfaText.textContent(xfa);
  1486. });
  1487. }
  1488. const readableStream = this.streamTextContent(params);
  1489. return new Promise(function (resolve, reject) {
  1490. function pump() {
  1491. reader.read().then(function ({
  1492. value,
  1493. done
  1494. }) {
  1495. if (done) {
  1496. resolve(textContent);
  1497. return;
  1498. }
  1499. Object.assign(textContent.styles, value.styles);
  1500. textContent.items.push(...value.items);
  1501. pump();
  1502. }, reject);
  1503. }
  1504. const reader = readableStream.getReader();
  1505. const textContent = {
  1506. items: [],
  1507. styles: Object.create(null)
  1508. };
  1509. pump();
  1510. });
  1511. }
  1512. getStructTree() {
  1513. return this._transport.getStructTree(this._pageIndex);
  1514. }
  1515. _destroy() {
  1516. this.destroyed = true;
  1517. const waitOn = [];
  1518. for (const intentState of this._intentStates.values()) {
  1519. this._abortOperatorList({
  1520. intentState,
  1521. reason: new Error("Page was destroyed."),
  1522. force: true
  1523. });
  1524. if (intentState.opListReadCapability) {
  1525. continue;
  1526. }
  1527. for (const internalRenderTask of intentState.renderTasks) {
  1528. waitOn.push(internalRenderTask.completed);
  1529. internalRenderTask.cancel();
  1530. }
  1531. }
  1532. this.objs.clear();
  1533. this.#pendingCleanup = false;
  1534. this.#abortDelayedCleanup();
  1535. return Promise.all(waitOn);
  1536. }
  1537. cleanup(resetStats = false) {
  1538. this.#pendingCleanup = true;
  1539. const success = this.#tryCleanup(false);
  1540. if (resetStats && success) {
  1541. this._stats &&= new _display_utils.StatTimer();
  1542. }
  1543. return success;
  1544. }
  1545. #tryCleanup(delayed = false) {
  1546. this.#abortDelayedCleanup();
  1547. if (!this.#pendingCleanup) {
  1548. return false;
  1549. }
  1550. if (delayed) {
  1551. this.#delayedCleanupTimeout = setTimeout(() => {
  1552. this.#delayedCleanupTimeout = null;
  1553. this.#tryCleanup(false);
  1554. }, DELAYED_CLEANUP_TIMEOUT);
  1555. return false;
  1556. }
  1557. for (const {
  1558. renderTasks,
  1559. operatorList
  1560. } of this._intentStates.values()) {
  1561. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  1562. return false;
  1563. }
  1564. }
  1565. this._intentStates.clear();
  1566. this.objs.clear();
  1567. this.#pendingCleanup = false;
  1568. return true;
  1569. }
  1570. #abortDelayedCleanup() {
  1571. if (this.#delayedCleanupTimeout) {
  1572. clearTimeout(this.#delayedCleanupTimeout);
  1573. this.#delayedCleanupTimeout = null;
  1574. }
  1575. }
  1576. _startRenderPage(transparency, cacheKey) {
  1577. const intentState = this._intentStates.get(cacheKey);
  1578. if (!intentState) {
  1579. return;
  1580. }
  1581. this._stats?.timeEnd("Page Request");
  1582. intentState.displayReadyCapability?.resolve(transparency);
  1583. }
  1584. _renderPageChunk(operatorListChunk, intentState) {
  1585. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  1586. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  1587. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  1588. }
  1589. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  1590. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  1591. for (const internalRenderTask of intentState.renderTasks) {
  1592. internalRenderTask.operatorListChanged();
  1593. }
  1594. if (operatorListChunk.lastChunk) {
  1595. this.#tryCleanup(true);
  1596. }
  1597. }
  1598. _pumpOperatorList({
  1599. renderingIntent,
  1600. cacheKey,
  1601. annotationStorageMap
  1602. }) {
  1603. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  1604. pageIndex: this._pageIndex,
  1605. intent: renderingIntent,
  1606. cacheKey,
  1607. annotationStorage: annotationStorageMap
  1608. });
  1609. const reader = readableStream.getReader();
  1610. const intentState = this._intentStates.get(cacheKey);
  1611. intentState.streamReader = reader;
  1612. const pump = () => {
  1613. reader.read().then(({
  1614. value,
  1615. done
  1616. }) => {
  1617. if (done) {
  1618. intentState.streamReader = null;
  1619. return;
  1620. }
  1621. if (this._transport.destroyed) {
  1622. return;
  1623. }
  1624. this._renderPageChunk(value, intentState);
  1625. pump();
  1626. }, reason => {
  1627. intentState.streamReader = null;
  1628. if (this._transport.destroyed) {
  1629. return;
  1630. }
  1631. if (intentState.operatorList) {
  1632. intentState.operatorList.lastChunk = true;
  1633. for (const internalRenderTask of intentState.renderTasks) {
  1634. internalRenderTask.operatorListChanged();
  1635. }
  1636. this.#tryCleanup(true);
  1637. }
  1638. if (intentState.displayReadyCapability) {
  1639. intentState.displayReadyCapability.reject(reason);
  1640. } else if (intentState.opListReadCapability) {
  1641. intentState.opListReadCapability.reject(reason);
  1642. } else {
  1643. throw reason;
  1644. }
  1645. });
  1646. };
  1647. pump();
  1648. }
  1649. _abortOperatorList({
  1650. intentState,
  1651. reason,
  1652. force = false
  1653. }) {
  1654. if (!intentState.streamReader) {
  1655. return;
  1656. }
  1657. if (intentState.streamReaderCancelTimeout) {
  1658. clearTimeout(intentState.streamReaderCancelTimeout);
  1659. intentState.streamReaderCancelTimeout = null;
  1660. }
  1661. if (!force) {
  1662. if (intentState.renderTasks.size > 0) {
  1663. return;
  1664. }
  1665. if (reason instanceof _display_utils.RenderingCancelledException) {
  1666. let delay = RENDERING_CANCELLED_TIMEOUT;
  1667. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  1668. delay += reason.extraDelay;
  1669. }
  1670. intentState.streamReaderCancelTimeout = setTimeout(() => {
  1671. intentState.streamReaderCancelTimeout = null;
  1672. this._abortOperatorList({
  1673. intentState,
  1674. reason,
  1675. force: true
  1676. });
  1677. }, delay);
  1678. return;
  1679. }
  1680. }
  1681. intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
  1682. intentState.streamReader = null;
  1683. if (this._transport.destroyed) {
  1684. return;
  1685. }
  1686. for (const [curCacheKey, curIntentState] of this._intentStates) {
  1687. if (curIntentState === intentState) {
  1688. this._intentStates.delete(curCacheKey);
  1689. break;
  1690. }
  1691. }
  1692. this.cleanup();
  1693. }
  1694. get stats() {
  1695. return this._stats;
  1696. }
  1697. }
  1698. exports.PDFPageProxy = PDFPageProxy;
  1699. class LoopbackPort {
  1700. #listeners = new Set();
  1701. #deferred = Promise.resolve();
  1702. postMessage(obj, transfer) {
  1703. const event = {
  1704. data: structuredClone(obj, transfer ? {
  1705. transfer
  1706. } : null)
  1707. };
  1708. this.#deferred.then(() => {
  1709. for (const listener of this.#listeners) {
  1710. listener.call(this, event);
  1711. }
  1712. });
  1713. }
  1714. addEventListener(name, listener) {
  1715. this.#listeners.add(listener);
  1716. }
  1717. removeEventListener(name, listener) {
  1718. this.#listeners.delete(listener);
  1719. }
  1720. terminate() {
  1721. this.#listeners.clear();
  1722. }
  1723. }
  1724. exports.LoopbackPort = LoopbackPort;
  1725. const PDFWorkerUtil = {
  1726. isWorkerDisabled: false,
  1727. fallbackWorkerSrc: null,
  1728. fakeWorkerId: 0
  1729. };
  1730. exports.PDFWorkerUtil = PDFWorkerUtil;
  1731. {
  1732. if (_is_node.isNodeJS && typeof require === "function") {
  1733. PDFWorkerUtil.isWorkerDisabled = true;
  1734. PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  1735. } else if (typeof document === "object") {
  1736. const pdfjsFilePath = document?.currentScript?.src;
  1737. if (pdfjsFilePath) {
  1738. PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
  1739. }
  1740. }
  1741. PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
  1742. let base;
  1743. try {
  1744. base = new URL(baseUrl);
  1745. if (!base.origin || base.origin === "null") {
  1746. return false;
  1747. }
  1748. } catch (e) {
  1749. return false;
  1750. }
  1751. const other = new URL(otherUrl, base);
  1752. return base.origin === other.origin;
  1753. };
  1754. PDFWorkerUtil.createCDNWrapper = function (url) {
  1755. const wrapper = `importScripts("${url}");`;
  1756. return URL.createObjectURL(new Blob([wrapper]));
  1757. };
  1758. }
  1759. class PDFWorker {
  1760. static #workerPorts = new WeakMap();
  1761. constructor({
  1762. name = null,
  1763. port = null,
  1764. verbosity = (0, _util.getVerbosityLevel)()
  1765. } = {}) {
  1766. if (port && PDFWorker.#workerPorts.has(port)) {
  1767. throw new Error("Cannot use more than one PDFWorker per port.");
  1768. }
  1769. this.name = name;
  1770. this.destroyed = false;
  1771. this.verbosity = verbosity;
  1772. this._readyCapability = (0, _util.createPromiseCapability)();
  1773. this._port = null;
  1774. this._webWorker = null;
  1775. this._messageHandler = null;
  1776. if (port) {
  1777. PDFWorker.#workerPorts.set(port, this);
  1778. this._initializeFromPort(port);
  1779. return;
  1780. }
  1781. this._initialize();
  1782. }
  1783. get promise() {
  1784. return this._readyCapability.promise;
  1785. }
  1786. get port() {
  1787. return this._port;
  1788. }
  1789. get messageHandler() {
  1790. return this._messageHandler;
  1791. }
  1792. _initializeFromPort(port) {
  1793. this._port = port;
  1794. this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
  1795. this._messageHandler.on("ready", function () {});
  1796. this._readyCapability.resolve();
  1797. this._messageHandler.send("configure", {
  1798. verbosity: this.verbosity
  1799. });
  1800. }
  1801. _initialize() {
  1802. if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
  1803. let {
  1804. workerSrc
  1805. } = PDFWorker;
  1806. try {
  1807. if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
  1808. workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
  1809. }
  1810. const worker = new Worker(workerSrc);
  1811. const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
  1812. const terminateEarly = () => {
  1813. worker.removeEventListener("error", onWorkerError);
  1814. messageHandler.destroy();
  1815. worker.terminate();
  1816. if (this.destroyed) {
  1817. this._readyCapability.reject(new Error("Worker was destroyed"));
  1818. } else {
  1819. this._setupFakeWorker();
  1820. }
  1821. };
  1822. const onWorkerError = () => {
  1823. if (!this._webWorker) {
  1824. terminateEarly();
  1825. }
  1826. };
  1827. worker.addEventListener("error", onWorkerError);
  1828. messageHandler.on("test", data => {
  1829. worker.removeEventListener("error", onWorkerError);
  1830. if (this.destroyed) {
  1831. terminateEarly();
  1832. return;
  1833. }
  1834. if (data) {
  1835. this._messageHandler = messageHandler;
  1836. this._port = worker;
  1837. this._webWorker = worker;
  1838. this._readyCapability.resolve();
  1839. messageHandler.send("configure", {
  1840. verbosity: this.verbosity
  1841. });
  1842. } else {
  1843. this._setupFakeWorker();
  1844. messageHandler.destroy();
  1845. worker.terminate();
  1846. }
  1847. });
  1848. messageHandler.on("ready", data => {
  1849. worker.removeEventListener("error", onWorkerError);
  1850. if (this.destroyed) {
  1851. terminateEarly();
  1852. return;
  1853. }
  1854. try {
  1855. sendTest();
  1856. } catch (e) {
  1857. this._setupFakeWorker();
  1858. }
  1859. });
  1860. const sendTest = () => {
  1861. const testObj = new Uint8Array();
  1862. messageHandler.send("test", testObj, [testObj.buffer]);
  1863. };
  1864. sendTest();
  1865. return;
  1866. } catch (e) {
  1867. (0, _util.info)("The worker has been disabled.");
  1868. }
  1869. }
  1870. this._setupFakeWorker();
  1871. }
  1872. _setupFakeWorker() {
  1873. if (!PDFWorkerUtil.isWorkerDisabled) {
  1874. (0, _util.warn)("Setting up fake worker.");
  1875. PDFWorkerUtil.isWorkerDisabled = true;
  1876. }
  1877. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  1878. if (this.destroyed) {
  1879. this._readyCapability.reject(new Error("Worker was destroyed"));
  1880. return;
  1881. }
  1882. const port = new LoopbackPort();
  1883. this._port = port;
  1884. const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
  1885. const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
  1886. WorkerMessageHandler.setup(workerHandler, port);
  1887. const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
  1888. this._messageHandler = messageHandler;
  1889. this._readyCapability.resolve();
  1890. messageHandler.send("configure", {
  1891. verbosity: this.verbosity
  1892. });
  1893. }).catch(reason => {
  1894. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  1895. });
  1896. }
  1897. destroy() {
  1898. this.destroyed = true;
  1899. if (this._webWorker) {
  1900. this._webWorker.terminate();
  1901. this._webWorker = null;
  1902. }
  1903. PDFWorker.#workerPorts.delete(this._port);
  1904. this._port = null;
  1905. if (this._messageHandler) {
  1906. this._messageHandler.destroy();
  1907. this._messageHandler = null;
  1908. }
  1909. }
  1910. static fromPort(params) {
  1911. if (!params?.port) {
  1912. throw new Error("PDFWorker.fromPort - invalid method signature.");
  1913. }
  1914. if (this.#workerPorts.has(params.port)) {
  1915. return this.#workerPorts.get(params.port);
  1916. }
  1917. return new PDFWorker(params);
  1918. }
  1919. static get workerSrc() {
  1920. if (_worker_options.GlobalWorkerOptions.workerSrc) {
  1921. return _worker_options.GlobalWorkerOptions.workerSrc;
  1922. }
  1923. if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
  1924. if (!_is_node.isNodeJS) {
  1925. (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
  1926. }
  1927. return PDFWorkerUtil.fallbackWorkerSrc;
  1928. }
  1929. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  1930. }
  1931. static get _mainThreadWorkerMessageHandler() {
  1932. try {
  1933. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  1934. } catch (ex) {
  1935. return null;
  1936. }
  1937. }
  1938. static get _setupFakeWorkerGlobal() {
  1939. const loader = async () => {
  1940. const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
  1941. if (mainWorkerMessageHandler) {
  1942. return mainWorkerMessageHandler;
  1943. }
  1944. if (_is_node.isNodeJS && typeof require === "function") {
  1945. const worker = eval("require")(this.workerSrc);
  1946. return worker.WorkerMessageHandler;
  1947. }
  1948. await (0, _display_utils.loadScript)(this.workerSrc);
  1949. return window.pdfjsWorker.WorkerMessageHandler;
  1950. };
  1951. return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  1952. }
  1953. }
  1954. exports.PDFWorker = PDFWorker;
  1955. class WorkerTransport {
  1956. #methodPromises = new Map();
  1957. #pageCache = new Map();
  1958. #pagePromises = new Map();
  1959. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  1960. this.messageHandler = messageHandler;
  1961. this.loadingTask = loadingTask;
  1962. this.commonObjs = new PDFObjects();
  1963. this.fontLoader = new _font_loader.FontLoader({
  1964. ownerDocument: params.ownerDocument,
  1965. styleElement: params.styleElement
  1966. });
  1967. this._params = params;
  1968. this.canvasFactory = factory.canvasFactory;
  1969. this.filterFactory = factory.filterFactory;
  1970. this.cMapReaderFactory = factory.cMapReaderFactory;
  1971. this.standardFontDataFactory = factory.standardFontDataFactory;
  1972. this.destroyed = false;
  1973. this.destroyCapability = null;
  1974. this._passwordCapability = null;
  1975. this._networkStream = networkStream;
  1976. this._fullReader = null;
  1977. this._lastProgress = null;
  1978. this.downloadInfoCapability = (0, _util.createPromiseCapability)();
  1979. this.setupMessageHandler();
  1980. }
  1981. #cacheSimpleMethod(name, data = null) {
  1982. const cachedPromise = this.#methodPromises.get(name);
  1983. if (cachedPromise) {
  1984. return cachedPromise;
  1985. }
  1986. const promise = this.messageHandler.sendWithPromise(name, data);
  1987. this.#methodPromises.set(name, promise);
  1988. return promise;
  1989. }
  1990. get annotationStorage() {
  1991. return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  1992. }
  1993. getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
  1994. let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
  1995. let annotationMap = null;
  1996. switch (intent) {
  1997. case "any":
  1998. renderingIntent = _util.RenderingIntentFlag.ANY;
  1999. break;
  2000. case "display":
  2001. break;
  2002. case "print":
  2003. renderingIntent = _util.RenderingIntentFlag.PRINT;
  2004. break;
  2005. default:
  2006. (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
  2007. }
  2008. switch (annotationMode) {
  2009. case _util.AnnotationMode.DISABLE:
  2010. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
  2011. break;
  2012. case _util.AnnotationMode.ENABLE:
  2013. break;
  2014. case _util.AnnotationMode.ENABLE_FORMS:
  2015. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
  2016. break;
  2017. case _util.AnnotationMode.ENABLE_STORAGE:
  2018. renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
  2019. const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  2020. annotationMap = annotationStorage.serializable;
  2021. break;
  2022. default:
  2023. (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  2024. }
  2025. if (isOpList) {
  2026. renderingIntent += _util.RenderingIntentFlag.OPLIST;
  2027. }
  2028. return {
  2029. renderingIntent,
  2030. cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
  2031. annotationStorageMap: annotationMap
  2032. };
  2033. }
  2034. destroy() {
  2035. if (this.destroyCapability) {
  2036. return this.destroyCapability.promise;
  2037. }
  2038. this.destroyed = true;
  2039. this.destroyCapability = (0, _util.createPromiseCapability)();
  2040. if (this._passwordCapability) {
  2041. this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
  2042. }
  2043. const waitOn = [];
  2044. for (const page of this.#pageCache.values()) {
  2045. waitOn.push(page._destroy());
  2046. }
  2047. this.#pageCache.clear();
  2048. this.#pagePromises.clear();
  2049. if (this.hasOwnProperty("annotationStorage")) {
  2050. this.annotationStorage.resetModified();
  2051. }
  2052. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  2053. waitOn.push(terminated);
  2054. Promise.all(waitOn).then(() => {
  2055. this.commonObjs.clear();
  2056. this.fontLoader.clear();
  2057. this.#methodPromises.clear();
  2058. this.filterFactory.destroy();
  2059. if (this._networkStream) {
  2060. this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
  2061. }
  2062. if (this.messageHandler) {
  2063. this.messageHandler.destroy();
  2064. this.messageHandler = null;
  2065. }
  2066. this.destroyCapability.resolve();
  2067. }, this.destroyCapability.reject);
  2068. return this.destroyCapability.promise;
  2069. }
  2070. setupMessageHandler() {
  2071. const {
  2072. messageHandler,
  2073. loadingTask
  2074. } = this;
  2075. messageHandler.on("GetReader", (data, sink) => {
  2076. (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  2077. this._fullReader = this._networkStream.getFullReader();
  2078. this._fullReader.onProgress = evt => {
  2079. this._lastProgress = {
  2080. loaded: evt.loaded,
  2081. total: evt.total
  2082. };
  2083. };
  2084. sink.onPull = () => {
  2085. this._fullReader.read().then(function ({
  2086. value,
  2087. done
  2088. }) {
  2089. if (done) {
  2090. sink.close();
  2091. return;
  2092. }
  2093. (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  2094. sink.enqueue(new Uint8Array(value), 1, [value]);
  2095. }).catch(reason => {
  2096. sink.error(reason);
  2097. });
  2098. };
  2099. sink.onCancel = reason => {
  2100. this._fullReader.cancel(reason);
  2101. sink.ready.catch(readyReason => {
  2102. if (this.destroyed) {
  2103. return;
  2104. }
  2105. throw readyReason;
  2106. });
  2107. };
  2108. });
  2109. messageHandler.on("ReaderHeadersReady", data => {
  2110. const headersCapability = (0, _util.createPromiseCapability)();
  2111. const fullReader = this._fullReader;
  2112. fullReader.headersReady.then(() => {
  2113. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  2114. if (this._lastProgress) {
  2115. loadingTask.onProgress?.(this._lastProgress);
  2116. }
  2117. fullReader.onProgress = evt => {
  2118. loadingTask.onProgress?.({
  2119. loaded: evt.loaded,
  2120. total: evt.total
  2121. });
  2122. };
  2123. }
  2124. headersCapability.resolve({
  2125. isStreamingSupported: fullReader.isStreamingSupported,
  2126. isRangeSupported: fullReader.isRangeSupported,
  2127. contentLength: fullReader.contentLength
  2128. });
  2129. }, headersCapability.reject);
  2130. return headersCapability.promise;
  2131. });
  2132. messageHandler.on("GetRangeReader", (data, sink) => {
  2133. (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  2134. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  2135. if (!rangeReader) {
  2136. sink.close();
  2137. return;
  2138. }
  2139. sink.onPull = () => {
  2140. rangeReader.read().then(function ({
  2141. value,
  2142. done
  2143. }) {
  2144. if (done) {
  2145. sink.close();
  2146. return;
  2147. }
  2148. (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  2149. sink.enqueue(new Uint8Array(value), 1, [value]);
  2150. }).catch(reason => {
  2151. sink.error(reason);
  2152. });
  2153. };
  2154. sink.onCancel = reason => {
  2155. rangeReader.cancel(reason);
  2156. sink.ready.catch(readyReason => {
  2157. if (this.destroyed) {
  2158. return;
  2159. }
  2160. throw readyReason;
  2161. });
  2162. };
  2163. });
  2164. messageHandler.on("GetDoc", ({
  2165. pdfInfo
  2166. }) => {
  2167. this._numPages = pdfInfo.numPages;
  2168. this._htmlForXfa = pdfInfo.htmlForXfa;
  2169. delete pdfInfo.htmlForXfa;
  2170. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  2171. });
  2172. messageHandler.on("DocException", function (ex) {
  2173. let reason;
  2174. switch (ex.name) {
  2175. case "PasswordException":
  2176. reason = new _util.PasswordException(ex.message, ex.code);
  2177. break;
  2178. case "InvalidPDFException":
  2179. reason = new _util.InvalidPDFException(ex.message);
  2180. break;
  2181. case "MissingPDFException":
  2182. reason = new _util.MissingPDFException(ex.message);
  2183. break;
  2184. case "UnexpectedResponseException":
  2185. reason = new _util.UnexpectedResponseException(ex.message, ex.status);
  2186. break;
  2187. case "UnknownErrorException":
  2188. reason = new _util.UnknownErrorException(ex.message, ex.details);
  2189. break;
  2190. default:
  2191. (0, _util.unreachable)("DocException - expected a valid Error.");
  2192. }
  2193. loadingTask._capability.reject(reason);
  2194. });
  2195. messageHandler.on("PasswordRequest", exception => {
  2196. this._passwordCapability = (0, _util.createPromiseCapability)();
  2197. if (loadingTask.onPassword) {
  2198. const updatePassword = password => {
  2199. if (password instanceof Error) {
  2200. this._passwordCapability.reject(password);
  2201. } else {
  2202. this._passwordCapability.resolve({
  2203. password
  2204. });
  2205. }
  2206. };
  2207. try {
  2208. loadingTask.onPassword(updatePassword, exception.code);
  2209. } catch (ex) {
  2210. this._passwordCapability.reject(ex);
  2211. }
  2212. } else {
  2213. this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
  2214. }
  2215. return this._passwordCapability.promise;
  2216. });
  2217. messageHandler.on("DataLoaded", data => {
  2218. loadingTask.onProgress?.({
  2219. loaded: data.length,
  2220. total: data.length
  2221. });
  2222. this.downloadInfoCapability.resolve(data);
  2223. });
  2224. messageHandler.on("StartRenderPage", data => {
  2225. if (this.destroyed) {
  2226. return;
  2227. }
  2228. const page = this.#pageCache.get(data.pageIndex);
  2229. page._startRenderPage(data.transparency, data.cacheKey);
  2230. });
  2231. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  2232. if (this.destroyed) {
  2233. return;
  2234. }
  2235. if (this.commonObjs.has(id)) {
  2236. return;
  2237. }
  2238. switch (type) {
  2239. case "Font":
  2240. const params = this._params;
  2241. if ("error" in exportedData) {
  2242. const exportedError = exportedData.error;
  2243. (0, _util.warn)(`Error during font loading: ${exportedError}`);
  2244. this.commonObjs.resolve(id, exportedError);
  2245. break;
  2246. }
  2247. const inspectFont = params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  2248. const font = new _font_loader.FontFaceObject(exportedData, {
  2249. isEvalSupported: params.isEvalSupported,
  2250. disableFontFace: params.disableFontFace,
  2251. ignoreErrors: params.ignoreErrors,
  2252. inspectFont
  2253. });
  2254. this.fontLoader.bind(font).catch(reason => {
  2255. return messageHandler.sendWithPromise("FontFallback", {
  2256. id
  2257. });
  2258. }).finally(() => {
  2259. if (!params.fontExtraProperties && font.data) {
  2260. font.data = null;
  2261. }
  2262. this.commonObjs.resolve(id, font);
  2263. });
  2264. break;
  2265. case "FontPath":
  2266. case "Image":
  2267. case "Pattern":
  2268. this.commonObjs.resolve(id, exportedData);
  2269. break;
  2270. default:
  2271. throw new Error(`Got unknown common object type ${type}`);
  2272. }
  2273. });
  2274. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  2275. if (this.destroyed) {
  2276. return;
  2277. }
  2278. const pageProxy = this.#pageCache.get(pageIndex);
  2279. if (pageProxy.objs.has(id)) {
  2280. return;
  2281. }
  2282. switch (type) {
  2283. case "Image":
  2284. pageProxy.objs.resolve(id, imageData);
  2285. if (imageData) {
  2286. let length;
  2287. if (imageData.bitmap) {
  2288. const {
  2289. width,
  2290. height
  2291. } = imageData;
  2292. length = width * height * 4;
  2293. } else {
  2294. length = imageData.data?.length || 0;
  2295. }
  2296. if (length > _util.MAX_IMAGE_SIZE_TO_CACHE) {
  2297. pageProxy._maybeCleanupAfterRender = true;
  2298. }
  2299. }
  2300. break;
  2301. case "Pattern":
  2302. pageProxy.objs.resolve(id, imageData);
  2303. break;
  2304. default:
  2305. throw new Error(`Got unknown object type ${type}`);
  2306. }
  2307. });
  2308. messageHandler.on("DocProgress", data => {
  2309. if (this.destroyed) {
  2310. return;
  2311. }
  2312. loadingTask.onProgress?.({
  2313. loaded: data.loaded,
  2314. total: data.total
  2315. });
  2316. });
  2317. messageHandler.on("FetchBuiltInCMap", data => {
  2318. if (this.destroyed) {
  2319. return Promise.reject(new Error("Worker was destroyed."));
  2320. }
  2321. if (!this.cMapReaderFactory) {
  2322. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  2323. }
  2324. return this.cMapReaderFactory.fetch(data);
  2325. });
  2326. messageHandler.on("FetchStandardFontData", data => {
  2327. if (this.destroyed) {
  2328. return Promise.reject(new Error("Worker was destroyed."));
  2329. }
  2330. if (!this.standardFontDataFactory) {
  2331. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  2332. }
  2333. return this.standardFontDataFactory.fetch(data);
  2334. });
  2335. }
  2336. getData() {
  2337. return this.messageHandler.sendWithPromise("GetData", null);
  2338. }
  2339. saveDocument() {
  2340. if (this.annotationStorage.size <= 0) {
  2341. (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  2342. }
  2343. return this.messageHandler.sendWithPromise("SaveDocument", {
  2344. isPureXfa: !!this._htmlForXfa,
  2345. numPages: this._numPages,
  2346. annotationStorage: this.annotationStorage.serializable,
  2347. filename: this._fullReader?.filename ?? null
  2348. }).finally(() => {
  2349. this.annotationStorage.resetModified();
  2350. });
  2351. }
  2352. getPage(pageNumber) {
  2353. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  2354. return Promise.reject(new Error("Invalid page request."));
  2355. }
  2356. const pageIndex = pageNumber - 1,
  2357. cachedPromise = this.#pagePromises.get(pageIndex);
  2358. if (cachedPromise) {
  2359. return cachedPromise;
  2360. }
  2361. const promise = this.messageHandler.sendWithPromise("GetPage", {
  2362. pageIndex
  2363. }).then(pageInfo => {
  2364. if (this.destroyed) {
  2365. throw new Error("Transport destroyed");
  2366. }
  2367. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  2368. this.#pageCache.set(pageIndex, page);
  2369. return page;
  2370. });
  2371. this.#pagePromises.set(pageIndex, promise);
  2372. return promise;
  2373. }
  2374. getPageIndex(ref) {
  2375. if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
  2376. return Promise.reject(new Error("Invalid pageIndex request."));
  2377. }
  2378. return this.messageHandler.sendWithPromise("GetPageIndex", {
  2379. num: ref.num,
  2380. gen: ref.gen
  2381. });
  2382. }
  2383. getAnnotations(pageIndex, intent) {
  2384. return this.messageHandler.sendWithPromise("GetAnnotations", {
  2385. pageIndex,
  2386. intent
  2387. });
  2388. }
  2389. getFieldObjects() {
  2390. return this.#cacheSimpleMethod("GetFieldObjects");
  2391. }
  2392. hasJSActions() {
  2393. return this.#cacheSimpleMethod("HasJSActions");
  2394. }
  2395. getCalculationOrderIds() {
  2396. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  2397. }
  2398. getDestinations() {
  2399. return this.messageHandler.sendWithPromise("GetDestinations", null);
  2400. }
  2401. getDestination(id) {
  2402. if (typeof id !== "string") {
  2403. return Promise.reject(new Error("Invalid destination request."));
  2404. }
  2405. return this.messageHandler.sendWithPromise("GetDestination", {
  2406. id
  2407. });
  2408. }
  2409. getPageLabels() {
  2410. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  2411. }
  2412. getPageLayout() {
  2413. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  2414. }
  2415. getPageMode() {
  2416. return this.messageHandler.sendWithPromise("GetPageMode", null);
  2417. }
  2418. getViewerPreferences() {
  2419. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  2420. }
  2421. getOpenAction() {
  2422. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  2423. }
  2424. getAttachments() {
  2425. return this.messageHandler.sendWithPromise("GetAttachments", null);
  2426. }
  2427. getJavaScript() {
  2428. return this.messageHandler.sendWithPromise("GetJavaScript", null);
  2429. }
  2430. getDocJSActions() {
  2431. return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  2432. }
  2433. getPageJSActions(pageIndex) {
  2434. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  2435. pageIndex
  2436. });
  2437. }
  2438. getStructTree(pageIndex) {
  2439. return this.messageHandler.sendWithPromise("GetStructTree", {
  2440. pageIndex
  2441. });
  2442. }
  2443. getOutline() {
  2444. return this.messageHandler.sendWithPromise("GetOutline", null);
  2445. }
  2446. getOptionalContentConfig() {
  2447. return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
  2448. return new _optional_content_config.OptionalContentConfig(results);
  2449. });
  2450. }
  2451. getPermissions() {
  2452. return this.messageHandler.sendWithPromise("GetPermissions", null);
  2453. }
  2454. getMetadata() {
  2455. const name = "GetMetadata",
  2456. cachedPromise = this.#methodPromises.get(name);
  2457. if (cachedPromise) {
  2458. return cachedPromise;
  2459. }
  2460. const promise = this.messageHandler.sendWithPromise(name, null).then(results => {
  2461. return {
  2462. info: results[0],
  2463. metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
  2464. contentDispositionFilename: this._fullReader?.filename ?? null,
  2465. contentLength: this._fullReader?.contentLength ?? null
  2466. };
  2467. });
  2468. this.#methodPromises.set(name, promise);
  2469. return promise;
  2470. }
  2471. getMarkInfo() {
  2472. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  2473. }
  2474. async startCleanup(keepLoadedFonts = false) {
  2475. if (this.destroyed) {
  2476. return;
  2477. }
  2478. await this.messageHandler.sendWithPromise("Cleanup", null);
  2479. for (const page of this.#pageCache.values()) {
  2480. const cleanupSuccessful = page.cleanup();
  2481. if (!cleanupSuccessful) {
  2482. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  2483. }
  2484. }
  2485. this.commonObjs.clear();
  2486. if (!keepLoadedFonts) {
  2487. this.fontLoader.clear();
  2488. }
  2489. this.#methodPromises.clear();
  2490. this.filterFactory.destroy(true);
  2491. }
  2492. get loadingParams() {
  2493. const {
  2494. disableAutoFetch,
  2495. enableXfa
  2496. } = this._params;
  2497. return (0, _util.shadow)(this, "loadingParams", {
  2498. disableAutoFetch,
  2499. enableXfa
  2500. });
  2501. }
  2502. }
  2503. class PDFObjects {
  2504. #objs = Object.create(null);
  2505. #ensureObj(objId) {
  2506. const obj = this.#objs[objId];
  2507. if (obj) {
  2508. return obj;
  2509. }
  2510. return this.#objs[objId] = {
  2511. capability: (0, _util.createPromiseCapability)(),
  2512. data: null
  2513. };
  2514. }
  2515. get(objId, callback = null) {
  2516. if (callback) {
  2517. const obj = this.#ensureObj(objId);
  2518. obj.capability.promise.then(() => callback(obj.data));
  2519. return null;
  2520. }
  2521. const obj = this.#objs[objId];
  2522. if (!obj?.capability.settled) {
  2523. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  2524. }
  2525. return obj.data;
  2526. }
  2527. has(objId) {
  2528. const obj = this.#objs[objId];
  2529. return obj?.capability.settled || false;
  2530. }
  2531. resolve(objId, data = null) {
  2532. const obj = this.#ensureObj(objId);
  2533. obj.data = data;
  2534. obj.capability.resolve();
  2535. }
  2536. clear() {
  2537. for (const objId in this.#objs) {
  2538. const {
  2539. data
  2540. } = this.#objs[objId];
  2541. data?.bitmap?.close();
  2542. }
  2543. this.#objs = Object.create(null);
  2544. }
  2545. }
  2546. class RenderTask {
  2547. #internalRenderTask = null;
  2548. constructor(internalRenderTask) {
  2549. this.#internalRenderTask = internalRenderTask;
  2550. this.onContinue = null;
  2551. }
  2552. get promise() {
  2553. return this.#internalRenderTask.capability.promise;
  2554. }
  2555. cancel(extraDelay = 0) {
  2556. this.#internalRenderTask.cancel(null, extraDelay);
  2557. }
  2558. get separateAnnots() {
  2559. const {
  2560. separateAnnots
  2561. } = this.#internalRenderTask.operatorList;
  2562. if (!separateAnnots) {
  2563. return false;
  2564. }
  2565. const {
  2566. annotationCanvasMap
  2567. } = this.#internalRenderTask;
  2568. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  2569. }
  2570. }
  2571. exports.RenderTask = RenderTask;
  2572. class InternalRenderTask {
  2573. static #canvasInUse = new WeakSet();
  2574. constructor({
  2575. callback,
  2576. params,
  2577. objs,
  2578. commonObjs,
  2579. annotationCanvasMap,
  2580. operatorList,
  2581. pageIndex,
  2582. canvasFactory,
  2583. filterFactory,
  2584. useRequestAnimationFrame = false,
  2585. pdfBug = false,
  2586. pageColors = null
  2587. }) {
  2588. this.callback = callback;
  2589. this.params = params;
  2590. this.objs = objs;
  2591. this.commonObjs = commonObjs;
  2592. this.annotationCanvasMap = annotationCanvasMap;
  2593. this.operatorListIdx = null;
  2594. this.operatorList = operatorList;
  2595. this._pageIndex = pageIndex;
  2596. this.canvasFactory = canvasFactory;
  2597. this.filterFactory = filterFactory;
  2598. this._pdfBug = pdfBug;
  2599. this.pageColors = pageColors;
  2600. this.running = false;
  2601. this.graphicsReadyCallback = null;
  2602. this.graphicsReady = false;
  2603. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  2604. this.cancelled = false;
  2605. this.capability = (0, _util.createPromiseCapability)();
  2606. this.task = new RenderTask(this);
  2607. this._cancelBound = this.cancel.bind(this);
  2608. this._continueBound = this._continue.bind(this);
  2609. this._scheduleNextBound = this._scheduleNext.bind(this);
  2610. this._nextBound = this._next.bind(this);
  2611. this._canvas = params.canvasContext.canvas;
  2612. }
  2613. get completed() {
  2614. return this.capability.promise.catch(function () {});
  2615. }
  2616. initializeGraphics({
  2617. transparency = false,
  2618. optionalContentConfig
  2619. }) {
  2620. if (this.cancelled) {
  2621. return;
  2622. }
  2623. if (this._canvas) {
  2624. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  2625. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  2626. }
  2627. InternalRenderTask.#canvasInUse.add(this._canvas);
  2628. }
  2629. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  2630. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  2631. this.stepper.init(this.operatorList);
  2632. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2633. }
  2634. const {
  2635. canvasContext,
  2636. viewport,
  2637. transform,
  2638. background
  2639. } = this.params;
  2640. this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  2641. optionalContentConfig
  2642. }, this.annotationCanvasMap);
  2643. this.gfx.beginDrawing({
  2644. transform,
  2645. viewport,
  2646. transparency,
  2647. background
  2648. });
  2649. this.operatorListIdx = 0;
  2650. this.graphicsReady = true;
  2651. this.graphicsReadyCallback?.();
  2652. }
  2653. cancel(error = null, extraDelay = 0) {
  2654. this.running = false;
  2655. this.cancelled = true;
  2656. this.gfx?.endDrawing(this.pageColors);
  2657. if (this._canvas) {
  2658. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2659. }
  2660. this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas", extraDelay));
  2661. }
  2662. operatorListChanged() {
  2663. if (!this.graphicsReady) {
  2664. if (!this.graphicsReadyCallback) {
  2665. this.graphicsReadyCallback = this._continueBound;
  2666. }
  2667. return;
  2668. }
  2669. this.stepper?.updateOperatorList(this.operatorList);
  2670. if (this.running) {
  2671. return;
  2672. }
  2673. this._continue();
  2674. }
  2675. _continue() {
  2676. this.running = true;
  2677. if (this.cancelled) {
  2678. return;
  2679. }
  2680. if (this.task.onContinue) {
  2681. this.task.onContinue(this._scheduleNextBound);
  2682. } else {
  2683. this._scheduleNext();
  2684. }
  2685. }
  2686. _scheduleNext() {
  2687. if (this._useRequestAnimationFrame) {
  2688. window.requestAnimationFrame(() => {
  2689. this._nextBound().catch(this._cancelBound);
  2690. });
  2691. } else {
  2692. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  2693. }
  2694. }
  2695. async _next() {
  2696. if (this.cancelled) {
  2697. return;
  2698. }
  2699. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  2700. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2701. this.running = false;
  2702. if (this.operatorList.lastChunk) {
  2703. this.gfx.endDrawing(this.pageColors);
  2704. if (this._canvas) {
  2705. InternalRenderTask.#canvasInUse.delete(this._canvas);
  2706. }
  2707. this.callback();
  2708. }
  2709. }
  2710. }
  2711. }
  2712. const version = '3.5.141';
  2713. exports.version = version;
  2714. const build = 'be0f6ee08';
  2715. exports.build = build;
  2716. /***/ }),
  2717. /* 3 */
  2718. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2719. Object.defineProperty(exports, "__esModule", ({
  2720. value: true
  2721. }));
  2722. exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
  2723. var _util = __w_pdfjs_require__(1);
  2724. var _editor = __w_pdfjs_require__(4);
  2725. var _murmurhash = __w_pdfjs_require__(8);
  2726. class AnnotationStorage {
  2727. #modified = false;
  2728. #storage = new Map();
  2729. constructor() {
  2730. this.onSetModified = null;
  2731. this.onResetModified = null;
  2732. this.onAnnotationEditor = null;
  2733. }
  2734. getValue(key, defaultValue) {
  2735. const value = this.#storage.get(key);
  2736. if (value === undefined) {
  2737. return defaultValue;
  2738. }
  2739. return Object.assign(defaultValue, value);
  2740. }
  2741. getRawValue(key) {
  2742. return this.#storage.get(key);
  2743. }
  2744. remove(key) {
  2745. this.#storage.delete(key);
  2746. if (this.#storage.size === 0) {
  2747. this.resetModified();
  2748. }
  2749. if (typeof this.onAnnotationEditor === "function") {
  2750. for (const value of this.#storage.values()) {
  2751. if (value instanceof _editor.AnnotationEditor) {
  2752. return;
  2753. }
  2754. }
  2755. this.onAnnotationEditor(null);
  2756. }
  2757. }
  2758. setValue(key, value) {
  2759. const obj = this.#storage.get(key);
  2760. let modified = false;
  2761. if (obj !== undefined) {
  2762. for (const [entry, val] of Object.entries(value)) {
  2763. if (obj[entry] !== val) {
  2764. modified = true;
  2765. obj[entry] = val;
  2766. }
  2767. }
  2768. } else {
  2769. modified = true;
  2770. this.#storage.set(key, value);
  2771. }
  2772. if (modified) {
  2773. this.#setModified();
  2774. }
  2775. if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  2776. this.onAnnotationEditor(value.constructor._type);
  2777. }
  2778. }
  2779. has(key) {
  2780. return this.#storage.has(key);
  2781. }
  2782. getAll() {
  2783. return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
  2784. }
  2785. setAll(obj) {
  2786. for (const [key, val] of Object.entries(obj)) {
  2787. this.setValue(key, val);
  2788. }
  2789. }
  2790. get size() {
  2791. return this.#storage.size;
  2792. }
  2793. #setModified() {
  2794. if (!this.#modified) {
  2795. this.#modified = true;
  2796. if (typeof this.onSetModified === "function") {
  2797. this.onSetModified();
  2798. }
  2799. }
  2800. }
  2801. resetModified() {
  2802. if (this.#modified) {
  2803. this.#modified = false;
  2804. if (typeof this.onResetModified === "function") {
  2805. this.onResetModified();
  2806. }
  2807. }
  2808. }
  2809. get print() {
  2810. return new PrintAnnotationStorage(this);
  2811. }
  2812. get serializable() {
  2813. if (this.#storage.size === 0) {
  2814. return null;
  2815. }
  2816. const clone = new Map();
  2817. for (const [key, val] of this.#storage) {
  2818. const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
  2819. if (serialized) {
  2820. clone.set(key, serialized);
  2821. }
  2822. }
  2823. return clone;
  2824. }
  2825. static getHash(map) {
  2826. if (!map) {
  2827. return "";
  2828. }
  2829. const hash = new _murmurhash.MurmurHash3_64();
  2830. for (const [key, val] of map) {
  2831. hash.update(`${key}:${JSON.stringify(val)}`);
  2832. }
  2833. return hash.hexdigest();
  2834. }
  2835. }
  2836. exports.AnnotationStorage = AnnotationStorage;
  2837. class PrintAnnotationStorage extends AnnotationStorage {
  2838. #serializable = null;
  2839. constructor(parent) {
  2840. super();
  2841. this.#serializable = structuredClone(parent.serializable);
  2842. }
  2843. get print() {
  2844. (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  2845. }
  2846. get serializable() {
  2847. return this.#serializable;
  2848. }
  2849. }
  2850. exports.PrintAnnotationStorage = PrintAnnotationStorage;
  2851. /***/ }),
  2852. /* 4 */
  2853. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2854. Object.defineProperty(exports, "__esModule", ({
  2855. value: true
  2856. }));
  2857. exports.AnnotationEditor = void 0;
  2858. var _tools = __w_pdfjs_require__(5);
  2859. var _util = __w_pdfjs_require__(1);
  2860. class AnnotationEditor {
  2861. #boundFocusin = this.focusin.bind(this);
  2862. #boundFocusout = this.focusout.bind(this);
  2863. #hasBeenSelected = false;
  2864. #isEditing = false;
  2865. #isInEditMode = false;
  2866. _uiManager = null;
  2867. #zIndex = AnnotationEditor._zIndex++;
  2868. static _colorManager = new _tools.ColorManager();
  2869. static _zIndex = 1;
  2870. constructor(parameters) {
  2871. if (this.constructor === AnnotationEditor) {
  2872. (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
  2873. }
  2874. this.parent = parameters.parent;
  2875. this.id = parameters.id;
  2876. this.width = this.height = null;
  2877. this.pageIndex = parameters.parent.pageIndex;
  2878. this.name = parameters.name;
  2879. this.div = null;
  2880. this._uiManager = parameters.uiManager;
  2881. const {
  2882. rotation,
  2883. rawDims: {
  2884. pageWidth,
  2885. pageHeight,
  2886. pageX,
  2887. pageY
  2888. }
  2889. } = this.parent.viewport;
  2890. this.rotation = rotation;
  2891. this.pageDimensions = [pageWidth, pageHeight];
  2892. this.pageTranslation = [pageX, pageY];
  2893. const [width, height] = this.parentDimensions;
  2894. this.x = parameters.x / width;
  2895. this.y = parameters.y / height;
  2896. this.isAttachedToDOM = false;
  2897. }
  2898. static get _defaultLineColor() {
  2899. return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  2900. }
  2901. addCommands(params) {
  2902. this._uiManager.addCommands(params);
  2903. }
  2904. get currentLayer() {
  2905. return this._uiManager.currentLayer;
  2906. }
  2907. setInBackground() {
  2908. this.div.style.zIndex = 0;
  2909. }
  2910. setInForeground() {
  2911. this.div.style.zIndex = this.#zIndex;
  2912. }
  2913. setParent(parent) {
  2914. if (parent !== null) {
  2915. this.pageIndex = parent.pageIndex;
  2916. this.pageDimensions = parent.pageDimensions;
  2917. }
  2918. this.parent = parent;
  2919. }
  2920. focusin(event) {
  2921. if (!this.#hasBeenSelected) {
  2922. this.parent.setSelected(this);
  2923. } else {
  2924. this.#hasBeenSelected = false;
  2925. }
  2926. }
  2927. focusout(event) {
  2928. if (!this.isAttachedToDOM) {
  2929. return;
  2930. }
  2931. const target = event.relatedTarget;
  2932. if (target?.closest(`#${this.id}`)) {
  2933. return;
  2934. }
  2935. event.preventDefault();
  2936. if (!this.parent?.isMultipleSelection) {
  2937. this.commitOrRemove();
  2938. }
  2939. }
  2940. commitOrRemove() {
  2941. if (this.isEmpty()) {
  2942. this.remove();
  2943. } else {
  2944. this.commit();
  2945. }
  2946. }
  2947. commit() {
  2948. this.addToAnnotationStorage();
  2949. }
  2950. addToAnnotationStorage() {
  2951. this._uiManager.addToAnnotationStorage(this);
  2952. }
  2953. dragstart(event) {
  2954. const rect = this.parent.div.getBoundingClientRect();
  2955. this.startX = event.clientX - rect.x;
  2956. this.startY = event.clientY - rect.y;
  2957. event.dataTransfer.setData("text/plain", this.id);
  2958. event.dataTransfer.effectAllowed = "move";
  2959. }
  2960. setAt(x, y, tx, ty) {
  2961. const [width, height] = this.parentDimensions;
  2962. [tx, ty] = this.screenToPageTranslation(tx, ty);
  2963. this.x = (x + tx) / width;
  2964. this.y = (y + ty) / height;
  2965. this.div.style.left = `${100 * this.x}%`;
  2966. this.div.style.top = `${100 * this.y}%`;
  2967. }
  2968. translate(x, y) {
  2969. const [width, height] = this.parentDimensions;
  2970. [x, y] = this.screenToPageTranslation(x, y);
  2971. this.x += x / width;
  2972. this.y += y / height;
  2973. this.div.style.left = `${100 * this.x}%`;
  2974. this.div.style.top = `${100 * this.y}%`;
  2975. }
  2976. screenToPageTranslation(x, y) {
  2977. switch (this.parentRotation) {
  2978. case 90:
  2979. return [y, -x];
  2980. case 180:
  2981. return [-x, -y];
  2982. case 270:
  2983. return [-y, x];
  2984. default:
  2985. return [x, y];
  2986. }
  2987. }
  2988. get parentScale() {
  2989. return this._uiManager.viewParameters.realScale;
  2990. }
  2991. get parentRotation() {
  2992. return this._uiManager.viewParameters.rotation;
  2993. }
  2994. get parentDimensions() {
  2995. const {
  2996. realScale
  2997. } = this._uiManager.viewParameters;
  2998. const [pageWidth, pageHeight] = this.pageDimensions;
  2999. return [pageWidth * realScale, pageHeight * realScale];
  3000. }
  3001. setDims(width, height) {
  3002. const [parentWidth, parentHeight] = this.parentDimensions;
  3003. this.div.style.width = `${100 * width / parentWidth}%`;
  3004. this.div.style.height = `${100 * height / parentHeight}%`;
  3005. }
  3006. fixDims() {
  3007. const {
  3008. style
  3009. } = this.div;
  3010. const {
  3011. height,
  3012. width
  3013. } = style;
  3014. const widthPercent = width.endsWith("%");
  3015. const heightPercent = height.endsWith("%");
  3016. if (widthPercent && heightPercent) {
  3017. return;
  3018. }
  3019. const [parentWidth, parentHeight] = this.parentDimensions;
  3020. if (!widthPercent) {
  3021. style.width = `${100 * parseFloat(width) / parentWidth}%`;
  3022. }
  3023. if (!heightPercent) {
  3024. style.height = `${100 * parseFloat(height) / parentHeight}%`;
  3025. }
  3026. }
  3027. getInitialTranslation() {
  3028. return [0, 0];
  3029. }
  3030. render() {
  3031. this.div = document.createElement("div");
  3032. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  3033. this.div.className = this.name;
  3034. this.div.setAttribute("id", this.id);
  3035. this.div.setAttribute("tabIndex", 0);
  3036. this.setInForeground();
  3037. this.div.addEventListener("focusin", this.#boundFocusin);
  3038. this.div.addEventListener("focusout", this.#boundFocusout);
  3039. const [tx, ty] = this.getInitialTranslation();
  3040. this.translate(tx, ty);
  3041. (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
  3042. return this.div;
  3043. }
  3044. pointerdown(event) {
  3045. const {
  3046. isMac
  3047. } = _util.FeatureTest.platform;
  3048. if (event.button !== 0 || event.ctrlKey && isMac) {
  3049. event.preventDefault();
  3050. return;
  3051. }
  3052. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  3053. this.parent.toggleSelected(this);
  3054. } else {
  3055. this.parent.setSelected(this);
  3056. }
  3057. this.#hasBeenSelected = true;
  3058. }
  3059. getRect(tx, ty) {
  3060. const scale = this.parentScale;
  3061. const [pageWidth, pageHeight] = this.pageDimensions;
  3062. const [pageX, pageY] = this.pageTranslation;
  3063. const shiftX = tx / scale;
  3064. const shiftY = ty / scale;
  3065. const x = this.x * pageWidth;
  3066. const y = this.y * pageHeight;
  3067. const width = this.width * pageWidth;
  3068. const height = this.height * pageHeight;
  3069. switch (this.rotation) {
  3070. case 0:
  3071. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  3072. case 90:
  3073. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  3074. case 180:
  3075. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  3076. case 270:
  3077. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  3078. default:
  3079. throw new Error("Invalid rotation");
  3080. }
  3081. }
  3082. getRectInCurrentCoords(rect, pageHeight) {
  3083. const [x1, y1, x2, y2] = rect;
  3084. const width = x2 - x1;
  3085. const height = y2 - y1;
  3086. switch (this.rotation) {
  3087. case 0:
  3088. return [x1, pageHeight - y2, width, height];
  3089. case 90:
  3090. return [x1, pageHeight - y1, height, width];
  3091. case 180:
  3092. return [x2, pageHeight - y1, width, height];
  3093. case 270:
  3094. return [x2, pageHeight - y2, height, width];
  3095. default:
  3096. throw new Error("Invalid rotation");
  3097. }
  3098. }
  3099. onceAdded() {}
  3100. isEmpty() {
  3101. return false;
  3102. }
  3103. enableEditMode() {
  3104. this.#isInEditMode = true;
  3105. }
  3106. disableEditMode() {
  3107. this.#isInEditMode = false;
  3108. }
  3109. isInEditMode() {
  3110. return this.#isInEditMode;
  3111. }
  3112. shouldGetKeyboardEvents() {
  3113. return false;
  3114. }
  3115. needsToBeRebuilt() {
  3116. return this.div && !this.isAttachedToDOM;
  3117. }
  3118. rebuild() {
  3119. this.div?.addEventListener("focusin", this.#boundFocusin);
  3120. }
  3121. serialize() {
  3122. (0, _util.unreachable)("An editor must be serializable");
  3123. }
  3124. static deserialize(data, parent, uiManager) {
  3125. const editor = new this.prototype.constructor({
  3126. parent,
  3127. id: parent.getNextId(),
  3128. uiManager
  3129. });
  3130. editor.rotation = data.rotation;
  3131. const [pageWidth, pageHeight] = editor.pageDimensions;
  3132. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  3133. editor.x = x / pageWidth;
  3134. editor.y = y / pageHeight;
  3135. editor.width = width / pageWidth;
  3136. editor.height = height / pageHeight;
  3137. return editor;
  3138. }
  3139. remove() {
  3140. this.div.removeEventListener("focusin", this.#boundFocusin);
  3141. this.div.removeEventListener("focusout", this.#boundFocusout);
  3142. if (!this.isEmpty()) {
  3143. this.commit();
  3144. }
  3145. this.parent.remove(this);
  3146. }
  3147. select() {
  3148. this.div?.classList.add("selectedEditor");
  3149. }
  3150. unselect() {
  3151. this.div?.classList.remove("selectedEditor");
  3152. }
  3153. updateParams(type, value) {}
  3154. disableEditing() {}
  3155. enableEditing() {}
  3156. get propertiesToUpdate() {
  3157. return {};
  3158. }
  3159. get contentDiv() {
  3160. return this.div;
  3161. }
  3162. get isEditing() {
  3163. return this.#isEditing;
  3164. }
  3165. set isEditing(value) {
  3166. this.#isEditing = value;
  3167. if (value) {
  3168. this.parent.setSelected(this);
  3169. this.parent.setActiveEditor(this);
  3170. } else {
  3171. this.parent.setActiveEditor(null);
  3172. }
  3173. }
  3174. }
  3175. exports.AnnotationEditor = AnnotationEditor;
  3176. /***/ }),
  3177. /* 5 */
  3178. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3179. Object.defineProperty(exports, "__esModule", ({
  3180. value: true
  3181. }));
  3182. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  3183. exports.bindEvents = bindEvents;
  3184. exports.opacityToHex = opacityToHex;
  3185. var _util = __w_pdfjs_require__(1);
  3186. var _display_utils = __w_pdfjs_require__(6);
  3187. function bindEvents(obj, element, names) {
  3188. for (const name of names) {
  3189. element.addEventListener(name, obj[name].bind(obj));
  3190. }
  3191. }
  3192. function opacityToHex(opacity) {
  3193. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  3194. }
  3195. class IdManager {
  3196. #id = 0;
  3197. getId() {
  3198. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  3199. }
  3200. }
  3201. class CommandManager {
  3202. #commands = [];
  3203. #locked = false;
  3204. #maxSize;
  3205. #position = -1;
  3206. constructor(maxSize = 128) {
  3207. this.#maxSize = maxSize;
  3208. }
  3209. add({
  3210. cmd,
  3211. undo,
  3212. mustExec,
  3213. type = NaN,
  3214. overwriteIfSameType = false,
  3215. keepUndo = false
  3216. }) {
  3217. if (mustExec) {
  3218. cmd();
  3219. }
  3220. if (this.#locked) {
  3221. return;
  3222. }
  3223. const save = {
  3224. cmd,
  3225. undo,
  3226. type
  3227. };
  3228. if (this.#position === -1) {
  3229. if (this.#commands.length > 0) {
  3230. this.#commands.length = 0;
  3231. }
  3232. this.#position = 0;
  3233. this.#commands.push(save);
  3234. return;
  3235. }
  3236. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  3237. if (keepUndo) {
  3238. save.undo = this.#commands[this.#position].undo;
  3239. }
  3240. this.#commands[this.#position] = save;
  3241. return;
  3242. }
  3243. const next = this.#position + 1;
  3244. if (next === this.#maxSize) {
  3245. this.#commands.splice(0, 1);
  3246. } else {
  3247. this.#position = next;
  3248. if (next < this.#commands.length) {
  3249. this.#commands.splice(next);
  3250. }
  3251. }
  3252. this.#commands.push(save);
  3253. }
  3254. undo() {
  3255. if (this.#position === -1) {
  3256. return;
  3257. }
  3258. this.#locked = true;
  3259. this.#commands[this.#position].undo();
  3260. this.#locked = false;
  3261. this.#position -= 1;
  3262. }
  3263. redo() {
  3264. if (this.#position < this.#commands.length - 1) {
  3265. this.#position += 1;
  3266. this.#locked = true;
  3267. this.#commands[this.#position].cmd();
  3268. this.#locked = false;
  3269. }
  3270. }
  3271. hasSomethingToUndo() {
  3272. return this.#position !== -1;
  3273. }
  3274. hasSomethingToRedo() {
  3275. return this.#position < this.#commands.length - 1;
  3276. }
  3277. destroy() {
  3278. this.#commands = null;
  3279. }
  3280. }
  3281. exports.CommandManager = CommandManager;
  3282. class KeyboardManager {
  3283. constructor(callbacks) {
  3284. this.buffer = [];
  3285. this.callbacks = new Map();
  3286. this.allKeys = new Set();
  3287. const {
  3288. isMac
  3289. } = _util.FeatureTest.platform;
  3290. for (const [keys, callback] of callbacks) {
  3291. for (const key of keys) {
  3292. const isMacKey = key.startsWith("mac+");
  3293. if (isMac && isMacKey) {
  3294. this.callbacks.set(key.slice(4), callback);
  3295. this.allKeys.add(key.split("+").at(-1));
  3296. } else if (!isMac && !isMacKey) {
  3297. this.callbacks.set(key, callback);
  3298. this.allKeys.add(key.split("+").at(-1));
  3299. }
  3300. }
  3301. }
  3302. }
  3303. #serialize(event) {
  3304. if (event.altKey) {
  3305. this.buffer.push("alt");
  3306. }
  3307. if (event.ctrlKey) {
  3308. this.buffer.push("ctrl");
  3309. }
  3310. if (event.metaKey) {
  3311. this.buffer.push("meta");
  3312. }
  3313. if (event.shiftKey) {
  3314. this.buffer.push("shift");
  3315. }
  3316. this.buffer.push(event.key);
  3317. const str = this.buffer.join("+");
  3318. this.buffer.length = 0;
  3319. return str;
  3320. }
  3321. exec(self, event) {
  3322. if (!this.allKeys.has(event.key)) {
  3323. return;
  3324. }
  3325. const callback = this.callbacks.get(this.#serialize(event));
  3326. if (!callback) {
  3327. return;
  3328. }
  3329. callback.bind(self)();
  3330. event.stopPropagation();
  3331. event.preventDefault();
  3332. }
  3333. }
  3334. exports.KeyboardManager = KeyboardManager;
  3335. class ColorManager {
  3336. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  3337. get _colors() {
  3338. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  3339. (0, _display_utils.getColorValues)(colors);
  3340. return (0, _util.shadow)(this, "_colors", colors);
  3341. }
  3342. convert(color) {
  3343. const rgb = (0, _display_utils.getRGB)(color);
  3344. if (!window.matchMedia("(forced-colors: active)").matches) {
  3345. return rgb;
  3346. }
  3347. for (const [name, RGB] of this._colors) {
  3348. if (RGB.every((x, i) => x === rgb[i])) {
  3349. return ColorManager._colorsMapping.get(name);
  3350. }
  3351. }
  3352. return rgb;
  3353. }
  3354. getHexCode(name) {
  3355. const rgb = this._colors.get(name);
  3356. if (!rgb) {
  3357. return name;
  3358. }
  3359. return _util.Util.makeHexColor(...rgb);
  3360. }
  3361. }
  3362. exports.ColorManager = ColorManager;
  3363. class AnnotationEditorUIManager {
  3364. #activeEditor = null;
  3365. #allEditors = new Map();
  3366. #allLayers = new Map();
  3367. #annotationStorage = null;
  3368. #commandManager = new CommandManager();
  3369. #currentPageIndex = 0;
  3370. #editorTypes = null;
  3371. #editorsToRescale = new Set();
  3372. #eventBus = null;
  3373. #idManager = new IdManager();
  3374. #isEnabled = false;
  3375. #mode = _util.AnnotationEditorType.NONE;
  3376. #selectedEditors = new Set();
  3377. #boundCopy = this.copy.bind(this);
  3378. #boundCut = this.cut.bind(this);
  3379. #boundPaste = this.paste.bind(this);
  3380. #boundKeydown = this.keydown.bind(this);
  3381. #boundOnEditingAction = this.onEditingAction.bind(this);
  3382. #boundOnPageChanging = this.onPageChanging.bind(this);
  3383. #boundOnScaleChanging = this.onScaleChanging.bind(this);
  3384. #boundOnRotationChanging = this.onRotationChanging.bind(this);
  3385. #previousStates = {
  3386. isEditing: false,
  3387. isEmpty: true,
  3388. hasSomethingToUndo: false,
  3389. hasSomethingToRedo: false,
  3390. hasSelectedEditor: false
  3391. };
  3392. #container = null;
  3393. 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]]);
  3394. constructor(container, eventBus, annotationStorage) {
  3395. this.#container = container;
  3396. this.#eventBus = eventBus;
  3397. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  3398. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  3399. this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
  3400. this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
  3401. this.#annotationStorage = annotationStorage;
  3402. this.viewParameters = {
  3403. realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
  3404. rotation: 0
  3405. };
  3406. }
  3407. destroy() {
  3408. this.#removeKeyboardManager();
  3409. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  3410. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  3411. this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
  3412. this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
  3413. for (const layer of this.#allLayers.values()) {
  3414. layer.destroy();
  3415. }
  3416. this.#allLayers.clear();
  3417. this.#allEditors.clear();
  3418. this.#editorsToRescale.clear();
  3419. this.#activeEditor = null;
  3420. this.#selectedEditors.clear();
  3421. this.#commandManager.destroy();
  3422. }
  3423. onPageChanging({
  3424. pageNumber
  3425. }) {
  3426. this.#currentPageIndex = pageNumber - 1;
  3427. }
  3428. focusMainContainer() {
  3429. this.#container.focus();
  3430. }
  3431. addShouldRescale(editor) {
  3432. this.#editorsToRescale.add(editor);
  3433. }
  3434. removeShouldRescale(editor) {
  3435. this.#editorsToRescale.delete(editor);
  3436. }
  3437. onScaleChanging({
  3438. scale
  3439. }) {
  3440. this.commitOrRemove();
  3441. this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
  3442. for (const editor of this.#editorsToRescale) {
  3443. editor.onScaleChanging();
  3444. }
  3445. }
  3446. onRotationChanging({
  3447. pagesRotation
  3448. }) {
  3449. this.commitOrRemove();
  3450. this.viewParameters.rotation = pagesRotation;
  3451. }
  3452. addToAnnotationStorage(editor) {
  3453. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  3454. this.#annotationStorage.setValue(editor.id, editor);
  3455. }
  3456. }
  3457. #addKeyboardManager() {
  3458. this.#container.addEventListener("keydown", this.#boundKeydown);
  3459. }
  3460. #removeKeyboardManager() {
  3461. this.#container.removeEventListener("keydown", this.#boundKeydown);
  3462. }
  3463. #addCopyPasteListeners() {
  3464. document.addEventListener("copy", this.#boundCopy);
  3465. document.addEventListener("cut", this.#boundCut);
  3466. document.addEventListener("paste", this.#boundPaste);
  3467. }
  3468. #removeCopyPasteListeners() {
  3469. document.removeEventListener("copy", this.#boundCopy);
  3470. document.removeEventListener("cut", this.#boundCut);
  3471. document.removeEventListener("paste", this.#boundPaste);
  3472. }
  3473. copy(event) {
  3474. event.preventDefault();
  3475. if (this.#activeEditor) {
  3476. this.#activeEditor.commitOrRemove();
  3477. }
  3478. if (!this.hasSelection) {
  3479. return;
  3480. }
  3481. const editors = [];
  3482. for (const editor of this.#selectedEditors) {
  3483. if (!editor.isEmpty()) {
  3484. editors.push(editor.serialize());
  3485. }
  3486. }
  3487. if (editors.length === 0) {
  3488. return;
  3489. }
  3490. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  3491. }
  3492. cut(event) {
  3493. this.copy(event);
  3494. this.delete();
  3495. }
  3496. paste(event) {
  3497. event.preventDefault();
  3498. let data = event.clipboardData.getData("application/pdfjs");
  3499. if (!data) {
  3500. return;
  3501. }
  3502. try {
  3503. data = JSON.parse(data);
  3504. } catch (ex) {
  3505. (0, _util.warn)(`paste: "${ex.message}".`);
  3506. return;
  3507. }
  3508. if (!Array.isArray(data)) {
  3509. return;
  3510. }
  3511. this.unselectAll();
  3512. const layer = this.#allLayers.get(this.#currentPageIndex);
  3513. try {
  3514. const newEditors = [];
  3515. for (const editor of data) {
  3516. const deserializedEditor = layer.deserialize(editor);
  3517. if (!deserializedEditor) {
  3518. return;
  3519. }
  3520. newEditors.push(deserializedEditor);
  3521. }
  3522. const cmd = () => {
  3523. for (const editor of newEditors) {
  3524. this.#addEditorToLayer(editor);
  3525. }
  3526. this.#selectEditors(newEditors);
  3527. };
  3528. const undo = () => {
  3529. for (const editor of newEditors) {
  3530. editor.remove();
  3531. }
  3532. };
  3533. this.addCommands({
  3534. cmd,
  3535. undo,
  3536. mustExec: true
  3537. });
  3538. } catch (ex) {
  3539. (0, _util.warn)(`paste: "${ex.message}".`);
  3540. }
  3541. }
  3542. keydown(event) {
  3543. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  3544. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  3545. }
  3546. }
  3547. onEditingAction(details) {
  3548. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  3549. this[details.name]();
  3550. }
  3551. }
  3552. #dispatchUpdateStates(details) {
  3553. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  3554. if (hasChanged) {
  3555. this.#eventBus.dispatch("annotationeditorstateschanged", {
  3556. source: this,
  3557. details: Object.assign(this.#previousStates, details)
  3558. });
  3559. }
  3560. }
  3561. #dispatchUpdateUI(details) {
  3562. this.#eventBus.dispatch("annotationeditorparamschanged", {
  3563. source: this,
  3564. details
  3565. });
  3566. }
  3567. setEditingState(isEditing) {
  3568. if (isEditing) {
  3569. this.#addKeyboardManager();
  3570. this.#addCopyPasteListeners();
  3571. this.#dispatchUpdateStates({
  3572. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  3573. isEmpty: this.#isEmpty(),
  3574. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3575. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3576. hasSelectedEditor: false
  3577. });
  3578. } else {
  3579. this.#removeKeyboardManager();
  3580. this.#removeCopyPasteListeners();
  3581. this.#dispatchUpdateStates({
  3582. isEditing: false
  3583. });
  3584. }
  3585. }
  3586. registerEditorTypes(types) {
  3587. if (this.#editorTypes) {
  3588. return;
  3589. }
  3590. this.#editorTypes = types;
  3591. for (const editorType of this.#editorTypes) {
  3592. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  3593. }
  3594. }
  3595. getId() {
  3596. return this.#idManager.getId();
  3597. }
  3598. get currentLayer() {
  3599. return this.#allLayers.get(this.#currentPageIndex);
  3600. }
  3601. get currentPageIndex() {
  3602. return this.#currentPageIndex;
  3603. }
  3604. addLayer(layer) {
  3605. this.#allLayers.set(layer.pageIndex, layer);
  3606. if (this.#isEnabled) {
  3607. layer.enable();
  3608. } else {
  3609. layer.disable();
  3610. }
  3611. }
  3612. removeLayer(layer) {
  3613. this.#allLayers.delete(layer.pageIndex);
  3614. }
  3615. updateMode(mode) {
  3616. this.#mode = mode;
  3617. if (mode === _util.AnnotationEditorType.NONE) {
  3618. this.setEditingState(false);
  3619. this.#disableAll();
  3620. } else {
  3621. this.setEditingState(true);
  3622. this.#enableAll();
  3623. for (const layer of this.#allLayers.values()) {
  3624. layer.updateMode(mode);
  3625. }
  3626. }
  3627. }
  3628. updateToolbar(mode) {
  3629. if (mode === this.#mode) {
  3630. return;
  3631. }
  3632. this.#eventBus.dispatch("switchannotationeditormode", {
  3633. source: this,
  3634. mode
  3635. });
  3636. }
  3637. updateParams(type, value) {
  3638. if (!this.#editorTypes) {
  3639. return;
  3640. }
  3641. for (const editor of this.#selectedEditors) {
  3642. editor.updateParams(type, value);
  3643. }
  3644. for (const editorType of this.#editorTypes) {
  3645. editorType.updateDefaultParams(type, value);
  3646. }
  3647. }
  3648. #enableAll() {
  3649. if (!this.#isEnabled) {
  3650. this.#isEnabled = true;
  3651. for (const layer of this.#allLayers.values()) {
  3652. layer.enable();
  3653. }
  3654. }
  3655. }
  3656. #disableAll() {
  3657. this.unselectAll();
  3658. if (this.#isEnabled) {
  3659. this.#isEnabled = false;
  3660. for (const layer of this.#allLayers.values()) {
  3661. layer.disable();
  3662. }
  3663. }
  3664. }
  3665. getEditors(pageIndex) {
  3666. const editors = [];
  3667. for (const editor of this.#allEditors.values()) {
  3668. if (editor.pageIndex === pageIndex) {
  3669. editors.push(editor);
  3670. }
  3671. }
  3672. return editors;
  3673. }
  3674. getEditor(id) {
  3675. return this.#allEditors.get(id);
  3676. }
  3677. addEditor(editor) {
  3678. this.#allEditors.set(editor.id, editor);
  3679. }
  3680. removeEditor(editor) {
  3681. this.#allEditors.delete(editor.id);
  3682. this.unselect(editor);
  3683. this.#annotationStorage?.remove(editor.id);
  3684. }
  3685. #addEditorToLayer(editor) {
  3686. const layer = this.#allLayers.get(editor.pageIndex);
  3687. if (layer) {
  3688. layer.addOrRebuild(editor);
  3689. } else {
  3690. this.addEditor(editor);
  3691. }
  3692. }
  3693. setActiveEditor(editor) {
  3694. if (this.#activeEditor === editor) {
  3695. return;
  3696. }
  3697. this.#activeEditor = editor;
  3698. if (editor) {
  3699. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3700. }
  3701. }
  3702. toggleSelected(editor) {
  3703. if (this.#selectedEditors.has(editor)) {
  3704. this.#selectedEditors.delete(editor);
  3705. editor.unselect();
  3706. this.#dispatchUpdateStates({
  3707. hasSelectedEditor: this.hasSelection
  3708. });
  3709. return;
  3710. }
  3711. this.#selectedEditors.add(editor);
  3712. editor.select();
  3713. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3714. this.#dispatchUpdateStates({
  3715. hasSelectedEditor: true
  3716. });
  3717. }
  3718. setSelected(editor) {
  3719. for (const ed of this.#selectedEditors) {
  3720. if (ed !== editor) {
  3721. ed.unselect();
  3722. }
  3723. }
  3724. this.#selectedEditors.clear();
  3725. this.#selectedEditors.add(editor);
  3726. editor.select();
  3727. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  3728. this.#dispatchUpdateStates({
  3729. hasSelectedEditor: true
  3730. });
  3731. }
  3732. isSelected(editor) {
  3733. return this.#selectedEditors.has(editor);
  3734. }
  3735. unselect(editor) {
  3736. editor.unselect();
  3737. this.#selectedEditors.delete(editor);
  3738. this.#dispatchUpdateStates({
  3739. hasSelectedEditor: this.hasSelection
  3740. });
  3741. }
  3742. get hasSelection() {
  3743. return this.#selectedEditors.size !== 0;
  3744. }
  3745. undo() {
  3746. this.#commandManager.undo();
  3747. this.#dispatchUpdateStates({
  3748. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  3749. hasSomethingToRedo: true,
  3750. isEmpty: this.#isEmpty()
  3751. });
  3752. }
  3753. redo() {
  3754. this.#commandManager.redo();
  3755. this.#dispatchUpdateStates({
  3756. hasSomethingToUndo: true,
  3757. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  3758. isEmpty: this.#isEmpty()
  3759. });
  3760. }
  3761. addCommands(params) {
  3762. this.#commandManager.add(params);
  3763. this.#dispatchUpdateStates({
  3764. hasSomethingToUndo: true,
  3765. hasSomethingToRedo: false,
  3766. isEmpty: this.#isEmpty()
  3767. });
  3768. }
  3769. #isEmpty() {
  3770. if (this.#allEditors.size === 0) {
  3771. return true;
  3772. }
  3773. if (this.#allEditors.size === 1) {
  3774. for (const editor of this.#allEditors.values()) {
  3775. return editor.isEmpty();
  3776. }
  3777. }
  3778. return false;
  3779. }
  3780. delete() {
  3781. this.commitOrRemove();
  3782. if (!this.hasSelection) {
  3783. return;
  3784. }
  3785. const editors = [...this.#selectedEditors];
  3786. const cmd = () => {
  3787. for (const editor of editors) {
  3788. editor.remove();
  3789. }
  3790. };
  3791. const undo = () => {
  3792. for (const editor of editors) {
  3793. this.#addEditorToLayer(editor);
  3794. }
  3795. };
  3796. this.addCommands({
  3797. cmd,
  3798. undo,
  3799. mustExec: true
  3800. });
  3801. }
  3802. commitOrRemove() {
  3803. this.#activeEditor?.commitOrRemove();
  3804. }
  3805. #selectEditors(editors) {
  3806. this.#selectedEditors.clear();
  3807. for (const editor of editors) {
  3808. if (editor.isEmpty()) {
  3809. continue;
  3810. }
  3811. this.#selectedEditors.add(editor);
  3812. editor.select();
  3813. }
  3814. this.#dispatchUpdateStates({
  3815. hasSelectedEditor: true
  3816. });
  3817. }
  3818. selectAll() {
  3819. for (const editor of this.#selectedEditors) {
  3820. editor.commit();
  3821. }
  3822. this.#selectEditors(this.#allEditors.values());
  3823. }
  3824. unselectAll() {
  3825. if (this.#activeEditor) {
  3826. this.#activeEditor.commitOrRemove();
  3827. return;
  3828. }
  3829. if (this.#selectedEditors.size === 0) {
  3830. return;
  3831. }
  3832. for (const editor of this.#selectedEditors) {
  3833. editor.unselect();
  3834. }
  3835. this.#selectedEditors.clear();
  3836. this.#dispatchUpdateStates({
  3837. hasSelectedEditor: false
  3838. });
  3839. }
  3840. isActive(editor) {
  3841. return this.#activeEditor === editor;
  3842. }
  3843. getActive() {
  3844. return this.#activeEditor;
  3845. }
  3846. getMode() {
  3847. return this.#mode;
  3848. }
  3849. }
  3850. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
  3851. /***/ }),
  3852. /* 6 */
  3853. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3854. Object.defineProperty(exports, "__esModule", ({
  3855. value: true
  3856. }));
  3857. exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMFilterFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  3858. exports.deprecated = deprecated;
  3859. exports.getColorValues = getColorValues;
  3860. exports.getCurrentTransform = getCurrentTransform;
  3861. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  3862. exports.getFilenameFromUrl = getFilenameFromUrl;
  3863. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  3864. exports.getRGB = getRGB;
  3865. exports.getXfaPageViewport = getXfaPageViewport;
  3866. exports.isDataScheme = isDataScheme;
  3867. exports.isPdfFile = isPdfFile;
  3868. exports.isValidFetchUrl = isValidFetchUrl;
  3869. exports.loadScript = loadScript;
  3870. exports.setLayerDimensions = setLayerDimensions;
  3871. var _base_factory = __w_pdfjs_require__(7);
  3872. var _util = __w_pdfjs_require__(1);
  3873. const SVG_NS = "http://www.w3.org/2000/svg";
  3874. const AnnotationPrefix = "pdfjs_internal_id_";
  3875. exports.AnnotationPrefix = AnnotationPrefix;
  3876. class PixelsPerInch {
  3877. static CSS = 96.0;
  3878. static PDF = 72.0;
  3879. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  3880. }
  3881. exports.PixelsPerInch = PixelsPerInch;
  3882. class DOMFilterFactory extends _base_factory.BaseFilterFactory {
  3883. #_cache;
  3884. #_defs;
  3885. #docId;
  3886. #document;
  3887. #hcmFilter;
  3888. #hcmKey;
  3889. #hcmUrl;
  3890. #id = 0;
  3891. constructor({
  3892. docId,
  3893. ownerDocument = globalThis.document
  3894. } = {}) {
  3895. super();
  3896. this.#docId = docId;
  3897. this.#document = ownerDocument;
  3898. }
  3899. get #cache() {
  3900. return this.#_cache ||= new Map();
  3901. }
  3902. get #defs() {
  3903. if (!this.#_defs) {
  3904. const div = this.#document.createElement("div");
  3905. const {
  3906. style
  3907. } = div;
  3908. style.visibility = "hidden";
  3909. style.contain = "strict";
  3910. style.width = style.height = 0;
  3911. style.position = "absolute";
  3912. style.top = style.left = 0;
  3913. style.zIndex = -1;
  3914. const svg = this.#document.createElementNS(SVG_NS, "svg");
  3915. svg.setAttribute("width", 0);
  3916. svg.setAttribute("height", 0);
  3917. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  3918. div.append(svg);
  3919. svg.append(this.#_defs);
  3920. this.#document.body.append(div);
  3921. }
  3922. return this.#_defs;
  3923. }
  3924. #appendFeFunc(feComponentTransfer, func, table) {
  3925. const feFunc = this.#document.createElementNS(SVG_NS, func);
  3926. feFunc.setAttribute("type", "discrete");
  3927. feFunc.setAttribute("tableValues", table);
  3928. feComponentTransfer.append(feFunc);
  3929. }
  3930. addFilter(maps) {
  3931. if (!maps) {
  3932. return "none";
  3933. }
  3934. let value = this.#cache.get(maps);
  3935. if (value) {
  3936. return value;
  3937. }
  3938. let tableR, tableG, tableB, key;
  3939. if (maps.length === 1) {
  3940. const mapR = maps[0];
  3941. const buffer = new Array(256);
  3942. for (let i = 0; i < 256; i++) {
  3943. buffer[i] = mapR[i] / 255;
  3944. }
  3945. key = tableR = tableG = tableB = buffer.join(",");
  3946. } else {
  3947. const [mapR, mapG, mapB] = maps;
  3948. const bufferR = new Array(256);
  3949. const bufferG = new Array(256);
  3950. const bufferB = new Array(256);
  3951. for (let i = 0; i < 256; i++) {
  3952. bufferR[i] = mapR[i] / 255;
  3953. bufferG[i] = mapG[i] / 255;
  3954. bufferB[i] = mapB[i] / 255;
  3955. }
  3956. tableR = bufferR.join(",");
  3957. tableG = bufferG.join(",");
  3958. tableB = bufferB.join(",");
  3959. key = `${tableR}${tableG}${tableB}`;
  3960. }
  3961. value = this.#cache.get(key);
  3962. if (value) {
  3963. this.#cache.set(maps, value);
  3964. return value;
  3965. }
  3966. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  3967. const url = `url(#${id})`;
  3968. this.#cache.set(maps, url);
  3969. this.#cache.set(key, url);
  3970. const filter = this.#document.createElementNS(SVG_NS, "filter", SVG_NS);
  3971. filter.setAttribute("id", id);
  3972. filter.setAttribute("color-interpolation-filters", "sRGB");
  3973. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  3974. filter.append(feComponentTransfer);
  3975. this.#appendFeFunc(feComponentTransfer, "feFuncR", tableR);
  3976. this.#appendFeFunc(feComponentTransfer, "feFuncG", tableG);
  3977. this.#appendFeFunc(feComponentTransfer, "feFuncB", tableB);
  3978. this.#defs.append(filter);
  3979. return url;
  3980. }
  3981. addHCMFilter(fgColor, bgColor) {
  3982. const key = `${fgColor}-${bgColor}`;
  3983. if (this.#hcmKey === key) {
  3984. return this.#hcmUrl;
  3985. }
  3986. this.#hcmKey = key;
  3987. this.#hcmUrl = "none";
  3988. this.#hcmFilter?.remove();
  3989. if (!fgColor || !bgColor) {
  3990. return this.#hcmUrl;
  3991. }
  3992. this.#defs.style.color = fgColor;
  3993. fgColor = getComputedStyle(this.#defs).getPropertyValue("color");
  3994. const fgRGB = getRGB(fgColor);
  3995. fgColor = _util.Util.makeHexColor(...fgRGB);
  3996. this.#defs.style.color = bgColor;
  3997. bgColor = getComputedStyle(this.#defs).getPropertyValue("color");
  3998. const bgRGB = getRGB(bgColor);
  3999. bgColor = _util.Util.makeHexColor(...bgRGB);
  4000. this.#defs.style.color = "";
  4001. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  4002. return this.#hcmUrl;
  4003. }
  4004. const map = new Array(256);
  4005. for (let i = 0; i <= 255; i++) {
  4006. const x = i / 255;
  4007. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  4008. }
  4009. const table = map.join(",");
  4010. const id = `g_${this.#docId}_hcm_filter`;
  4011. const filter = this.#hcmFilter = this.#document.createElementNS(SVG_NS, "filter", SVG_NS);
  4012. filter.setAttribute("id", id);
  4013. filter.setAttribute("color-interpolation-filters", "sRGB");
  4014. let feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  4015. filter.append(feComponentTransfer);
  4016. this.#appendFeFunc(feComponentTransfer, "feFuncR", table);
  4017. this.#appendFeFunc(feComponentTransfer, "feFuncG", table);
  4018. this.#appendFeFunc(feComponentTransfer, "feFuncB", table);
  4019. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  4020. feColorMatrix.setAttribute("type", "matrix");
  4021. feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
  4022. filter.append(feColorMatrix);
  4023. feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  4024. filter.append(feComponentTransfer);
  4025. const getSteps = (c, n) => {
  4026. const start = fgRGB[c] / 255;
  4027. const end = bgRGB[c] / 255;
  4028. const arr = new Array(n + 1);
  4029. for (let i = 0; i <= n; i++) {
  4030. arr[i] = start + i / n * (end - start);
  4031. }
  4032. return arr.join(",");
  4033. };
  4034. this.#appendFeFunc(feComponentTransfer, "feFuncR", getSteps(0, 5));
  4035. this.#appendFeFunc(feComponentTransfer, "feFuncG", getSteps(1, 5));
  4036. this.#appendFeFunc(feComponentTransfer, "feFuncB", getSteps(2, 5));
  4037. this.#defs.append(filter);
  4038. this.#hcmUrl = `url(#${id})`;
  4039. return this.#hcmUrl;
  4040. }
  4041. destroy(keepHCM = false) {
  4042. if (keepHCM && this.#hcmUrl) {
  4043. return;
  4044. }
  4045. if (this.#_defs) {
  4046. this.#_defs.parentNode.parentNode.remove();
  4047. this.#_defs = null;
  4048. }
  4049. if (this.#_cache) {
  4050. this.#_cache.clear();
  4051. this.#_cache = null;
  4052. }
  4053. this.#id = 0;
  4054. }
  4055. }
  4056. exports.DOMFilterFactory = DOMFilterFactory;
  4057. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  4058. constructor({
  4059. ownerDocument = globalThis.document
  4060. } = {}) {
  4061. super();
  4062. this._document = ownerDocument;
  4063. }
  4064. _createCanvas(width, height) {
  4065. const canvas = this._document.createElement("canvas");
  4066. canvas.width = width;
  4067. canvas.height = height;
  4068. return canvas;
  4069. }
  4070. }
  4071. exports.DOMCanvasFactory = DOMCanvasFactory;
  4072. async function fetchData(url, asTypedArray = false) {
  4073. if (isValidFetchUrl(url, document.baseURI)) {
  4074. const response = await fetch(url);
  4075. if (!response.ok) {
  4076. throw new Error(response.statusText);
  4077. }
  4078. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  4079. }
  4080. return new Promise((resolve, reject) => {
  4081. const request = new XMLHttpRequest();
  4082. request.open("GET", url, true);
  4083. if (asTypedArray) {
  4084. request.responseType = "arraybuffer";
  4085. }
  4086. request.onreadystatechange = () => {
  4087. if (request.readyState !== XMLHttpRequest.DONE) {
  4088. return;
  4089. }
  4090. if (request.status === 200 || request.status === 0) {
  4091. let data;
  4092. if (asTypedArray && request.response) {
  4093. data = new Uint8Array(request.response);
  4094. } else if (!asTypedArray && request.responseText) {
  4095. data = (0, _util.stringToBytes)(request.responseText);
  4096. }
  4097. if (data) {
  4098. resolve(data);
  4099. return;
  4100. }
  4101. }
  4102. reject(new Error(request.statusText));
  4103. };
  4104. request.send(null);
  4105. });
  4106. }
  4107. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  4108. _fetchData(url, compressionType) {
  4109. return fetchData(url, this.isCompressed).then(data => {
  4110. return {
  4111. cMapData: data,
  4112. compressionType
  4113. };
  4114. });
  4115. }
  4116. }
  4117. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  4118. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  4119. _fetchData(url) {
  4120. return fetchData(url, true);
  4121. }
  4122. }
  4123. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  4124. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  4125. _createSVG(type) {
  4126. return document.createElementNS(SVG_NS, type);
  4127. }
  4128. }
  4129. exports.DOMSVGFactory = DOMSVGFactory;
  4130. class PageViewport {
  4131. constructor({
  4132. viewBox,
  4133. scale,
  4134. rotation,
  4135. offsetX = 0,
  4136. offsetY = 0,
  4137. dontFlip = false
  4138. }) {
  4139. this.viewBox = viewBox;
  4140. this.scale = scale;
  4141. this.rotation = rotation;
  4142. this.offsetX = offsetX;
  4143. this.offsetY = offsetY;
  4144. const centerX = (viewBox[2] + viewBox[0]) / 2;
  4145. const centerY = (viewBox[3] + viewBox[1]) / 2;
  4146. let rotateA, rotateB, rotateC, rotateD;
  4147. rotation %= 360;
  4148. if (rotation < 0) {
  4149. rotation += 360;
  4150. }
  4151. switch (rotation) {
  4152. case 180:
  4153. rotateA = -1;
  4154. rotateB = 0;
  4155. rotateC = 0;
  4156. rotateD = 1;
  4157. break;
  4158. case 90:
  4159. rotateA = 0;
  4160. rotateB = 1;
  4161. rotateC = 1;
  4162. rotateD = 0;
  4163. break;
  4164. case 270:
  4165. rotateA = 0;
  4166. rotateB = -1;
  4167. rotateC = -1;
  4168. rotateD = 0;
  4169. break;
  4170. case 0:
  4171. rotateA = 1;
  4172. rotateB = 0;
  4173. rotateC = 0;
  4174. rotateD = -1;
  4175. break;
  4176. default:
  4177. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  4178. }
  4179. if (dontFlip) {
  4180. rotateC = -rotateC;
  4181. rotateD = -rotateD;
  4182. }
  4183. let offsetCanvasX, offsetCanvasY;
  4184. let width, height;
  4185. if (rotateA === 0) {
  4186. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  4187. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  4188. width = (viewBox[3] - viewBox[1]) * scale;
  4189. height = (viewBox[2] - viewBox[0]) * scale;
  4190. } else {
  4191. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  4192. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  4193. width = (viewBox[2] - viewBox[0]) * scale;
  4194. height = (viewBox[3] - viewBox[1]) * scale;
  4195. }
  4196. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4197. this.width = width;
  4198. this.height = height;
  4199. }
  4200. get rawDims() {
  4201. const {
  4202. viewBox
  4203. } = this;
  4204. return (0, _util.shadow)(this, "rawDims", {
  4205. pageWidth: viewBox[2] - viewBox[0],
  4206. pageHeight: viewBox[3] - viewBox[1],
  4207. pageX: viewBox[0],
  4208. pageY: viewBox[1]
  4209. });
  4210. }
  4211. clone({
  4212. scale = this.scale,
  4213. rotation = this.rotation,
  4214. offsetX = this.offsetX,
  4215. offsetY = this.offsetY,
  4216. dontFlip = false
  4217. } = {}) {
  4218. return new PageViewport({
  4219. viewBox: this.viewBox.slice(),
  4220. scale,
  4221. rotation,
  4222. offsetX,
  4223. offsetY,
  4224. dontFlip
  4225. });
  4226. }
  4227. convertToViewportPoint(x, y) {
  4228. return _util.Util.applyTransform([x, y], this.transform);
  4229. }
  4230. convertToViewportRectangle(rect) {
  4231. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  4232. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  4233. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  4234. }
  4235. convertToPdfPoint(x, y) {
  4236. return _util.Util.applyInverseTransform([x, y], this.transform);
  4237. }
  4238. }
  4239. exports.PageViewport = PageViewport;
  4240. class RenderingCancelledException extends _util.BaseException {
  4241. constructor(msg, type, extraDelay = 0) {
  4242. super(msg, "RenderingCancelledException");
  4243. this.type = type;
  4244. this.extraDelay = extraDelay;
  4245. }
  4246. }
  4247. exports.RenderingCancelledException = RenderingCancelledException;
  4248. function isDataScheme(url) {
  4249. const ii = url.length;
  4250. let i = 0;
  4251. while (i < ii && url[i].trim() === "") {
  4252. i++;
  4253. }
  4254. return url.substring(i, i + 5).toLowerCase() === "data:";
  4255. }
  4256. function isPdfFile(filename) {
  4257. return typeof filename === "string" && /\.pdf$/i.test(filename);
  4258. }
  4259. function getFilenameFromUrl(url, onlyStripPath = false) {
  4260. if (!onlyStripPath) {
  4261. [url] = url.split(/[#?]/, 1);
  4262. }
  4263. return url.substring(url.lastIndexOf("/") + 1);
  4264. }
  4265. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  4266. if (typeof url !== "string") {
  4267. return defaultFilename;
  4268. }
  4269. if (isDataScheme(url)) {
  4270. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  4271. return defaultFilename;
  4272. }
  4273. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  4274. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  4275. const splitURI = reURI.exec(url);
  4276. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  4277. if (suggestedFilename) {
  4278. suggestedFilename = suggestedFilename[0];
  4279. if (suggestedFilename.includes("%")) {
  4280. try {
  4281. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  4282. } catch (ex) {}
  4283. }
  4284. }
  4285. return suggestedFilename || defaultFilename;
  4286. }
  4287. class StatTimer {
  4288. started = Object.create(null);
  4289. times = [];
  4290. time(name) {
  4291. if (name in this.started) {
  4292. (0, _util.warn)(`Timer is already running for ${name}`);
  4293. }
  4294. this.started[name] = Date.now();
  4295. }
  4296. timeEnd(name) {
  4297. if (!(name in this.started)) {
  4298. (0, _util.warn)(`Timer has not been started for ${name}`);
  4299. }
  4300. this.times.push({
  4301. name,
  4302. start: this.started[name],
  4303. end: Date.now()
  4304. });
  4305. delete this.started[name];
  4306. }
  4307. toString() {
  4308. const outBuf = [];
  4309. let longest = 0;
  4310. for (const {
  4311. name
  4312. } of this.times) {
  4313. longest = Math.max(name.length, longest);
  4314. }
  4315. for (const {
  4316. name,
  4317. start,
  4318. end
  4319. } of this.times) {
  4320. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  4321. }
  4322. return outBuf.join("");
  4323. }
  4324. }
  4325. exports.StatTimer = StatTimer;
  4326. function isValidFetchUrl(url, baseUrl) {
  4327. try {
  4328. const {
  4329. protocol
  4330. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  4331. return protocol === "http:" || protocol === "https:";
  4332. } catch (ex) {
  4333. return false;
  4334. }
  4335. }
  4336. function loadScript(src, removeScriptElement = false) {
  4337. return new Promise((resolve, reject) => {
  4338. const script = document.createElement("script");
  4339. script.src = src;
  4340. script.onload = function (evt) {
  4341. if (removeScriptElement) {
  4342. script.remove();
  4343. }
  4344. resolve(evt);
  4345. };
  4346. script.onerror = function () {
  4347. reject(new Error(`Cannot load script at: ${script.src}`));
  4348. };
  4349. (document.head || document.documentElement).append(script);
  4350. });
  4351. }
  4352. function deprecated(details) {
  4353. console.log("Deprecated API usage: " + details);
  4354. }
  4355. let pdfDateStringRegex;
  4356. class PDFDateString {
  4357. static toDateObject(input) {
  4358. if (!input || typeof input !== "string") {
  4359. return null;
  4360. }
  4361. if (!pdfDateStringRegex) {
  4362. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  4363. }
  4364. const matches = pdfDateStringRegex.exec(input);
  4365. if (!matches) {
  4366. return null;
  4367. }
  4368. const year = parseInt(matches[1], 10);
  4369. let month = parseInt(matches[2], 10);
  4370. month = month >= 1 && month <= 12 ? month - 1 : 0;
  4371. let day = parseInt(matches[3], 10);
  4372. day = day >= 1 && day <= 31 ? day : 1;
  4373. let hour = parseInt(matches[4], 10);
  4374. hour = hour >= 0 && hour <= 23 ? hour : 0;
  4375. let minute = parseInt(matches[5], 10);
  4376. minute = minute >= 0 && minute <= 59 ? minute : 0;
  4377. let second = parseInt(matches[6], 10);
  4378. second = second >= 0 && second <= 59 ? second : 0;
  4379. const universalTimeRelation = matches[7] || "Z";
  4380. let offsetHour = parseInt(matches[8], 10);
  4381. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  4382. let offsetMinute = parseInt(matches[9], 10) || 0;
  4383. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  4384. if (universalTimeRelation === "-") {
  4385. hour += offsetHour;
  4386. minute += offsetMinute;
  4387. } else if (universalTimeRelation === "+") {
  4388. hour -= offsetHour;
  4389. minute -= offsetMinute;
  4390. }
  4391. return new Date(Date.UTC(year, month, day, hour, minute, second));
  4392. }
  4393. }
  4394. exports.PDFDateString = PDFDateString;
  4395. function getXfaPageViewport(xfaPage, {
  4396. scale = 1,
  4397. rotation = 0
  4398. }) {
  4399. const {
  4400. width,
  4401. height
  4402. } = xfaPage.attributes.style;
  4403. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  4404. return new PageViewport({
  4405. viewBox,
  4406. scale,
  4407. rotation
  4408. });
  4409. }
  4410. function getRGB(color) {
  4411. if (color.startsWith("#")) {
  4412. const colorRGB = parseInt(color.slice(1), 16);
  4413. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  4414. }
  4415. if (color.startsWith("rgb(")) {
  4416. return color.slice(4, -1).split(",").map(x => parseInt(x));
  4417. }
  4418. if (color.startsWith("rgba(")) {
  4419. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  4420. }
  4421. (0, _util.warn)(`Not a valid color format: "${color}"`);
  4422. return [0, 0, 0];
  4423. }
  4424. function getColorValues(colors) {
  4425. const span = document.createElement("span");
  4426. span.style.visibility = "hidden";
  4427. document.body.append(span);
  4428. for (const name of colors.keys()) {
  4429. span.style.color = name;
  4430. const computedColor = window.getComputedStyle(span).color;
  4431. colors.set(name, getRGB(computedColor));
  4432. }
  4433. span.remove();
  4434. }
  4435. function getCurrentTransform(ctx) {
  4436. const {
  4437. a,
  4438. b,
  4439. c,
  4440. d,
  4441. e,
  4442. f
  4443. } = ctx.getTransform();
  4444. return [a, b, c, d, e, f];
  4445. }
  4446. function getCurrentTransformInverse(ctx) {
  4447. const {
  4448. a,
  4449. b,
  4450. c,
  4451. d,
  4452. e,
  4453. f
  4454. } = ctx.getTransform().invertSelf();
  4455. return [a, b, c, d, e, f];
  4456. }
  4457. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  4458. if (viewport instanceof PageViewport) {
  4459. const {
  4460. pageWidth,
  4461. pageHeight
  4462. } = viewport.rawDims;
  4463. const {
  4464. style
  4465. } = div;
  4466. const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
  4467. const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
  4468. if (!mustFlip || viewport.rotation % 180 === 0) {
  4469. style.width = widthStr;
  4470. style.height = heightStr;
  4471. } else {
  4472. style.width = heightStr;
  4473. style.height = widthStr;
  4474. }
  4475. }
  4476. if (mustRotate) {
  4477. div.setAttribute("data-main-rotation", viewport.rotation);
  4478. }
  4479. }
  4480. /***/ }),
  4481. /* 7 */
  4482. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4483. Object.defineProperty(exports, "__esModule", ({
  4484. value: true
  4485. }));
  4486. exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseFilterFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
  4487. var _util = __w_pdfjs_require__(1);
  4488. class BaseFilterFactory {
  4489. constructor() {
  4490. if (this.constructor === BaseFilterFactory) {
  4491. (0, _util.unreachable)("Cannot initialize BaseFilterFactory.");
  4492. }
  4493. }
  4494. addFilter(maps) {
  4495. return "none";
  4496. }
  4497. addHCMFilter(fgColor, bgColor) {
  4498. return "none";
  4499. }
  4500. destroy(keepHCM = false) {}
  4501. }
  4502. exports.BaseFilterFactory = BaseFilterFactory;
  4503. class BaseCanvasFactory {
  4504. constructor() {
  4505. if (this.constructor === BaseCanvasFactory) {
  4506. (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
  4507. }
  4508. }
  4509. create(width, height) {
  4510. if (width <= 0 || height <= 0) {
  4511. throw new Error("Invalid canvas size");
  4512. }
  4513. const canvas = this._createCanvas(width, height);
  4514. return {
  4515. canvas,
  4516. context: canvas.getContext("2d")
  4517. };
  4518. }
  4519. reset(canvasAndContext, width, height) {
  4520. if (!canvasAndContext.canvas) {
  4521. throw new Error("Canvas is not specified");
  4522. }
  4523. if (width <= 0 || height <= 0) {
  4524. throw new Error("Invalid canvas size");
  4525. }
  4526. canvasAndContext.canvas.width = width;
  4527. canvasAndContext.canvas.height = height;
  4528. }
  4529. destroy(canvasAndContext) {
  4530. if (!canvasAndContext.canvas) {
  4531. throw new Error("Canvas is not specified");
  4532. }
  4533. canvasAndContext.canvas.width = 0;
  4534. canvasAndContext.canvas.height = 0;
  4535. canvasAndContext.canvas = null;
  4536. canvasAndContext.context = null;
  4537. }
  4538. _createCanvas(width, height) {
  4539. (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  4540. }
  4541. }
  4542. exports.BaseCanvasFactory = BaseCanvasFactory;
  4543. class BaseCMapReaderFactory {
  4544. constructor({
  4545. baseUrl = null,
  4546. isCompressed = true
  4547. }) {
  4548. if (this.constructor === BaseCMapReaderFactory) {
  4549. (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
  4550. }
  4551. this.baseUrl = baseUrl;
  4552. this.isCompressed = isCompressed;
  4553. }
  4554. async fetch({
  4555. name
  4556. }) {
  4557. if (!this.baseUrl) {
  4558. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  4559. }
  4560. if (!name) {
  4561. throw new Error("CMap name must be specified.");
  4562. }
  4563. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  4564. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  4565. return this._fetchData(url, compressionType).catch(reason => {
  4566. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  4567. });
  4568. }
  4569. _fetchData(url, compressionType) {
  4570. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4571. }
  4572. }
  4573. exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
  4574. class BaseStandardFontDataFactory {
  4575. constructor({
  4576. baseUrl = null
  4577. }) {
  4578. if (this.constructor === BaseStandardFontDataFactory) {
  4579. (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
  4580. }
  4581. this.baseUrl = baseUrl;
  4582. }
  4583. async fetch({
  4584. filename
  4585. }) {
  4586. if (!this.baseUrl) {
  4587. throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
  4588. }
  4589. if (!filename) {
  4590. throw new Error("Font filename must be specified.");
  4591. }
  4592. const url = `${this.baseUrl}${filename}`;
  4593. return this._fetchData(url).catch(reason => {
  4594. throw new Error(`Unable to load font data at: ${url}`);
  4595. });
  4596. }
  4597. _fetchData(url) {
  4598. (0, _util.unreachable)("Abstract method `_fetchData` called.");
  4599. }
  4600. }
  4601. exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
  4602. class BaseSVGFactory {
  4603. constructor() {
  4604. if (this.constructor === BaseSVGFactory) {
  4605. (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
  4606. }
  4607. }
  4608. create(width, height, skipDimensions = false) {
  4609. if (width <= 0 || height <= 0) {
  4610. throw new Error("Invalid SVG dimensions");
  4611. }
  4612. const svg = this._createSVG("svg:svg");
  4613. svg.setAttribute("version", "1.1");
  4614. if (!skipDimensions) {
  4615. svg.setAttribute("width", `${width}px`);
  4616. svg.setAttribute("height", `${height}px`);
  4617. }
  4618. svg.setAttribute("preserveAspectRatio", "none");
  4619. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  4620. return svg;
  4621. }
  4622. createElement(type) {
  4623. if (typeof type !== "string") {
  4624. throw new Error("Invalid SVG element type");
  4625. }
  4626. return this._createSVG(type);
  4627. }
  4628. _createSVG(type) {
  4629. (0, _util.unreachable)("Abstract method `_createSVG` called.");
  4630. }
  4631. }
  4632. exports.BaseSVGFactory = BaseSVGFactory;
  4633. /***/ }),
  4634. /* 8 */
  4635. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4636. Object.defineProperty(exports, "__esModule", ({
  4637. value: true
  4638. }));
  4639. exports.MurmurHash3_64 = void 0;
  4640. var _util = __w_pdfjs_require__(1);
  4641. const SEED = 0xc3d2e1f0;
  4642. const MASK_HIGH = 0xffff0000;
  4643. const MASK_LOW = 0xffff;
  4644. class MurmurHash3_64 {
  4645. constructor(seed) {
  4646. this.h1 = seed ? seed & 0xffffffff : SEED;
  4647. this.h2 = seed ? seed & 0xffffffff : SEED;
  4648. }
  4649. update(input) {
  4650. let data, length;
  4651. if (typeof input === "string") {
  4652. data = new Uint8Array(input.length * 2);
  4653. length = 0;
  4654. for (let i = 0, ii = input.length; i < ii; i++) {
  4655. const code = input.charCodeAt(i);
  4656. if (code <= 0xff) {
  4657. data[length++] = code;
  4658. } else {
  4659. data[length++] = code >>> 8;
  4660. data[length++] = code & 0xff;
  4661. }
  4662. }
  4663. } else if ((0, _util.isArrayBuffer)(input)) {
  4664. data = input.slice();
  4665. length = data.byteLength;
  4666. } else {
  4667. throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
  4668. }
  4669. const blockCounts = length >> 2;
  4670. const tailLength = length - blockCounts * 4;
  4671. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  4672. let k1 = 0,
  4673. k2 = 0;
  4674. let h1 = this.h1,
  4675. h2 = this.h2;
  4676. const C1 = 0xcc9e2d51,
  4677. C2 = 0x1b873593;
  4678. const C1_LOW = C1 & MASK_LOW,
  4679. C2_LOW = C2 & MASK_LOW;
  4680. for (let i = 0; i < blockCounts; i++) {
  4681. if (i & 1) {
  4682. k1 = dataUint32[i];
  4683. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4684. k1 = k1 << 15 | k1 >>> 17;
  4685. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4686. h1 ^= k1;
  4687. h1 = h1 << 13 | h1 >>> 19;
  4688. h1 = h1 * 5 + 0xe6546b64;
  4689. } else {
  4690. k2 = dataUint32[i];
  4691. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  4692. k2 = k2 << 15 | k2 >>> 17;
  4693. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  4694. h2 ^= k2;
  4695. h2 = h2 << 13 | h2 >>> 19;
  4696. h2 = h2 * 5 + 0xe6546b64;
  4697. }
  4698. }
  4699. k1 = 0;
  4700. switch (tailLength) {
  4701. case 3:
  4702. k1 ^= data[blockCounts * 4 + 2] << 16;
  4703. case 2:
  4704. k1 ^= data[blockCounts * 4 + 1] << 8;
  4705. case 1:
  4706. k1 ^= data[blockCounts * 4];
  4707. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  4708. k1 = k1 << 15 | k1 >>> 17;
  4709. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  4710. if (blockCounts & 1) {
  4711. h1 ^= k1;
  4712. } else {
  4713. h2 ^= k1;
  4714. }
  4715. }
  4716. this.h1 = h1;
  4717. this.h2 = h2;
  4718. }
  4719. hexdigest() {
  4720. let h1 = this.h1,
  4721. h2 = this.h2;
  4722. h1 ^= h2 >>> 1;
  4723. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  4724. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  4725. h1 ^= h2 >>> 1;
  4726. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  4727. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  4728. h1 ^= h2 >>> 1;
  4729. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  4730. }
  4731. }
  4732. exports.MurmurHash3_64 = MurmurHash3_64;
  4733. /***/ }),
  4734. /* 9 */
  4735. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4736. Object.defineProperty(exports, "__esModule", ({
  4737. value: true
  4738. }));
  4739. exports.FontLoader = exports.FontFaceObject = void 0;
  4740. var _util = __w_pdfjs_require__(1);
  4741. var _is_node = __w_pdfjs_require__(10);
  4742. class FontLoader {
  4743. constructor({
  4744. ownerDocument = globalThis.document,
  4745. styleElement = null
  4746. }) {
  4747. this._document = ownerDocument;
  4748. this.nativeFontFaces = [];
  4749. this.styleElement = null;
  4750. this.loadingRequests = [];
  4751. this.loadTestFontId = 0;
  4752. }
  4753. addNativeFontFace(nativeFontFace) {
  4754. this.nativeFontFaces.push(nativeFontFace);
  4755. this._document.fonts.add(nativeFontFace);
  4756. }
  4757. insertRule(rule) {
  4758. if (!this.styleElement) {
  4759. this.styleElement = this._document.createElement("style");
  4760. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  4761. }
  4762. const styleSheet = this.styleElement.sheet;
  4763. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  4764. }
  4765. clear() {
  4766. for (const nativeFontFace of this.nativeFontFaces) {
  4767. this._document.fonts.delete(nativeFontFace);
  4768. }
  4769. this.nativeFontFaces.length = 0;
  4770. if (this.styleElement) {
  4771. this.styleElement.remove();
  4772. this.styleElement = null;
  4773. }
  4774. }
  4775. async bind(font) {
  4776. if (font.attached || font.missingFile) {
  4777. return;
  4778. }
  4779. font.attached = true;
  4780. if (this.isFontLoadingAPISupported) {
  4781. const nativeFontFace = font.createNativeFontFace();
  4782. if (nativeFontFace) {
  4783. this.addNativeFontFace(nativeFontFace);
  4784. try {
  4785. await nativeFontFace.loaded;
  4786. } catch (ex) {
  4787. (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  4788. font.disableFontFace = true;
  4789. throw ex;
  4790. }
  4791. }
  4792. return;
  4793. }
  4794. const rule = font.createFontFaceRule();
  4795. if (rule) {
  4796. this.insertRule(rule);
  4797. if (this.isSyncFontLoadingSupported) {
  4798. return;
  4799. }
  4800. await new Promise(resolve => {
  4801. const request = this._queueLoadingCallback(resolve);
  4802. this._prepareFontLoadEvent(font, request);
  4803. });
  4804. }
  4805. }
  4806. get isFontLoadingAPISupported() {
  4807. const hasFonts = !!this._document?.fonts;
  4808. return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  4809. }
  4810. get isSyncFontLoadingSupported() {
  4811. let supported = false;
  4812. if (_is_node.isNodeJS) {
  4813. supported = true;
  4814. } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  4815. supported = true;
  4816. }
  4817. return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  4818. }
  4819. _queueLoadingCallback(callback) {
  4820. function completeRequest() {
  4821. (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
  4822. request.done = true;
  4823. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  4824. const otherRequest = loadingRequests.shift();
  4825. setTimeout(otherRequest.callback, 0);
  4826. }
  4827. }
  4828. const {
  4829. loadingRequests
  4830. } = this;
  4831. const request = {
  4832. done: false,
  4833. complete: completeRequest,
  4834. callback
  4835. };
  4836. loadingRequests.push(request);
  4837. return request;
  4838. }
  4839. get _loadTestFont() {
  4840. 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==");
  4841. return (0, _util.shadow)(this, "_loadTestFont", testFont);
  4842. }
  4843. _prepareFontLoadEvent(font, request) {
  4844. function int32(data, offset) {
  4845. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  4846. }
  4847. function spliceString(s, offset, remove, insert) {
  4848. const chunk1 = s.substring(0, offset);
  4849. const chunk2 = s.substring(offset + remove);
  4850. return chunk1 + insert + chunk2;
  4851. }
  4852. let i, ii;
  4853. const canvas = this._document.createElement("canvas");
  4854. canvas.width = 1;
  4855. canvas.height = 1;
  4856. const ctx = canvas.getContext("2d");
  4857. let called = 0;
  4858. function isFontReady(name, callback) {
  4859. if (++called > 30) {
  4860. (0, _util.warn)("Load test font never loaded.");
  4861. callback();
  4862. return;
  4863. }
  4864. ctx.font = "30px " + name;
  4865. ctx.fillText(".", 0, 20);
  4866. const imageData = ctx.getImageData(0, 0, 1, 1);
  4867. if (imageData.data[3] > 0) {
  4868. callback();
  4869. return;
  4870. }
  4871. setTimeout(isFontReady.bind(null, name, callback));
  4872. }
  4873. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  4874. let data = this._loadTestFont;
  4875. const COMMENT_OFFSET = 976;
  4876. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  4877. const CFF_CHECKSUM_OFFSET = 16;
  4878. const XXXX_VALUE = 0x58585858;
  4879. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  4880. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  4881. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  4882. }
  4883. if (i < loadTestFontId.length) {
  4884. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  4885. }
  4886. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
  4887. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  4888. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  4889. this.insertRule(rule);
  4890. const div = this._document.createElement("div");
  4891. div.style.visibility = "hidden";
  4892. div.style.width = div.style.height = "10px";
  4893. div.style.position = "absolute";
  4894. div.style.top = div.style.left = "0px";
  4895. for (const name of [font.loadedName, loadTestFontId]) {
  4896. const span = this._document.createElement("span");
  4897. span.textContent = "Hi";
  4898. span.style.fontFamily = name;
  4899. div.append(span);
  4900. }
  4901. this._document.body.append(div);
  4902. isFontReady(loadTestFontId, () => {
  4903. div.remove();
  4904. request.complete();
  4905. });
  4906. }
  4907. }
  4908. exports.FontLoader = FontLoader;
  4909. class FontFaceObject {
  4910. constructor(translatedData, {
  4911. isEvalSupported = true,
  4912. disableFontFace = false,
  4913. ignoreErrors = false,
  4914. inspectFont = null
  4915. }) {
  4916. this.compiledGlyphs = Object.create(null);
  4917. for (const i in translatedData) {
  4918. this[i] = translatedData[i];
  4919. }
  4920. this.isEvalSupported = isEvalSupported !== false;
  4921. this.disableFontFace = disableFontFace === true;
  4922. this.ignoreErrors = ignoreErrors === true;
  4923. this._inspectFont = inspectFont;
  4924. }
  4925. createNativeFontFace() {
  4926. if (!this.data || this.disableFontFace) {
  4927. return null;
  4928. }
  4929. let nativeFontFace;
  4930. if (!this.cssFontInfo) {
  4931. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  4932. } else {
  4933. const css = {
  4934. weight: this.cssFontInfo.fontWeight
  4935. };
  4936. if (this.cssFontInfo.italicAngle) {
  4937. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  4938. }
  4939. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  4940. }
  4941. this._inspectFont?.(this);
  4942. return nativeFontFace;
  4943. }
  4944. createFontFaceRule() {
  4945. if (!this.data || this.disableFontFace) {
  4946. return null;
  4947. }
  4948. const data = (0, _util.bytesToString)(this.data);
  4949. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  4950. let rule;
  4951. if (!this.cssFontInfo) {
  4952. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  4953. } else {
  4954. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  4955. if (this.cssFontInfo.italicAngle) {
  4956. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  4957. }
  4958. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  4959. }
  4960. this._inspectFont?.(this, url);
  4961. return rule;
  4962. }
  4963. getPathGenerator(objs, character) {
  4964. if (this.compiledGlyphs[character] !== undefined) {
  4965. return this.compiledGlyphs[character];
  4966. }
  4967. let cmds;
  4968. try {
  4969. cmds = objs.get(this.loadedName + "_path_" + character);
  4970. } catch (ex) {
  4971. if (!this.ignoreErrors) {
  4972. throw ex;
  4973. }
  4974. (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
  4975. return this.compiledGlyphs[character] = function (c, size) {};
  4976. }
  4977. if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
  4978. const jsBuf = [];
  4979. for (const current of cmds) {
  4980. const args = current.args !== undefined ? current.args.join(",") : "";
  4981. jsBuf.push("c.", current.cmd, "(", args, ");\n");
  4982. }
  4983. return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
  4984. }
  4985. return this.compiledGlyphs[character] = function (c, size) {
  4986. for (const current of cmds) {
  4987. if (current.cmd === "scale") {
  4988. current.args = [size, -size];
  4989. }
  4990. c[current.cmd].apply(c, current.args);
  4991. }
  4992. };
  4993. }
  4994. }
  4995. exports.FontFaceObject = FontFaceObject;
  4996. /***/ }),
  4997. /* 10 */
  4998. /***/ ((__unused_webpack_module, exports) => {
  4999. Object.defineProperty(exports, "__esModule", ({
  5000. value: true
  5001. }));
  5002. exports.isNodeJS = void 0;
  5003. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  5004. exports.isNodeJS = isNodeJS;
  5005. /***/ }),
  5006. /* 11 */
  5007. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5008. Object.defineProperty(exports, "__esModule", ({
  5009. value: true
  5010. }));
  5011. exports.CanvasGraphics = void 0;
  5012. var _util = __w_pdfjs_require__(1);
  5013. var _display_utils = __w_pdfjs_require__(6);
  5014. var _pattern_helper = __w_pdfjs_require__(12);
  5015. var _image_utils = __w_pdfjs_require__(13);
  5016. var _is_node = __w_pdfjs_require__(10);
  5017. const MIN_FONT_SIZE = 16;
  5018. const MAX_FONT_SIZE = 100;
  5019. const MAX_GROUP_SIZE = 4096;
  5020. const EXECUTION_TIME = 15;
  5021. const EXECUTION_STEPS = 10;
  5022. const MAX_SIZE_TO_COMPILE = 1000;
  5023. const FULL_CHUNK_HEIGHT = 16;
  5024. function mirrorContextOperations(ctx, destCtx) {
  5025. if (ctx._removeMirroring) {
  5026. throw new Error("Context is already forwarding operations.");
  5027. }
  5028. ctx.__originalSave = ctx.save;
  5029. ctx.__originalRestore = ctx.restore;
  5030. ctx.__originalRotate = ctx.rotate;
  5031. ctx.__originalScale = ctx.scale;
  5032. ctx.__originalTranslate = ctx.translate;
  5033. ctx.__originalTransform = ctx.transform;
  5034. ctx.__originalSetTransform = ctx.setTransform;
  5035. ctx.__originalResetTransform = ctx.resetTransform;
  5036. ctx.__originalClip = ctx.clip;
  5037. ctx.__originalMoveTo = ctx.moveTo;
  5038. ctx.__originalLineTo = ctx.lineTo;
  5039. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  5040. ctx.__originalRect = ctx.rect;
  5041. ctx.__originalClosePath = ctx.closePath;
  5042. ctx.__originalBeginPath = ctx.beginPath;
  5043. ctx._removeMirroring = () => {
  5044. ctx.save = ctx.__originalSave;
  5045. ctx.restore = ctx.__originalRestore;
  5046. ctx.rotate = ctx.__originalRotate;
  5047. ctx.scale = ctx.__originalScale;
  5048. ctx.translate = ctx.__originalTranslate;
  5049. ctx.transform = ctx.__originalTransform;
  5050. ctx.setTransform = ctx.__originalSetTransform;
  5051. ctx.resetTransform = ctx.__originalResetTransform;
  5052. ctx.clip = ctx.__originalClip;
  5053. ctx.moveTo = ctx.__originalMoveTo;
  5054. ctx.lineTo = ctx.__originalLineTo;
  5055. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  5056. ctx.rect = ctx.__originalRect;
  5057. ctx.closePath = ctx.__originalClosePath;
  5058. ctx.beginPath = ctx.__originalBeginPath;
  5059. delete ctx._removeMirroring;
  5060. };
  5061. ctx.save = function ctxSave() {
  5062. destCtx.save();
  5063. this.__originalSave();
  5064. };
  5065. ctx.restore = function ctxRestore() {
  5066. destCtx.restore();
  5067. this.__originalRestore();
  5068. };
  5069. ctx.translate = function ctxTranslate(x, y) {
  5070. destCtx.translate(x, y);
  5071. this.__originalTranslate(x, y);
  5072. };
  5073. ctx.scale = function ctxScale(x, y) {
  5074. destCtx.scale(x, y);
  5075. this.__originalScale(x, y);
  5076. };
  5077. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  5078. destCtx.transform(a, b, c, d, e, f);
  5079. this.__originalTransform(a, b, c, d, e, f);
  5080. };
  5081. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  5082. destCtx.setTransform(a, b, c, d, e, f);
  5083. this.__originalSetTransform(a, b, c, d, e, f);
  5084. };
  5085. ctx.resetTransform = function ctxResetTransform() {
  5086. destCtx.resetTransform();
  5087. this.__originalResetTransform();
  5088. };
  5089. ctx.rotate = function ctxRotate(angle) {
  5090. destCtx.rotate(angle);
  5091. this.__originalRotate(angle);
  5092. };
  5093. ctx.clip = function ctxRotate(rule) {
  5094. destCtx.clip(rule);
  5095. this.__originalClip(rule);
  5096. };
  5097. ctx.moveTo = function (x, y) {
  5098. destCtx.moveTo(x, y);
  5099. this.__originalMoveTo(x, y);
  5100. };
  5101. ctx.lineTo = function (x, y) {
  5102. destCtx.lineTo(x, y);
  5103. this.__originalLineTo(x, y);
  5104. };
  5105. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  5106. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  5107. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  5108. };
  5109. ctx.rect = function (x, y, width, height) {
  5110. destCtx.rect(x, y, width, height);
  5111. this.__originalRect(x, y, width, height);
  5112. };
  5113. ctx.closePath = function () {
  5114. destCtx.closePath();
  5115. this.__originalClosePath();
  5116. };
  5117. ctx.beginPath = function () {
  5118. destCtx.beginPath();
  5119. this.__originalBeginPath();
  5120. };
  5121. }
  5122. class CachedCanvases {
  5123. constructor(canvasFactory) {
  5124. this.canvasFactory = canvasFactory;
  5125. this.cache = Object.create(null);
  5126. }
  5127. getCanvas(id, width, height) {
  5128. let canvasEntry;
  5129. if (this.cache[id] !== undefined) {
  5130. canvasEntry = this.cache[id];
  5131. this.canvasFactory.reset(canvasEntry, width, height);
  5132. } else {
  5133. canvasEntry = this.canvasFactory.create(width, height);
  5134. this.cache[id] = canvasEntry;
  5135. }
  5136. return canvasEntry;
  5137. }
  5138. delete(id) {
  5139. delete this.cache[id];
  5140. }
  5141. clear() {
  5142. for (const id in this.cache) {
  5143. const canvasEntry = this.cache[id];
  5144. this.canvasFactory.destroy(canvasEntry);
  5145. delete this.cache[id];
  5146. }
  5147. }
  5148. }
  5149. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  5150. const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  5151. if (b === 0 && c === 0) {
  5152. const tlX = destX * a + tx;
  5153. const rTlX = Math.round(tlX);
  5154. const tlY = destY * d + ty;
  5155. const rTlY = Math.round(tlY);
  5156. const brX = (destX + destW) * a + tx;
  5157. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5158. const brY = (destY + destH) * d + ty;
  5159. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5160. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  5161. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  5162. ctx.setTransform(a, b, c, d, tx, ty);
  5163. return [rWidth, rHeight];
  5164. }
  5165. if (a === 0 && d === 0) {
  5166. const tlX = destY * c + tx;
  5167. const rTlX = Math.round(tlX);
  5168. const tlY = destX * b + ty;
  5169. const rTlY = Math.round(tlY);
  5170. const brX = (destY + destH) * c + tx;
  5171. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  5172. const brY = (destX + destW) * b + ty;
  5173. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  5174. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  5175. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  5176. ctx.setTransform(a, b, c, d, tx, ty);
  5177. return [rHeight, rWidth];
  5178. }
  5179. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  5180. const scaleX = Math.hypot(a, b);
  5181. const scaleY = Math.hypot(c, d);
  5182. return [scaleX * destW, scaleY * destH];
  5183. }
  5184. function compileType3Glyph(imgData) {
  5185. const {
  5186. width,
  5187. height
  5188. } = imgData;
  5189. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  5190. return null;
  5191. }
  5192. const POINT_TO_PROCESS_LIMIT = 1000;
  5193. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  5194. const width1 = width + 1;
  5195. let points = new Uint8Array(width1 * (height + 1));
  5196. let i, j, j0;
  5197. const lineSize = width + 7 & ~7;
  5198. let data = new Uint8Array(lineSize * height),
  5199. pos = 0;
  5200. for (const elem of imgData.data) {
  5201. let mask = 128;
  5202. while (mask > 0) {
  5203. data[pos++] = elem & mask ? 0 : 255;
  5204. mask >>= 1;
  5205. }
  5206. }
  5207. let count = 0;
  5208. pos = 0;
  5209. if (data[pos] !== 0) {
  5210. points[0] = 1;
  5211. ++count;
  5212. }
  5213. for (j = 1; j < width; j++) {
  5214. if (data[pos] !== data[pos + 1]) {
  5215. points[j] = data[pos] ? 2 : 1;
  5216. ++count;
  5217. }
  5218. pos++;
  5219. }
  5220. if (data[pos] !== 0) {
  5221. points[j] = 2;
  5222. ++count;
  5223. }
  5224. for (i = 1; i < height; i++) {
  5225. pos = i * lineSize;
  5226. j0 = i * width1;
  5227. if (data[pos - lineSize] !== data[pos]) {
  5228. points[j0] = data[pos] ? 1 : 8;
  5229. ++count;
  5230. }
  5231. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5232. for (j = 1; j < width; j++) {
  5233. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  5234. if (POINT_TYPES[sum]) {
  5235. points[j0 + j] = POINT_TYPES[sum];
  5236. ++count;
  5237. }
  5238. pos++;
  5239. }
  5240. if (data[pos - lineSize] !== data[pos]) {
  5241. points[j0 + j] = data[pos] ? 2 : 4;
  5242. ++count;
  5243. }
  5244. if (count > POINT_TO_PROCESS_LIMIT) {
  5245. return null;
  5246. }
  5247. }
  5248. pos = lineSize * (height - 1);
  5249. j0 = i * width1;
  5250. if (data[pos] !== 0) {
  5251. points[j0] = 8;
  5252. ++count;
  5253. }
  5254. for (j = 1; j < width; j++) {
  5255. if (data[pos] !== data[pos + 1]) {
  5256. points[j0 + j] = data[pos] ? 4 : 8;
  5257. ++count;
  5258. }
  5259. pos++;
  5260. }
  5261. if (data[pos] !== 0) {
  5262. points[j0 + j] = 4;
  5263. ++count;
  5264. }
  5265. if (count > POINT_TO_PROCESS_LIMIT) {
  5266. return null;
  5267. }
  5268. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5269. const path = new Path2D();
  5270. for (i = 0; count && i <= height; i++) {
  5271. let p = i * width1;
  5272. const end = p + width;
  5273. while (p < end && !points[p]) {
  5274. p++;
  5275. }
  5276. if (p === end) {
  5277. continue;
  5278. }
  5279. path.moveTo(p % width1, i);
  5280. const p0 = p;
  5281. let type = points[p];
  5282. do {
  5283. const step = steps[type];
  5284. do {
  5285. p += step;
  5286. } while (!points[p]);
  5287. const pp = points[p];
  5288. if (pp !== 5 && pp !== 10) {
  5289. type = pp;
  5290. points[p] = 0;
  5291. } else {
  5292. type = pp & 0x33 * type >> 4;
  5293. points[p] &= type >> 2 | type << 2;
  5294. }
  5295. path.lineTo(p % width1, p / width1 | 0);
  5296. if (!points[p]) {
  5297. --count;
  5298. }
  5299. } while (p0 !== p);
  5300. --i;
  5301. }
  5302. data = null;
  5303. points = null;
  5304. const drawOutline = function (c) {
  5305. c.save();
  5306. c.scale(1 / width, -1 / height);
  5307. c.translate(0, -height);
  5308. c.fill(path);
  5309. c.beginPath();
  5310. c.restore();
  5311. };
  5312. return drawOutline;
  5313. }
  5314. class CanvasExtraState {
  5315. constructor(width, height) {
  5316. this.alphaIsShape = false;
  5317. this.fontSize = 0;
  5318. this.fontSizeScale = 1;
  5319. this.textMatrix = _util.IDENTITY_MATRIX;
  5320. this.textMatrixScale = 1;
  5321. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  5322. this.leading = 0;
  5323. this.x = 0;
  5324. this.y = 0;
  5325. this.lineX = 0;
  5326. this.lineY = 0;
  5327. this.charSpacing = 0;
  5328. this.wordSpacing = 0;
  5329. this.textHScale = 1;
  5330. this.textRenderingMode = _util.TextRenderingMode.FILL;
  5331. this.textRise = 0;
  5332. this.fillColor = "#000000";
  5333. this.strokeColor = "#000000";
  5334. this.patternFill = false;
  5335. this.fillAlpha = 1;
  5336. this.strokeAlpha = 1;
  5337. this.lineWidth = 1;
  5338. this.activeSMask = null;
  5339. this.transferMaps = "none";
  5340. this.startNewPathAndClipBox([0, 0, width, height]);
  5341. }
  5342. clone() {
  5343. const clone = Object.create(this);
  5344. clone.clipBox = this.clipBox.slice();
  5345. return clone;
  5346. }
  5347. setCurrentPoint(x, y) {
  5348. this.x = x;
  5349. this.y = y;
  5350. }
  5351. updatePathMinMax(transform, x, y) {
  5352. [x, y] = _util.Util.applyTransform([x, y], transform);
  5353. this.minX = Math.min(this.minX, x);
  5354. this.minY = Math.min(this.minY, y);
  5355. this.maxX = Math.max(this.maxX, x);
  5356. this.maxY = Math.max(this.maxY, y);
  5357. }
  5358. updateRectMinMax(transform, rect) {
  5359. const p1 = _util.Util.applyTransform(rect, transform);
  5360. const p2 = _util.Util.applyTransform(rect.slice(2), transform);
  5361. this.minX = Math.min(this.minX, p1[0], p2[0]);
  5362. this.minY = Math.min(this.minY, p1[1], p2[1]);
  5363. this.maxX = Math.max(this.maxX, p1[0], p2[0]);
  5364. this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  5365. }
  5366. updateScalingPathMinMax(transform, minMax) {
  5367. _util.Util.scaleMinMax(transform, minMax);
  5368. this.minX = Math.min(this.minX, minMax[0]);
  5369. this.maxX = Math.max(this.maxX, minMax[1]);
  5370. this.minY = Math.min(this.minY, minMax[2]);
  5371. this.maxY = Math.max(this.maxY, minMax[3]);
  5372. }
  5373. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  5374. const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
  5375. if (minMax) {
  5376. minMax[0] = Math.min(minMax[0], box[0], box[2]);
  5377. minMax[1] = Math.max(minMax[1], box[0], box[2]);
  5378. minMax[2] = Math.min(minMax[2], box[1], box[3]);
  5379. minMax[3] = Math.max(minMax[3], box[1], box[3]);
  5380. return;
  5381. }
  5382. this.updateRectMinMax(transform, box);
  5383. }
  5384. getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5385. const box = [this.minX, this.minY, this.maxX, this.maxY];
  5386. if (pathType === _pattern_helper.PathType.STROKE) {
  5387. if (!transform) {
  5388. (0, _util.unreachable)("Stroke bounding box must include transform.");
  5389. }
  5390. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5391. const xStrokePad = scale[0] * this.lineWidth / 2;
  5392. const yStrokePad = scale[1] * this.lineWidth / 2;
  5393. box[0] -= xStrokePad;
  5394. box[1] -= yStrokePad;
  5395. box[2] += xStrokePad;
  5396. box[3] += yStrokePad;
  5397. }
  5398. return box;
  5399. }
  5400. updateClipFromPath() {
  5401. const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
  5402. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  5403. }
  5404. isEmptyClip() {
  5405. return this.minX === Infinity;
  5406. }
  5407. startNewPathAndClipBox(box) {
  5408. this.clipBox = box;
  5409. this.minX = Infinity;
  5410. this.minY = Infinity;
  5411. this.maxX = 0;
  5412. this.maxY = 0;
  5413. }
  5414. getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
  5415. return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  5416. }
  5417. }
  5418. function putBinaryImageData(ctx, imgData) {
  5419. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  5420. ctx.putImageData(imgData, 0, 0);
  5421. return;
  5422. }
  5423. const height = imgData.height,
  5424. width = imgData.width;
  5425. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5426. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5427. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5428. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5429. let srcPos = 0,
  5430. destPos;
  5431. const src = imgData.data;
  5432. const dest = chunkImgData.data;
  5433. let i, j, thisChunkHeight, elemsInThisChunk;
  5434. if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
  5435. const srcLength = src.byteLength;
  5436. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  5437. const dest32DataLength = dest32.length;
  5438. const fullSrcDiff = width + 7 >> 3;
  5439. const white = 0xffffffff;
  5440. const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  5441. for (i = 0; i < totalChunks; i++) {
  5442. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5443. destPos = 0;
  5444. for (j = 0; j < thisChunkHeight; j++) {
  5445. const srcDiff = srcLength - srcPos;
  5446. let k = 0;
  5447. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  5448. const kEndUnrolled = kEnd & ~7;
  5449. let mask = 0;
  5450. let srcByte = 0;
  5451. for (; k < kEndUnrolled; k += 8) {
  5452. srcByte = src[srcPos++];
  5453. dest32[destPos++] = srcByte & 128 ? white : black;
  5454. dest32[destPos++] = srcByte & 64 ? white : black;
  5455. dest32[destPos++] = srcByte & 32 ? white : black;
  5456. dest32[destPos++] = srcByte & 16 ? white : black;
  5457. dest32[destPos++] = srcByte & 8 ? white : black;
  5458. dest32[destPos++] = srcByte & 4 ? white : black;
  5459. dest32[destPos++] = srcByte & 2 ? white : black;
  5460. dest32[destPos++] = srcByte & 1 ? white : black;
  5461. }
  5462. for (; k < kEnd; k++) {
  5463. if (mask === 0) {
  5464. srcByte = src[srcPos++];
  5465. mask = 128;
  5466. }
  5467. dest32[destPos++] = srcByte & mask ? white : black;
  5468. mask >>= 1;
  5469. }
  5470. }
  5471. while (destPos < dest32DataLength) {
  5472. dest32[destPos++] = 0;
  5473. }
  5474. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5475. }
  5476. } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
  5477. j = 0;
  5478. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  5479. for (i = 0; i < fullChunks; i++) {
  5480. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5481. srcPos += elemsInThisChunk;
  5482. ctx.putImageData(chunkImgData, 0, j);
  5483. j += FULL_CHUNK_HEIGHT;
  5484. }
  5485. if (i < totalChunks) {
  5486. elemsInThisChunk = width * partialChunkHeight * 4;
  5487. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5488. ctx.putImageData(chunkImgData, 0, j);
  5489. }
  5490. } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
  5491. thisChunkHeight = FULL_CHUNK_HEIGHT;
  5492. elemsInThisChunk = width * thisChunkHeight;
  5493. for (i = 0; i < totalChunks; i++) {
  5494. if (i >= fullChunks) {
  5495. thisChunkHeight = partialChunkHeight;
  5496. elemsInThisChunk = width * thisChunkHeight;
  5497. }
  5498. destPos = 0;
  5499. for (j = elemsInThisChunk; j--;) {
  5500. dest[destPos++] = src[srcPos++];
  5501. dest[destPos++] = src[srcPos++];
  5502. dest[destPos++] = src[srcPos++];
  5503. dest[destPos++] = 255;
  5504. }
  5505. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5506. }
  5507. } else {
  5508. throw new Error(`bad image kind: ${imgData.kind}`);
  5509. }
  5510. }
  5511. function putBinaryImageMask(ctx, imgData) {
  5512. if (imgData.bitmap) {
  5513. ctx.drawImage(imgData.bitmap, 0, 0);
  5514. return;
  5515. }
  5516. const height = imgData.height,
  5517. width = imgData.width;
  5518. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  5519. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  5520. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  5521. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  5522. let srcPos = 0;
  5523. const src = imgData.data;
  5524. const dest = chunkImgData.data;
  5525. for (let i = 0; i < totalChunks; i++) {
  5526. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  5527. ({
  5528. srcPos
  5529. } = (0, _image_utils.convertBlackAndWhiteToRGBA)({
  5530. src,
  5531. srcPos,
  5532. dest,
  5533. width,
  5534. height: thisChunkHeight,
  5535. nonBlackColor: 0
  5536. }));
  5537. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  5538. }
  5539. }
  5540. function copyCtxState(sourceCtx, destCtx) {
  5541. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  5542. for (const property of properties) {
  5543. if (sourceCtx[property] !== undefined) {
  5544. destCtx[property] = sourceCtx[property];
  5545. }
  5546. }
  5547. if (sourceCtx.setLineDash !== undefined) {
  5548. destCtx.setLineDash(sourceCtx.getLineDash());
  5549. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5550. }
  5551. }
  5552. function resetCtxToDefault(ctx) {
  5553. ctx.strokeStyle = ctx.fillStyle = "#000000";
  5554. ctx.fillRule = "nonzero";
  5555. ctx.globalAlpha = 1;
  5556. ctx.lineWidth = 1;
  5557. ctx.lineCap = "butt";
  5558. ctx.lineJoin = "miter";
  5559. ctx.miterLimit = 10;
  5560. ctx.globalCompositeOperation = "source-over";
  5561. ctx.font = "10px sans-serif";
  5562. if (ctx.setLineDash !== undefined) {
  5563. ctx.setLineDash([]);
  5564. ctx.lineDashOffset = 0;
  5565. }
  5566. if (!_is_node.isNodeJS) {
  5567. ctx.filter = "none";
  5568. }
  5569. }
  5570. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  5571. const length = bytes.length;
  5572. for (let i = 3; i < length; i += 4) {
  5573. const alpha = bytes[i];
  5574. if (alpha === 0) {
  5575. bytes[i - 3] = r0;
  5576. bytes[i - 2] = g0;
  5577. bytes[i - 1] = b0;
  5578. } else if (alpha < 255) {
  5579. const alpha_ = 255 - alpha;
  5580. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  5581. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  5582. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  5583. }
  5584. }
  5585. }
  5586. function composeSMaskAlpha(maskData, layerData, transferMap) {
  5587. const length = maskData.length;
  5588. const scale = 1 / 255;
  5589. for (let i = 3; i < length; i += 4) {
  5590. const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  5591. layerData[i] = layerData[i] * alpha * scale | 0;
  5592. }
  5593. }
  5594. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  5595. const length = maskData.length;
  5596. for (let i = 3; i < length; i += 4) {
  5597. const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  5598. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  5599. }
  5600. }
  5601. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  5602. const hasBackdrop = !!backdrop;
  5603. const r0 = hasBackdrop ? backdrop[0] : 0;
  5604. const g0 = hasBackdrop ? backdrop[1] : 0;
  5605. const b0 = hasBackdrop ? backdrop[2] : 0;
  5606. let composeFn;
  5607. if (subtype === "Luminosity") {
  5608. composeFn = composeSMaskLuminosity;
  5609. } else {
  5610. composeFn = composeSMaskAlpha;
  5611. }
  5612. const PIXELS_TO_PROCESS = 1048576;
  5613. const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5614. for (let row = 0; row < height; row += chunkSize) {
  5615. const chunkHeight = Math.min(chunkSize, height - row);
  5616. const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
  5617. const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
  5618. if (hasBackdrop) {
  5619. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  5620. }
  5621. composeFn(maskData.data, layerData.data, transferMap);
  5622. layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  5623. }
  5624. }
  5625. function composeSMask(ctx, smask, layerCtx, layerBox) {
  5626. const layerOffsetX = layerBox[0];
  5627. const layerOffsetY = layerBox[1];
  5628. const layerWidth = layerBox[2] - layerOffsetX;
  5629. const layerHeight = layerBox[3] - layerOffsetY;
  5630. if (layerWidth === 0 || layerHeight === 0) {
  5631. return;
  5632. }
  5633. genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  5634. ctx.save();
  5635. ctx.globalAlpha = 1;
  5636. ctx.globalCompositeOperation = "source-over";
  5637. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5638. ctx.drawImage(layerCtx.canvas, 0, 0);
  5639. ctx.restore();
  5640. }
  5641. function getImageSmoothingEnabled(transform, interpolate) {
  5642. const scale = _util.Util.singularValueDecompose2dScale(transform);
  5643. scale[0] = Math.fround(scale[0]);
  5644. scale[1] = Math.fround(scale[1]);
  5645. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  5646. if (interpolate !== undefined) {
  5647. return interpolate;
  5648. } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
  5649. return true;
  5650. }
  5651. return false;
  5652. }
  5653. const LINE_CAP_STYLES = ["butt", "round", "square"];
  5654. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  5655. const NORMAL_CLIP = {};
  5656. const EO_CLIP = {};
  5657. class CanvasGraphics {
  5658. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  5659. optionalContentConfig,
  5660. markedContentStack = null
  5661. }, annotationCanvasMap) {
  5662. this.ctx = canvasCtx;
  5663. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  5664. this.stateStack = [];
  5665. this.pendingClip = null;
  5666. this.pendingEOFill = false;
  5667. this.res = null;
  5668. this.xobjs = null;
  5669. this.commonObjs = commonObjs;
  5670. this.objs = objs;
  5671. this.canvasFactory = canvasFactory;
  5672. this.filterFactory = filterFactory;
  5673. this.groupStack = [];
  5674. this.processingType3 = null;
  5675. this.baseTransform = null;
  5676. this.baseTransformStack = [];
  5677. this.groupLevel = 0;
  5678. this.smaskStack = [];
  5679. this.smaskCounter = 0;
  5680. this.tempSMask = null;
  5681. this.suspendedCtx = null;
  5682. this.contentVisible = true;
  5683. this.markedContentStack = markedContentStack || [];
  5684. this.optionalContentConfig = optionalContentConfig;
  5685. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  5686. this.cachedPatterns = new Map();
  5687. this.annotationCanvasMap = annotationCanvasMap;
  5688. this.viewportScale = 1;
  5689. this.outputScaleX = 1;
  5690. this.outputScaleY = 1;
  5691. this._cachedScaleForStroking = null;
  5692. this._cachedGetSinglePixelWidth = null;
  5693. this._cachedBitmapsMap = new Map();
  5694. }
  5695. getObject(data, fallback = null) {
  5696. if (typeof data === "string") {
  5697. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  5698. }
  5699. return fallback;
  5700. }
  5701. beginDrawing({
  5702. transform,
  5703. viewport,
  5704. transparency = false,
  5705. background = null
  5706. }) {
  5707. const width = this.ctx.canvas.width;
  5708. const height = this.ctx.canvas.height;
  5709. const savedFillStyle = this.ctx.fillStyle;
  5710. this.ctx.fillStyle = background || "#ffffff";
  5711. this.ctx.fillRect(0, 0, width, height);
  5712. this.ctx.fillStyle = savedFillStyle;
  5713. if (transparency) {
  5714. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  5715. this.compositeCtx = this.ctx;
  5716. this.transparentCanvas = transparentCanvas.canvas;
  5717. this.ctx = transparentCanvas.context;
  5718. this.ctx.save();
  5719. this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
  5720. }
  5721. this.ctx.save();
  5722. resetCtxToDefault(this.ctx);
  5723. if (transform) {
  5724. this.ctx.transform(...transform);
  5725. this.outputScaleX = transform[0];
  5726. this.outputScaleY = transform[0];
  5727. }
  5728. this.ctx.transform(...viewport.transform);
  5729. this.viewportScale = viewport.scale;
  5730. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  5731. }
  5732. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  5733. const argsArray = operatorList.argsArray;
  5734. const fnArray = operatorList.fnArray;
  5735. let i = executionStartIdx || 0;
  5736. const argsArrayLen = argsArray.length;
  5737. if (argsArrayLen === i) {
  5738. return i;
  5739. }
  5740. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  5741. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  5742. let steps = 0;
  5743. const commonObjs = this.commonObjs;
  5744. const objs = this.objs;
  5745. let fnId;
  5746. while (true) {
  5747. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  5748. stepper.breakIt(i, continueCallback);
  5749. return i;
  5750. }
  5751. fnId = fnArray[i];
  5752. if (fnId !== _util.OPS.dependency) {
  5753. this[fnId].apply(this, argsArray[i]);
  5754. } else {
  5755. for (const depObjId of argsArray[i]) {
  5756. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  5757. if (!objsPool.has(depObjId)) {
  5758. objsPool.get(depObjId, continueCallback);
  5759. return i;
  5760. }
  5761. }
  5762. }
  5763. i++;
  5764. if (i === argsArrayLen) {
  5765. return i;
  5766. }
  5767. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  5768. if (Date.now() > endTime) {
  5769. continueCallback();
  5770. return i;
  5771. }
  5772. steps = 0;
  5773. }
  5774. }
  5775. }
  5776. #restoreInitialState() {
  5777. while (this.stateStack.length || this.inSMaskMode) {
  5778. this.restore();
  5779. }
  5780. this.ctx.restore();
  5781. if (this.transparentCanvas) {
  5782. this.ctx = this.compositeCtx;
  5783. this.ctx.save();
  5784. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  5785. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  5786. this.ctx.restore();
  5787. this.transparentCanvas = null;
  5788. }
  5789. }
  5790. endDrawing(pageColors = null) {
  5791. this.#restoreInitialState();
  5792. this.cachedCanvases.clear();
  5793. this.cachedPatterns.clear();
  5794. for (const cache of this._cachedBitmapsMap.values()) {
  5795. for (const canvas of cache.values()) {
  5796. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  5797. canvas.width = canvas.height = 0;
  5798. }
  5799. }
  5800. cache.clear();
  5801. }
  5802. this._cachedBitmapsMap.clear();
  5803. if (pageColors) {
  5804. const hcmFilterId = this.filterFactory.addHCMFilter(pageColors.foreground, pageColors.background);
  5805. if (hcmFilterId !== "none") {
  5806. const savedFilter = this.ctx.filter;
  5807. this.ctx.filter = hcmFilterId;
  5808. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  5809. this.ctx.filter = savedFilter;
  5810. }
  5811. }
  5812. }
  5813. _scaleImage(img, inverseTransform) {
  5814. const width = img.width;
  5815. const height = img.height;
  5816. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  5817. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  5818. let paintWidth = width,
  5819. paintHeight = height;
  5820. let tmpCanvasId = "prescale1";
  5821. let tmpCanvas, tmpCtx;
  5822. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  5823. let newWidth = paintWidth,
  5824. newHeight = paintHeight;
  5825. if (widthScale > 2 && paintWidth > 1) {
  5826. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  5827. widthScale /= paintWidth / newWidth;
  5828. }
  5829. if (heightScale > 2 && paintHeight > 1) {
  5830. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  5831. heightScale /= paintHeight / newHeight;
  5832. }
  5833. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  5834. tmpCtx = tmpCanvas.context;
  5835. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  5836. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  5837. img = tmpCanvas.canvas;
  5838. paintWidth = newWidth;
  5839. paintHeight = newHeight;
  5840. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  5841. }
  5842. return {
  5843. img,
  5844. paintWidth,
  5845. paintHeight
  5846. };
  5847. }
  5848. _createMaskCanvas(img) {
  5849. const ctx = this.ctx;
  5850. const {
  5851. width,
  5852. height
  5853. } = img;
  5854. const fillColor = this.current.fillColor;
  5855. const isPatternFill = this.current.patternFill;
  5856. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  5857. let cache, cacheKey, scaled, maskCanvas;
  5858. if ((img.bitmap || img.data) && img.count > 1) {
  5859. const mainKey = img.bitmap || img.data.buffer;
  5860. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  5861. cache = this._cachedBitmapsMap.get(mainKey);
  5862. if (!cache) {
  5863. cache = new Map();
  5864. this._cachedBitmapsMap.set(mainKey, cache);
  5865. }
  5866. const cachedImage = cache.get(cacheKey);
  5867. if (cachedImage && !isPatternFill) {
  5868. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  5869. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  5870. return {
  5871. canvas: cachedImage,
  5872. offsetX,
  5873. offsetY
  5874. };
  5875. }
  5876. scaled = cachedImage;
  5877. }
  5878. if (!scaled) {
  5879. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  5880. putBinaryImageMask(maskCanvas.context, img);
  5881. }
  5882. let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  5883. maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  5884. const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
  5885. const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
  5886. const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
  5887. const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
  5888. const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
  5889. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  5890. const fillCtx = fillCanvas.context;
  5891. const offsetX = Math.min(cord1[0], cord2[0]);
  5892. const offsetY = Math.min(cord1[1], cord2[1]);
  5893. fillCtx.translate(-offsetX, -offsetY);
  5894. fillCtx.transform(...maskToCanvas);
  5895. if (!scaled) {
  5896. scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
  5897. scaled = scaled.img;
  5898. if (cache && isPatternFill) {
  5899. cache.set(cacheKey, scaled);
  5900. }
  5901. }
  5902. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
  5903. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  5904. fillCtx.globalCompositeOperation = "source-in";
  5905. const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  5906. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
  5907. fillCtx.fillRect(0, 0, width, height);
  5908. if (cache && !isPatternFill) {
  5909. this.cachedCanvases.delete("fillCanvas");
  5910. cache.set(cacheKey, fillCanvas.canvas);
  5911. }
  5912. return {
  5913. canvas: fillCanvas.canvas,
  5914. offsetX: Math.round(offsetX),
  5915. offsetY: Math.round(offsetY)
  5916. };
  5917. }
  5918. setLineWidth(width) {
  5919. if (width !== this.current.lineWidth) {
  5920. this._cachedScaleForStroking = null;
  5921. }
  5922. this.current.lineWidth = width;
  5923. this.ctx.lineWidth = width;
  5924. }
  5925. setLineCap(style) {
  5926. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5927. }
  5928. setLineJoin(style) {
  5929. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5930. }
  5931. setMiterLimit(limit) {
  5932. this.ctx.miterLimit = limit;
  5933. }
  5934. setDash(dashArray, dashPhase) {
  5935. const ctx = this.ctx;
  5936. if (ctx.setLineDash !== undefined) {
  5937. ctx.setLineDash(dashArray);
  5938. ctx.lineDashOffset = dashPhase;
  5939. }
  5940. }
  5941. setRenderingIntent(intent) {}
  5942. setFlatness(flatness) {}
  5943. setGState(states) {
  5944. for (const [key, value] of states) {
  5945. switch (key) {
  5946. case "LW":
  5947. this.setLineWidth(value);
  5948. break;
  5949. case "LC":
  5950. this.setLineCap(value);
  5951. break;
  5952. case "LJ":
  5953. this.setLineJoin(value);
  5954. break;
  5955. case "ML":
  5956. this.setMiterLimit(value);
  5957. break;
  5958. case "D":
  5959. this.setDash(value[0], value[1]);
  5960. break;
  5961. case "RI":
  5962. this.setRenderingIntent(value);
  5963. break;
  5964. case "FL":
  5965. this.setFlatness(value);
  5966. break;
  5967. case "Font":
  5968. this.setFont(value[0], value[1]);
  5969. break;
  5970. case "CA":
  5971. this.current.strokeAlpha = value;
  5972. break;
  5973. case "ca":
  5974. this.current.fillAlpha = value;
  5975. this.ctx.globalAlpha = value;
  5976. break;
  5977. case "BM":
  5978. this.ctx.globalCompositeOperation = value;
  5979. break;
  5980. case "SMask":
  5981. this.current.activeSMask = value ? this.tempSMask : null;
  5982. this.tempSMask = null;
  5983. this.checkSMaskState();
  5984. break;
  5985. case "TR":
  5986. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  5987. break;
  5988. }
  5989. }
  5990. }
  5991. get inSMaskMode() {
  5992. return !!this.suspendedCtx;
  5993. }
  5994. checkSMaskState() {
  5995. const inSMaskMode = this.inSMaskMode;
  5996. if (this.current.activeSMask && !inSMaskMode) {
  5997. this.beginSMaskMode();
  5998. } else if (!this.current.activeSMask && inSMaskMode) {
  5999. this.endSMaskMode();
  6000. }
  6001. }
  6002. beginSMaskMode() {
  6003. if (this.inSMaskMode) {
  6004. throw new Error("beginSMaskMode called while already in smask mode");
  6005. }
  6006. const drawnWidth = this.ctx.canvas.width;
  6007. const drawnHeight = this.ctx.canvas.height;
  6008. const cacheId = "smaskGroupAt" + this.groupLevel;
  6009. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  6010. this.suspendedCtx = this.ctx;
  6011. this.ctx = scratchCanvas.context;
  6012. const ctx = this.ctx;
  6013. ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
  6014. copyCtxState(this.suspendedCtx, ctx);
  6015. mirrorContextOperations(ctx, this.suspendedCtx);
  6016. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6017. }
  6018. endSMaskMode() {
  6019. if (!this.inSMaskMode) {
  6020. throw new Error("endSMaskMode called while not in smask mode");
  6021. }
  6022. this.ctx._removeMirroring();
  6023. copyCtxState(this.ctx, this.suspendedCtx);
  6024. this.ctx = this.suspendedCtx;
  6025. this.suspendedCtx = null;
  6026. }
  6027. compose(dirtyBox) {
  6028. if (!this.current.activeSMask) {
  6029. return;
  6030. }
  6031. if (!dirtyBox) {
  6032. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  6033. } else {
  6034. dirtyBox[0] = Math.floor(dirtyBox[0]);
  6035. dirtyBox[1] = Math.floor(dirtyBox[1]);
  6036. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  6037. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  6038. }
  6039. const smask = this.current.activeSMask;
  6040. const suspendedCtx = this.suspendedCtx;
  6041. composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  6042. this.ctx.save();
  6043. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  6044. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  6045. this.ctx.restore();
  6046. }
  6047. save() {
  6048. if (this.inSMaskMode) {
  6049. copyCtxState(this.ctx, this.suspendedCtx);
  6050. this.suspendedCtx.save();
  6051. } else {
  6052. this.ctx.save();
  6053. }
  6054. const old = this.current;
  6055. this.stateStack.push(old);
  6056. this.current = old.clone();
  6057. }
  6058. restore() {
  6059. if (this.stateStack.length === 0 && this.inSMaskMode) {
  6060. this.endSMaskMode();
  6061. }
  6062. if (this.stateStack.length !== 0) {
  6063. this.current = this.stateStack.pop();
  6064. if (this.inSMaskMode) {
  6065. this.suspendedCtx.restore();
  6066. copyCtxState(this.suspendedCtx, this.ctx);
  6067. } else {
  6068. this.ctx.restore();
  6069. }
  6070. this.checkSMaskState();
  6071. this.pendingClip = null;
  6072. this._cachedScaleForStroking = null;
  6073. this._cachedGetSinglePixelWidth = null;
  6074. }
  6075. }
  6076. transform(a, b, c, d, e, f) {
  6077. this.ctx.transform(a, b, c, d, e, f);
  6078. this._cachedScaleForStroking = null;
  6079. this._cachedGetSinglePixelWidth = null;
  6080. }
  6081. constructPath(ops, args, minMax) {
  6082. const ctx = this.ctx;
  6083. const current = this.current;
  6084. let x = current.x,
  6085. y = current.y;
  6086. let startX, startY;
  6087. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6088. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  6089. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  6090. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6091. switch (ops[i] | 0) {
  6092. case _util.OPS.rectangle:
  6093. x = args[j++];
  6094. y = args[j++];
  6095. const width = args[j++];
  6096. const height = args[j++];
  6097. const xw = x + width;
  6098. const yh = y + height;
  6099. ctx.moveTo(x, y);
  6100. if (width === 0 || height === 0) {
  6101. ctx.lineTo(xw, yh);
  6102. } else {
  6103. ctx.lineTo(xw, y);
  6104. ctx.lineTo(xw, yh);
  6105. ctx.lineTo(x, yh);
  6106. }
  6107. if (!isScalingMatrix) {
  6108. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  6109. }
  6110. ctx.closePath();
  6111. break;
  6112. case _util.OPS.moveTo:
  6113. x = args[j++];
  6114. y = args[j++];
  6115. ctx.moveTo(x, y);
  6116. if (!isScalingMatrix) {
  6117. current.updatePathMinMax(currentTransform, x, y);
  6118. }
  6119. break;
  6120. case _util.OPS.lineTo:
  6121. x = args[j++];
  6122. y = args[j++];
  6123. ctx.lineTo(x, y);
  6124. if (!isScalingMatrix) {
  6125. current.updatePathMinMax(currentTransform, x, y);
  6126. }
  6127. break;
  6128. case _util.OPS.curveTo:
  6129. startX = x;
  6130. startY = y;
  6131. x = args[j + 4];
  6132. y = args[j + 5];
  6133. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  6134. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  6135. j += 6;
  6136. break;
  6137. case _util.OPS.curveTo2:
  6138. startX = x;
  6139. startY = y;
  6140. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  6141. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  6142. x = args[j + 2];
  6143. y = args[j + 3];
  6144. j += 4;
  6145. break;
  6146. case _util.OPS.curveTo3:
  6147. startX = x;
  6148. startY = y;
  6149. x = args[j + 2];
  6150. y = args[j + 3];
  6151. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6152. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  6153. j += 4;
  6154. break;
  6155. case _util.OPS.closePath:
  6156. ctx.closePath();
  6157. break;
  6158. }
  6159. }
  6160. if (isScalingMatrix) {
  6161. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  6162. }
  6163. current.setCurrentPoint(x, y);
  6164. }
  6165. closePath() {
  6166. this.ctx.closePath();
  6167. }
  6168. stroke(consumePath = true) {
  6169. const ctx = this.ctx;
  6170. const strokeColor = this.current.strokeColor;
  6171. ctx.globalAlpha = this.current.strokeAlpha;
  6172. if (this.contentVisible) {
  6173. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  6174. ctx.save();
  6175. ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
  6176. this.rescaleAndStroke(false);
  6177. ctx.restore();
  6178. } else {
  6179. this.rescaleAndStroke(true);
  6180. }
  6181. }
  6182. if (consumePath) {
  6183. this.consumePath(this.current.getClippedPathBoundingBox());
  6184. }
  6185. ctx.globalAlpha = this.current.fillAlpha;
  6186. }
  6187. closeStroke() {
  6188. this.closePath();
  6189. this.stroke();
  6190. }
  6191. fill(consumePath = true) {
  6192. const ctx = this.ctx;
  6193. const fillColor = this.current.fillColor;
  6194. const isPatternFill = this.current.patternFill;
  6195. let needRestore = false;
  6196. if (isPatternFill) {
  6197. ctx.save();
  6198. ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6199. needRestore = true;
  6200. }
  6201. const intersect = this.current.getClippedPathBoundingBox();
  6202. if (this.contentVisible && intersect !== null) {
  6203. if (this.pendingEOFill) {
  6204. ctx.fill("evenodd");
  6205. this.pendingEOFill = false;
  6206. } else {
  6207. ctx.fill();
  6208. }
  6209. }
  6210. if (needRestore) {
  6211. ctx.restore();
  6212. }
  6213. if (consumePath) {
  6214. this.consumePath(intersect);
  6215. }
  6216. }
  6217. eoFill() {
  6218. this.pendingEOFill = true;
  6219. this.fill();
  6220. }
  6221. fillStroke() {
  6222. this.fill(false);
  6223. this.stroke(false);
  6224. this.consumePath();
  6225. }
  6226. eoFillStroke() {
  6227. this.pendingEOFill = true;
  6228. this.fillStroke();
  6229. }
  6230. closeFillStroke() {
  6231. this.closePath();
  6232. this.fillStroke();
  6233. }
  6234. closeEOFillStroke() {
  6235. this.pendingEOFill = true;
  6236. this.closePath();
  6237. this.fillStroke();
  6238. }
  6239. endPath() {
  6240. this.consumePath();
  6241. }
  6242. clip() {
  6243. this.pendingClip = NORMAL_CLIP;
  6244. }
  6245. eoClip() {
  6246. this.pendingClip = EO_CLIP;
  6247. }
  6248. beginText() {
  6249. this.current.textMatrix = _util.IDENTITY_MATRIX;
  6250. this.current.textMatrixScale = 1;
  6251. this.current.x = this.current.lineX = 0;
  6252. this.current.y = this.current.lineY = 0;
  6253. }
  6254. endText() {
  6255. const paths = this.pendingTextPaths;
  6256. const ctx = this.ctx;
  6257. if (paths === undefined) {
  6258. ctx.beginPath();
  6259. return;
  6260. }
  6261. ctx.save();
  6262. ctx.beginPath();
  6263. for (const path of paths) {
  6264. ctx.setTransform(...path.transform);
  6265. ctx.translate(path.x, path.y);
  6266. path.addToPath(ctx, path.fontSize);
  6267. }
  6268. ctx.restore();
  6269. ctx.clip();
  6270. ctx.beginPath();
  6271. delete this.pendingTextPaths;
  6272. }
  6273. setCharSpacing(spacing) {
  6274. this.current.charSpacing = spacing;
  6275. }
  6276. setWordSpacing(spacing) {
  6277. this.current.wordSpacing = spacing;
  6278. }
  6279. setHScale(scale) {
  6280. this.current.textHScale = scale / 100;
  6281. }
  6282. setLeading(leading) {
  6283. this.current.leading = -leading;
  6284. }
  6285. setFont(fontRefName, size) {
  6286. const fontObj = this.commonObjs.get(fontRefName);
  6287. const current = this.current;
  6288. if (!fontObj) {
  6289. throw new Error(`Can't find font for ${fontRefName}`);
  6290. }
  6291. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6292. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6293. (0, _util.warn)("Invalid font matrix for font " + fontRefName);
  6294. }
  6295. if (size < 0) {
  6296. size = -size;
  6297. current.fontDirection = -1;
  6298. } else {
  6299. current.fontDirection = 1;
  6300. }
  6301. this.current.font = fontObj;
  6302. this.current.fontSize = size;
  6303. if (fontObj.isType3Font) {
  6304. return;
  6305. }
  6306. const name = fontObj.loadedName || "sans-serif";
  6307. let bold = "normal";
  6308. if (fontObj.black) {
  6309. bold = "900";
  6310. } else if (fontObj.bold) {
  6311. bold = "bold";
  6312. }
  6313. const italic = fontObj.italic ? "italic" : "normal";
  6314. const typeface = `"${name}", ${fontObj.fallbackName}`;
  6315. let browserFontSize = size;
  6316. if (size < MIN_FONT_SIZE) {
  6317. browserFontSize = MIN_FONT_SIZE;
  6318. } else if (size > MAX_FONT_SIZE) {
  6319. browserFontSize = MAX_FONT_SIZE;
  6320. }
  6321. this.current.fontSizeScale = size / browserFontSize;
  6322. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  6323. }
  6324. setTextRenderingMode(mode) {
  6325. this.current.textRenderingMode = mode;
  6326. }
  6327. setTextRise(rise) {
  6328. this.current.textRise = rise;
  6329. }
  6330. moveText(x, y) {
  6331. this.current.x = this.current.lineX += x;
  6332. this.current.y = this.current.lineY += y;
  6333. }
  6334. setLeadingMoveText(x, y) {
  6335. this.setLeading(-y);
  6336. this.moveText(x, y);
  6337. }
  6338. setTextMatrix(a, b, c, d, e, f) {
  6339. this.current.textMatrix = [a, b, c, d, e, f];
  6340. this.current.textMatrixScale = Math.hypot(a, b);
  6341. this.current.x = this.current.lineX = 0;
  6342. this.current.y = this.current.lineY = 0;
  6343. }
  6344. nextLine() {
  6345. this.moveText(0, this.current.leading);
  6346. }
  6347. paintChar(character, x, y, patternTransform) {
  6348. const ctx = this.ctx;
  6349. const current = this.current;
  6350. const font = current.font;
  6351. const textRenderingMode = current.textRenderingMode;
  6352. const fontSize = current.fontSize / current.fontSizeScale;
  6353. const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6354. const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  6355. const patternFill = current.patternFill && !font.missingFile;
  6356. let addToPath;
  6357. if (font.disableFontFace || isAddToPathSet || patternFill) {
  6358. addToPath = font.getPathGenerator(this.commonObjs, character);
  6359. }
  6360. if (font.disableFontFace || patternFill) {
  6361. ctx.save();
  6362. ctx.translate(x, y);
  6363. ctx.beginPath();
  6364. addToPath(ctx, fontSize);
  6365. if (patternTransform) {
  6366. ctx.setTransform(...patternTransform);
  6367. }
  6368. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6369. ctx.fill();
  6370. }
  6371. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6372. ctx.stroke();
  6373. }
  6374. ctx.restore();
  6375. } else {
  6376. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6377. ctx.fillText(character, x, y);
  6378. }
  6379. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6380. ctx.strokeText(character, x, y);
  6381. }
  6382. }
  6383. if (isAddToPathSet) {
  6384. const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6385. paths.push({
  6386. transform: (0, _display_utils.getCurrentTransform)(ctx),
  6387. x,
  6388. y,
  6389. fontSize,
  6390. addToPath
  6391. });
  6392. }
  6393. }
  6394. get isFontSubpixelAAEnabled() {
  6395. const {
  6396. context: ctx
  6397. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  6398. ctx.scale(1.5, 1);
  6399. ctx.fillText("I", 0, 10);
  6400. const data = ctx.getImageData(0, 0, 10, 10).data;
  6401. let enabled = false;
  6402. for (let i = 3; i < data.length; i += 4) {
  6403. if (data[i] > 0 && data[i] < 255) {
  6404. enabled = true;
  6405. break;
  6406. }
  6407. }
  6408. return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  6409. }
  6410. showText(glyphs) {
  6411. const current = this.current;
  6412. const font = current.font;
  6413. if (font.isType3Font) {
  6414. return this.showType3Text(glyphs);
  6415. }
  6416. const fontSize = current.fontSize;
  6417. if (fontSize === 0) {
  6418. return undefined;
  6419. }
  6420. const ctx = this.ctx;
  6421. const fontSizeScale = current.fontSizeScale;
  6422. const charSpacing = current.charSpacing;
  6423. const wordSpacing = current.wordSpacing;
  6424. const fontDirection = current.fontDirection;
  6425. const textHScale = current.textHScale * fontDirection;
  6426. const glyphsLength = glyphs.length;
  6427. const vertical = font.vertical;
  6428. const spacingDir = vertical ? 1 : -1;
  6429. const defaultVMetrics = font.defaultVMetrics;
  6430. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  6431. const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  6432. ctx.save();
  6433. ctx.transform(...current.textMatrix);
  6434. ctx.translate(current.x, current.y + current.textRise);
  6435. if (fontDirection > 0) {
  6436. ctx.scale(textHScale, -1);
  6437. } else {
  6438. ctx.scale(textHScale, 1);
  6439. }
  6440. let patternTransform;
  6441. if (current.patternFill) {
  6442. ctx.save();
  6443. const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
  6444. patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6445. ctx.restore();
  6446. ctx.fillStyle = pattern;
  6447. }
  6448. let lineWidth = current.lineWidth;
  6449. const scale = current.textMatrixScale;
  6450. if (scale === 0 || lineWidth === 0) {
  6451. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  6452. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  6453. lineWidth = this.getSinglePixelWidth();
  6454. }
  6455. } else {
  6456. lineWidth /= scale;
  6457. }
  6458. if (fontSizeScale !== 1.0) {
  6459. ctx.scale(fontSizeScale, fontSizeScale);
  6460. lineWidth /= fontSizeScale;
  6461. }
  6462. ctx.lineWidth = lineWidth;
  6463. if (font.isInvalidPDFjsFont) {
  6464. const chars = [];
  6465. let width = 0;
  6466. for (const glyph of glyphs) {
  6467. chars.push(glyph.unicode);
  6468. width += glyph.width;
  6469. }
  6470. ctx.fillText(chars.join(""), 0, 0);
  6471. current.x += width * widthAdvanceScale * textHScale;
  6472. ctx.restore();
  6473. this.compose();
  6474. return undefined;
  6475. }
  6476. let x = 0,
  6477. i;
  6478. for (i = 0; i < glyphsLength; ++i) {
  6479. const glyph = glyphs[i];
  6480. if (typeof glyph === "number") {
  6481. x += spacingDir * glyph * fontSize / 1000;
  6482. continue;
  6483. }
  6484. let restoreNeeded = false;
  6485. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6486. const character = glyph.fontChar;
  6487. const accent = glyph.accent;
  6488. let scaledX, scaledY;
  6489. let width = glyph.width;
  6490. if (vertical) {
  6491. const vmetric = glyph.vmetric || defaultVMetrics;
  6492. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  6493. const vy = vmetric[2] * widthAdvanceScale;
  6494. width = vmetric ? -vmetric[0] : width;
  6495. scaledX = vx / fontSizeScale;
  6496. scaledY = (x + vy) / fontSizeScale;
  6497. } else {
  6498. scaledX = x / fontSizeScale;
  6499. scaledY = 0;
  6500. }
  6501. if (font.remeasure && width > 0) {
  6502. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6503. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6504. const characterScaleX = width / measuredWidth;
  6505. restoreNeeded = true;
  6506. ctx.save();
  6507. ctx.scale(characterScaleX, 1);
  6508. scaledX /= characterScaleX;
  6509. } else if (width !== measuredWidth) {
  6510. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6511. }
  6512. }
  6513. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  6514. if (simpleFillText && !accent) {
  6515. ctx.fillText(character, scaledX, scaledY);
  6516. } else {
  6517. this.paintChar(character, scaledX, scaledY, patternTransform);
  6518. if (accent) {
  6519. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  6520. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  6521. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  6522. }
  6523. }
  6524. }
  6525. let charWidth;
  6526. if (vertical) {
  6527. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  6528. } else {
  6529. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6530. }
  6531. x += charWidth;
  6532. if (restoreNeeded) {
  6533. ctx.restore();
  6534. }
  6535. }
  6536. if (vertical) {
  6537. current.y -= x;
  6538. } else {
  6539. current.x += x * textHScale;
  6540. }
  6541. ctx.restore();
  6542. this.compose();
  6543. return undefined;
  6544. }
  6545. showType3Text(glyphs) {
  6546. const ctx = this.ctx;
  6547. const current = this.current;
  6548. const font = current.font;
  6549. const fontSize = current.fontSize;
  6550. const fontDirection = current.fontDirection;
  6551. const spacingDir = font.vertical ? 1 : -1;
  6552. const charSpacing = current.charSpacing;
  6553. const wordSpacing = current.wordSpacing;
  6554. const textHScale = current.textHScale * fontDirection;
  6555. const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  6556. const glyphsLength = glyphs.length;
  6557. const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
  6558. let i, glyph, width, spacingLength;
  6559. if (isTextInvisible || fontSize === 0) {
  6560. return;
  6561. }
  6562. this._cachedScaleForStroking = null;
  6563. this._cachedGetSinglePixelWidth = null;
  6564. ctx.save();
  6565. ctx.transform(...current.textMatrix);
  6566. ctx.translate(current.x, current.y);
  6567. ctx.scale(textHScale, fontDirection);
  6568. for (i = 0; i < glyphsLength; ++i) {
  6569. glyph = glyphs[i];
  6570. if (typeof glyph === "number") {
  6571. spacingLength = spacingDir * glyph * fontSize / 1000;
  6572. this.ctx.translate(spacingLength, 0);
  6573. current.x += spacingLength * textHScale;
  6574. continue;
  6575. }
  6576. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6577. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  6578. if (!operatorList) {
  6579. (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
  6580. continue;
  6581. }
  6582. if (this.contentVisible) {
  6583. this.processingType3 = glyph;
  6584. this.save();
  6585. ctx.scale(fontSize, fontSize);
  6586. ctx.transform(...fontMatrix);
  6587. this.executeOperatorList(operatorList);
  6588. this.restore();
  6589. }
  6590. const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
  6591. width = transformed[0] * fontSize + spacing;
  6592. ctx.translate(width, 0);
  6593. current.x += width * textHScale;
  6594. }
  6595. ctx.restore();
  6596. this.processingType3 = null;
  6597. }
  6598. setCharWidth(xWidth, yWidth) {}
  6599. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  6600. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  6601. this.ctx.clip();
  6602. this.endPath();
  6603. }
  6604. getColorN_Pattern(IR) {
  6605. let pattern;
  6606. if (IR[0] === "TilingPattern") {
  6607. const color = IR[1];
  6608. const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
  6609. const canvasGraphicsFactory = {
  6610. createCanvasGraphics: ctx => {
  6611. return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  6612. optionalContentConfig: this.optionalContentConfig,
  6613. markedContentStack: this.markedContentStack
  6614. });
  6615. }
  6616. };
  6617. pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  6618. } else {
  6619. pattern = this._getPattern(IR[1], IR[2]);
  6620. }
  6621. return pattern;
  6622. }
  6623. setStrokeColorN() {
  6624. this.current.strokeColor = this.getColorN_Pattern(arguments);
  6625. }
  6626. setFillColorN() {
  6627. this.current.fillColor = this.getColorN_Pattern(arguments);
  6628. this.current.patternFill = true;
  6629. }
  6630. setStrokeRGBColor(r, g, b) {
  6631. const color = _util.Util.makeHexColor(r, g, b);
  6632. this.ctx.strokeStyle = color;
  6633. this.current.strokeColor = color;
  6634. }
  6635. setFillRGBColor(r, g, b) {
  6636. const color = _util.Util.makeHexColor(r, g, b);
  6637. this.ctx.fillStyle = color;
  6638. this.current.fillColor = color;
  6639. this.current.patternFill = false;
  6640. }
  6641. _getPattern(objId, matrix = null) {
  6642. let pattern;
  6643. if (this.cachedPatterns.has(objId)) {
  6644. pattern = this.cachedPatterns.get(objId);
  6645. } else {
  6646. pattern = (0, _pattern_helper.getShadingPattern)(this.getObject(objId));
  6647. this.cachedPatterns.set(objId, pattern);
  6648. }
  6649. if (matrix) {
  6650. pattern.matrix = matrix;
  6651. }
  6652. return pattern;
  6653. }
  6654. shadingFill(objId) {
  6655. if (!this.contentVisible) {
  6656. return;
  6657. }
  6658. const ctx = this.ctx;
  6659. this.save();
  6660. const pattern = this._getPattern(objId);
  6661. ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
  6662. const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
  6663. if (inv) {
  6664. const canvas = ctx.canvas;
  6665. const width = canvas.width;
  6666. const height = canvas.height;
  6667. const bl = _util.Util.applyTransform([0, 0], inv);
  6668. const br = _util.Util.applyTransform([0, height], inv);
  6669. const ul = _util.Util.applyTransform([width, 0], inv);
  6670. const ur = _util.Util.applyTransform([width, height], inv);
  6671. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6672. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6673. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6674. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6675. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6676. } else {
  6677. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6678. }
  6679. this.compose(this.current.getClippedPathBoundingBox());
  6680. this.restore();
  6681. }
  6682. beginInlineImage() {
  6683. (0, _util.unreachable)("Should not call beginInlineImage");
  6684. }
  6685. beginImageData() {
  6686. (0, _util.unreachable)("Should not call beginImageData");
  6687. }
  6688. paintFormXObjectBegin(matrix, bbox) {
  6689. if (!this.contentVisible) {
  6690. return;
  6691. }
  6692. this.save();
  6693. this.baseTransformStack.push(this.baseTransform);
  6694. if (Array.isArray(matrix) && matrix.length === 6) {
  6695. this.transform(...matrix);
  6696. }
  6697. this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  6698. if (bbox) {
  6699. const width = bbox[2] - bbox[0];
  6700. const height = bbox[3] - bbox[1];
  6701. this.ctx.rect(bbox[0], bbox[1], width, height);
  6702. this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
  6703. this.clip();
  6704. this.endPath();
  6705. }
  6706. }
  6707. paintFormXObjectEnd() {
  6708. if (!this.contentVisible) {
  6709. return;
  6710. }
  6711. this.restore();
  6712. this.baseTransform = this.baseTransformStack.pop();
  6713. }
  6714. beginGroup(group) {
  6715. if (!this.contentVisible) {
  6716. return;
  6717. }
  6718. this.save();
  6719. if (this.inSMaskMode) {
  6720. this.endSMaskMode();
  6721. this.current.activeSMask = null;
  6722. }
  6723. const currentCtx = this.ctx;
  6724. if (!group.isolated) {
  6725. (0, _util.info)("TODO: Support non-isolated groups.");
  6726. }
  6727. if (group.knockout) {
  6728. (0, _util.warn)("Knockout groups not supported.");
  6729. }
  6730. const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
  6731. if (group.matrix) {
  6732. currentCtx.transform(...group.matrix);
  6733. }
  6734. if (!group.bbox) {
  6735. throw new Error("Bounding box is required.");
  6736. }
  6737. let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
  6738. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  6739. bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6740. const offsetX = Math.floor(bounds[0]);
  6741. const offsetY = Math.floor(bounds[1]);
  6742. let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6743. let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6744. let scaleX = 1,
  6745. scaleY = 1;
  6746. if (drawnWidth > MAX_GROUP_SIZE) {
  6747. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6748. drawnWidth = MAX_GROUP_SIZE;
  6749. }
  6750. if (drawnHeight > MAX_GROUP_SIZE) {
  6751. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6752. drawnHeight = MAX_GROUP_SIZE;
  6753. }
  6754. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  6755. let cacheId = "groupAt" + this.groupLevel;
  6756. if (group.smask) {
  6757. cacheId += "_smask_" + this.smaskCounter++ % 2;
  6758. }
  6759. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  6760. const groupCtx = scratchCanvas.context;
  6761. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6762. groupCtx.translate(-offsetX, -offsetY);
  6763. groupCtx.transform(...currentTransform);
  6764. if (group.smask) {
  6765. this.smaskStack.push({
  6766. canvas: scratchCanvas.canvas,
  6767. context: groupCtx,
  6768. offsetX,
  6769. offsetY,
  6770. scaleX,
  6771. scaleY,
  6772. subtype: group.smask.subtype,
  6773. backdrop: group.smask.backdrop,
  6774. transferMap: group.smask.transferMap || null,
  6775. startTransformInverse: null
  6776. });
  6777. } else {
  6778. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6779. currentCtx.translate(offsetX, offsetY);
  6780. currentCtx.scale(scaleX, scaleY);
  6781. currentCtx.save();
  6782. }
  6783. copyCtxState(currentCtx, groupCtx);
  6784. this.ctx = groupCtx;
  6785. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  6786. this.groupStack.push(currentCtx);
  6787. this.groupLevel++;
  6788. }
  6789. endGroup(group) {
  6790. if (!this.contentVisible) {
  6791. return;
  6792. }
  6793. this.groupLevel--;
  6794. const groupCtx = this.ctx;
  6795. const ctx = this.groupStack.pop();
  6796. this.ctx = ctx;
  6797. this.ctx.imageSmoothingEnabled = false;
  6798. if (group.smask) {
  6799. this.tempSMask = this.smaskStack.pop();
  6800. this.restore();
  6801. } else {
  6802. this.ctx.restore();
  6803. const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
  6804. this.restore();
  6805. this.ctx.save();
  6806. this.ctx.setTransform(...currentMtx);
  6807. const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  6808. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6809. this.ctx.restore();
  6810. this.compose(dirtyBox);
  6811. }
  6812. }
  6813. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  6814. this.#restoreInitialState();
  6815. resetCtxToDefault(this.ctx);
  6816. this.ctx.save();
  6817. this.save();
  6818. if (this.baseTransform) {
  6819. this.ctx.setTransform(...this.baseTransform);
  6820. }
  6821. if (Array.isArray(rect) && rect.length === 4) {
  6822. const width = rect[2] - rect[0];
  6823. const height = rect[3] - rect[1];
  6824. if (hasOwnCanvas && this.annotationCanvasMap) {
  6825. transform = transform.slice();
  6826. transform[4] -= rect[0];
  6827. transform[5] -= rect[1];
  6828. rect = rect.slice();
  6829. rect[0] = rect[1] = 0;
  6830. rect[2] = width;
  6831. rect[3] = height;
  6832. const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
  6833. const {
  6834. viewportScale
  6835. } = this;
  6836. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  6837. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  6838. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  6839. const {
  6840. canvas,
  6841. context
  6842. } = this.annotationCanvas;
  6843. this.annotationCanvasMap.set(id, canvas);
  6844. this.annotationCanvas.savedCtx = this.ctx;
  6845. this.ctx = context;
  6846. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  6847. resetCtxToDefault(this.ctx);
  6848. } else {
  6849. resetCtxToDefault(this.ctx);
  6850. this.ctx.rect(rect[0], rect[1], width, height);
  6851. this.ctx.clip();
  6852. this.endPath();
  6853. }
  6854. }
  6855. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  6856. this.transform(...transform);
  6857. this.transform(...matrix);
  6858. }
  6859. endAnnotation() {
  6860. if (this.annotationCanvas) {
  6861. this.ctx = this.annotationCanvas.savedCtx;
  6862. delete this.annotationCanvas.savedCtx;
  6863. delete this.annotationCanvas;
  6864. }
  6865. }
  6866. paintImageMaskXObject(img) {
  6867. if (!this.contentVisible) {
  6868. return;
  6869. }
  6870. const count = img.count;
  6871. img = this.getObject(img.data, img);
  6872. img.count = count;
  6873. const ctx = this.ctx;
  6874. const glyph = this.processingType3;
  6875. if (glyph) {
  6876. if (glyph.compiled === undefined) {
  6877. glyph.compiled = compileType3Glyph(img);
  6878. }
  6879. if (glyph.compiled) {
  6880. glyph.compiled(ctx);
  6881. return;
  6882. }
  6883. }
  6884. const mask = this._createMaskCanvas(img);
  6885. const maskCanvas = mask.canvas;
  6886. ctx.save();
  6887. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6888. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  6889. ctx.restore();
  6890. this.compose();
  6891. }
  6892. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  6893. if (!this.contentVisible) {
  6894. return;
  6895. }
  6896. img = this.getObject(img.data, img);
  6897. const ctx = this.ctx;
  6898. ctx.save();
  6899. const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
  6900. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  6901. const mask = this._createMaskCanvas(img);
  6902. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  6903. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6904. const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  6905. const [x, y] = _util.Util.applyTransform([0, 0], trans);
  6906. ctx.drawImage(mask.canvas, x, y);
  6907. }
  6908. ctx.restore();
  6909. this.compose();
  6910. }
  6911. paintImageMaskXObjectGroup(images) {
  6912. if (!this.contentVisible) {
  6913. return;
  6914. }
  6915. const ctx = this.ctx;
  6916. const fillColor = this.current.fillColor;
  6917. const isPatternFill = this.current.patternFill;
  6918. for (const image of images) {
  6919. const {
  6920. data,
  6921. width,
  6922. height,
  6923. transform
  6924. } = image;
  6925. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  6926. const maskCtx = maskCanvas.context;
  6927. maskCtx.save();
  6928. const img = this.getObject(data, image);
  6929. putBinaryImageMask(maskCtx, img);
  6930. maskCtx.globalCompositeOperation = "source-in";
  6931. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
  6932. maskCtx.fillRect(0, 0, width, height);
  6933. maskCtx.restore();
  6934. ctx.save();
  6935. ctx.transform(...transform);
  6936. ctx.scale(1, -1);
  6937. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  6938. ctx.restore();
  6939. }
  6940. this.compose();
  6941. }
  6942. paintImageXObject(objId) {
  6943. if (!this.contentVisible) {
  6944. return;
  6945. }
  6946. const imgData = this.getObject(objId);
  6947. if (!imgData) {
  6948. (0, _util.warn)("Dependent image isn't ready yet");
  6949. return;
  6950. }
  6951. this.paintInlineImageXObject(imgData);
  6952. }
  6953. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  6954. if (!this.contentVisible) {
  6955. return;
  6956. }
  6957. const imgData = this.getObject(objId);
  6958. if (!imgData) {
  6959. (0, _util.warn)("Dependent image isn't ready yet");
  6960. return;
  6961. }
  6962. const width = imgData.width;
  6963. const height = imgData.height;
  6964. const map = [];
  6965. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  6966. map.push({
  6967. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  6968. x: 0,
  6969. y: 0,
  6970. w: width,
  6971. h: height
  6972. });
  6973. }
  6974. this.paintInlineImageXObjectGroup(imgData, map);
  6975. }
  6976. applyTransferMapsToCanvas(ctx) {
  6977. if (this.current.transferMaps !== "none") {
  6978. ctx.filter = this.current.transferMaps;
  6979. ctx.drawImage(ctx.canvas, 0, 0);
  6980. ctx.filter = "none";
  6981. }
  6982. return ctx.canvas;
  6983. }
  6984. applyTransferMapsToBitmap(imgData) {
  6985. if (this.current.transferMaps === "none") {
  6986. return imgData.bitmap;
  6987. }
  6988. const {
  6989. bitmap,
  6990. width,
  6991. height
  6992. } = imgData;
  6993. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  6994. const tmpCtx = tmpCanvas.context;
  6995. tmpCtx.filter = this.current.transferMaps;
  6996. tmpCtx.drawImage(bitmap, 0, 0);
  6997. tmpCtx.filter = "none";
  6998. return tmpCanvas.canvas;
  6999. }
  7000. paintInlineImageXObject(imgData) {
  7001. if (!this.contentVisible) {
  7002. return;
  7003. }
  7004. const width = imgData.width;
  7005. const height = imgData.height;
  7006. const ctx = this.ctx;
  7007. this.save();
  7008. if (!_is_node.isNodeJS) {
  7009. ctx.filter = "none";
  7010. }
  7011. ctx.scale(1 / width, -1 / height);
  7012. let imgToPaint;
  7013. if (imgData.bitmap) {
  7014. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  7015. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  7016. imgToPaint = imgData;
  7017. } else {
  7018. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  7019. const tmpCtx = tmpCanvas.context;
  7020. putBinaryImageData(tmpCtx, imgData);
  7021. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  7022. }
  7023. const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
  7024. ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
  7025. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  7026. this.compose();
  7027. this.restore();
  7028. }
  7029. paintInlineImageXObjectGroup(imgData, map) {
  7030. if (!this.contentVisible) {
  7031. return;
  7032. }
  7033. const ctx = this.ctx;
  7034. let imgToPaint;
  7035. if (imgData.bitmap) {
  7036. imgToPaint = imgData.bitmap;
  7037. } else {
  7038. const w = imgData.width;
  7039. const h = imgData.height;
  7040. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  7041. const tmpCtx = tmpCanvas.context;
  7042. putBinaryImageData(tmpCtx, imgData);
  7043. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  7044. }
  7045. for (const entry of map) {
  7046. ctx.save();
  7047. ctx.transform(...entry.transform);
  7048. ctx.scale(1, -1);
  7049. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  7050. ctx.restore();
  7051. }
  7052. this.compose();
  7053. }
  7054. paintSolidColorImageMask() {
  7055. if (!this.contentVisible) {
  7056. return;
  7057. }
  7058. this.ctx.fillRect(0, 0, 1, 1);
  7059. this.compose();
  7060. }
  7061. markPoint(tag) {}
  7062. markPointProps(tag, properties) {}
  7063. beginMarkedContent(tag) {
  7064. this.markedContentStack.push({
  7065. visible: true
  7066. });
  7067. }
  7068. beginMarkedContentProps(tag, properties) {
  7069. if (tag === "OC") {
  7070. this.markedContentStack.push({
  7071. visible: this.optionalContentConfig.isVisible(properties)
  7072. });
  7073. } else {
  7074. this.markedContentStack.push({
  7075. visible: true
  7076. });
  7077. }
  7078. this.contentVisible = this.isContentVisible();
  7079. }
  7080. endMarkedContent() {
  7081. this.markedContentStack.pop();
  7082. this.contentVisible = this.isContentVisible();
  7083. }
  7084. beginCompat() {}
  7085. endCompat() {}
  7086. consumePath(clipBox) {
  7087. const isEmpty = this.current.isEmptyClip();
  7088. if (this.pendingClip) {
  7089. this.current.updateClipFromPath();
  7090. }
  7091. if (!this.pendingClip) {
  7092. this.compose(clipBox);
  7093. }
  7094. const ctx = this.ctx;
  7095. if (this.pendingClip) {
  7096. if (!isEmpty) {
  7097. if (this.pendingClip === EO_CLIP) {
  7098. ctx.clip("evenodd");
  7099. } else {
  7100. ctx.clip();
  7101. }
  7102. }
  7103. this.pendingClip = null;
  7104. }
  7105. this.current.startNewPathAndClipBox(this.current.clipBox);
  7106. ctx.beginPath();
  7107. }
  7108. getSinglePixelWidth() {
  7109. if (!this._cachedGetSinglePixelWidth) {
  7110. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  7111. if (m[1] === 0 && m[2] === 0) {
  7112. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  7113. } else {
  7114. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7115. const normX = Math.hypot(m[0], m[2]);
  7116. const normY = Math.hypot(m[1], m[3]);
  7117. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  7118. }
  7119. }
  7120. return this._cachedGetSinglePixelWidth;
  7121. }
  7122. getScaleForStroking() {
  7123. if (!this._cachedScaleForStroking) {
  7124. const {
  7125. lineWidth
  7126. } = this.current;
  7127. const m = (0, _display_utils.getCurrentTransform)(this.ctx);
  7128. let scaleX, scaleY;
  7129. if (m[1] === 0 && m[2] === 0) {
  7130. const normX = Math.abs(m[0]);
  7131. const normY = Math.abs(m[3]);
  7132. if (lineWidth === 0) {
  7133. scaleX = 1 / normX;
  7134. scaleY = 1 / normY;
  7135. } else {
  7136. const scaledXLineWidth = normX * lineWidth;
  7137. const scaledYLineWidth = normY * lineWidth;
  7138. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  7139. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  7140. }
  7141. } else {
  7142. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  7143. const normX = Math.hypot(m[0], m[1]);
  7144. const normY = Math.hypot(m[2], m[3]);
  7145. if (lineWidth === 0) {
  7146. scaleX = normY / absDet;
  7147. scaleY = normX / absDet;
  7148. } else {
  7149. const baseArea = lineWidth * absDet;
  7150. scaleX = normY > baseArea ? normY / baseArea : 1;
  7151. scaleY = normX > baseArea ? normX / baseArea : 1;
  7152. }
  7153. }
  7154. this._cachedScaleForStroking = [scaleX, scaleY];
  7155. }
  7156. return this._cachedScaleForStroking;
  7157. }
  7158. rescaleAndStroke(saveRestore) {
  7159. const {
  7160. ctx
  7161. } = this;
  7162. const {
  7163. lineWidth
  7164. } = this.current;
  7165. const [scaleX, scaleY] = this.getScaleForStroking();
  7166. ctx.lineWidth = lineWidth || 1;
  7167. if (scaleX === 1 && scaleY === 1) {
  7168. ctx.stroke();
  7169. return;
  7170. }
  7171. let savedMatrix, savedDashes, savedDashOffset;
  7172. if (saveRestore) {
  7173. savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
  7174. savedDashes = ctx.getLineDash().slice();
  7175. savedDashOffset = ctx.lineDashOffset;
  7176. }
  7177. ctx.scale(scaleX, scaleY);
  7178. const scale = Math.max(scaleX, scaleY);
  7179. ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
  7180. ctx.lineDashOffset /= scale;
  7181. ctx.stroke();
  7182. if (saveRestore) {
  7183. ctx.setTransform(...savedMatrix);
  7184. ctx.setLineDash(savedDashes);
  7185. ctx.lineDashOffset = savedDashOffset;
  7186. }
  7187. }
  7188. isContentVisible() {
  7189. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  7190. if (!this.markedContentStack[i].visible) {
  7191. return false;
  7192. }
  7193. }
  7194. return true;
  7195. }
  7196. }
  7197. exports.CanvasGraphics = CanvasGraphics;
  7198. for (const op in _util.OPS) {
  7199. if (CanvasGraphics.prototype[op] !== undefined) {
  7200. CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  7201. }
  7202. }
  7203. /***/ }),
  7204. /* 12 */
  7205. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7206. Object.defineProperty(exports, "__esModule", ({
  7207. value: true
  7208. }));
  7209. exports.TilingPattern = exports.PathType = void 0;
  7210. exports.getShadingPattern = getShadingPattern;
  7211. var _util = __w_pdfjs_require__(1);
  7212. var _display_utils = __w_pdfjs_require__(6);
  7213. const PathType = {
  7214. FILL: "Fill",
  7215. STROKE: "Stroke",
  7216. SHADING: "Shading"
  7217. };
  7218. exports.PathType = PathType;
  7219. function applyBoundingBox(ctx, bbox) {
  7220. if (!bbox) {
  7221. return;
  7222. }
  7223. const width = bbox[2] - bbox[0];
  7224. const height = bbox[3] - bbox[1];
  7225. const region = new Path2D();
  7226. region.rect(bbox[0], bbox[1], width, height);
  7227. ctx.clip(region);
  7228. }
  7229. class BaseShadingPattern {
  7230. constructor() {
  7231. if (this.constructor === BaseShadingPattern) {
  7232. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  7233. }
  7234. }
  7235. getPattern() {
  7236. (0, _util.unreachable)("Abstract method `getPattern` called.");
  7237. }
  7238. }
  7239. class RadialAxialShadingPattern extends BaseShadingPattern {
  7240. constructor(IR) {
  7241. super();
  7242. this._type = IR[1];
  7243. this._bbox = IR[2];
  7244. this._colorStops = IR[3];
  7245. this._p0 = IR[4];
  7246. this._p1 = IR[5];
  7247. this._r0 = IR[6];
  7248. this._r1 = IR[7];
  7249. this.matrix = null;
  7250. }
  7251. _createGradient(ctx) {
  7252. let grad;
  7253. if (this._type === "axial") {
  7254. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  7255. } else if (this._type === "radial") {
  7256. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  7257. }
  7258. for (const colorStop of this._colorStops) {
  7259. grad.addColorStop(colorStop[0], colorStop[1]);
  7260. }
  7261. return grad;
  7262. }
  7263. getPattern(ctx, owner, inverse, pathType) {
  7264. let pattern;
  7265. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  7266. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  7267. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  7268. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  7269. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  7270. const tmpCtx = tmpCanvas.context;
  7271. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7272. tmpCtx.beginPath();
  7273. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  7274. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  7275. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  7276. tmpCtx.transform(...owner.baseTransform);
  7277. if (this.matrix) {
  7278. tmpCtx.transform(...this.matrix);
  7279. }
  7280. applyBoundingBox(tmpCtx, this._bbox);
  7281. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  7282. tmpCtx.fill();
  7283. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  7284. const domMatrix = new DOMMatrix(inverse);
  7285. pattern.setTransform(domMatrix);
  7286. } else {
  7287. applyBoundingBox(ctx, this._bbox);
  7288. pattern = this._createGradient(ctx);
  7289. }
  7290. return pattern;
  7291. }
  7292. }
  7293. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7294. const coords = context.coords,
  7295. colors = context.colors;
  7296. const bytes = data.data,
  7297. rowSize = data.width * 4;
  7298. let tmp;
  7299. if (coords[p1 + 1] > coords[p2 + 1]) {
  7300. tmp = p1;
  7301. p1 = p2;
  7302. p2 = tmp;
  7303. tmp = c1;
  7304. c1 = c2;
  7305. c2 = tmp;
  7306. }
  7307. if (coords[p2 + 1] > coords[p3 + 1]) {
  7308. tmp = p2;
  7309. p2 = p3;
  7310. p3 = tmp;
  7311. tmp = c2;
  7312. c2 = c3;
  7313. c3 = tmp;
  7314. }
  7315. if (coords[p1 + 1] > coords[p2 + 1]) {
  7316. tmp = p1;
  7317. p1 = p2;
  7318. p2 = tmp;
  7319. tmp = c1;
  7320. c1 = c2;
  7321. c2 = tmp;
  7322. }
  7323. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7324. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7325. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7326. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7327. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7328. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7329. if (y1 >= y3) {
  7330. return;
  7331. }
  7332. const c1r = colors[c1],
  7333. c1g = colors[c1 + 1],
  7334. c1b = colors[c1 + 2];
  7335. const c2r = colors[c2],
  7336. c2g = colors[c2 + 1],
  7337. c2b = colors[c2 + 2];
  7338. const c3r = colors[c3],
  7339. c3g = colors[c3 + 1],
  7340. c3b = colors[c3 + 2];
  7341. const minY = Math.round(y1),
  7342. maxY = Math.round(y3);
  7343. let xa, car, cag, cab;
  7344. let xb, cbr, cbg, cbb;
  7345. for (let y = minY; y <= maxY; y++) {
  7346. if (y < y2) {
  7347. let k;
  7348. if (y < y1) {
  7349. k = 0;
  7350. } else {
  7351. k = (y1 - y) / (y1 - y2);
  7352. }
  7353. xa = x1 - (x1 - x2) * k;
  7354. car = c1r - (c1r - c2r) * k;
  7355. cag = c1g - (c1g - c2g) * k;
  7356. cab = c1b - (c1b - c2b) * k;
  7357. } else {
  7358. let k;
  7359. if (y > y3) {
  7360. k = 1;
  7361. } else if (y2 === y3) {
  7362. k = 0;
  7363. } else {
  7364. k = (y2 - y) / (y2 - y3);
  7365. }
  7366. xa = x2 - (x2 - x3) * k;
  7367. car = c2r - (c2r - c3r) * k;
  7368. cag = c2g - (c2g - c3g) * k;
  7369. cab = c2b - (c2b - c3b) * k;
  7370. }
  7371. let k;
  7372. if (y < y1) {
  7373. k = 0;
  7374. } else if (y > y3) {
  7375. k = 1;
  7376. } else {
  7377. k = (y1 - y) / (y1 - y3);
  7378. }
  7379. xb = x1 - (x1 - x3) * k;
  7380. cbr = c1r - (c1r - c3r) * k;
  7381. cbg = c1g - (c1g - c3g) * k;
  7382. cbb = c1b - (c1b - c3b) * k;
  7383. const x1_ = Math.round(Math.min(xa, xb));
  7384. const x2_ = Math.round(Math.max(xa, xb));
  7385. let j = rowSize * y + x1_ * 4;
  7386. for (let x = x1_; x <= x2_; x++) {
  7387. k = (xa - x) / (xa - xb);
  7388. if (k < 0) {
  7389. k = 0;
  7390. } else if (k > 1) {
  7391. k = 1;
  7392. }
  7393. bytes[j++] = car - (car - cbr) * k | 0;
  7394. bytes[j++] = cag - (cag - cbg) * k | 0;
  7395. bytes[j++] = cab - (cab - cbb) * k | 0;
  7396. bytes[j++] = 255;
  7397. }
  7398. }
  7399. }
  7400. function drawFigure(data, figure, context) {
  7401. const ps = figure.coords;
  7402. const cs = figure.colors;
  7403. let i, ii;
  7404. switch (figure.type) {
  7405. case "lattice":
  7406. const verticesPerRow = figure.verticesPerRow;
  7407. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  7408. const cols = verticesPerRow - 1;
  7409. for (i = 0; i < rows; i++) {
  7410. let q = i * verticesPerRow;
  7411. for (let j = 0; j < cols; j++, q++) {
  7412. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7413. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7414. }
  7415. }
  7416. break;
  7417. case "triangles":
  7418. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7419. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  7420. }
  7421. break;
  7422. default:
  7423. throw new Error("illegal figure");
  7424. }
  7425. }
  7426. class MeshShadingPattern extends BaseShadingPattern {
  7427. constructor(IR) {
  7428. super();
  7429. this._coords = IR[2];
  7430. this._colors = IR[3];
  7431. this._figures = IR[4];
  7432. this._bounds = IR[5];
  7433. this._bbox = IR[7];
  7434. this._background = IR[8];
  7435. this.matrix = null;
  7436. }
  7437. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  7438. const EXPECTED_SCALE = 1.1;
  7439. const MAX_PATTERN_SIZE = 3000;
  7440. const BORDER_SIZE = 2;
  7441. const offsetX = Math.floor(this._bounds[0]);
  7442. const offsetY = Math.floor(this._bounds[1]);
  7443. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  7444. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  7445. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7446. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7447. const scaleX = boundsWidth / width;
  7448. const scaleY = boundsHeight / height;
  7449. const context = {
  7450. coords: this._coords,
  7451. colors: this._colors,
  7452. offsetX: -offsetX,
  7453. offsetY: -offsetY,
  7454. scaleX: 1 / scaleX,
  7455. scaleY: 1 / scaleY
  7456. };
  7457. const paddedWidth = width + BORDER_SIZE * 2;
  7458. const paddedHeight = height + BORDER_SIZE * 2;
  7459. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  7460. const tmpCtx = tmpCanvas.context;
  7461. const data = tmpCtx.createImageData(width, height);
  7462. if (backgroundColor) {
  7463. const bytes = data.data;
  7464. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  7465. bytes[i] = backgroundColor[0];
  7466. bytes[i + 1] = backgroundColor[1];
  7467. bytes[i + 2] = backgroundColor[2];
  7468. bytes[i + 3] = 255;
  7469. }
  7470. }
  7471. for (const figure of this._figures) {
  7472. drawFigure(data, figure, context);
  7473. }
  7474. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  7475. const canvas = tmpCanvas.canvas;
  7476. return {
  7477. canvas,
  7478. offsetX: offsetX - BORDER_SIZE * scaleX,
  7479. offsetY: offsetY - BORDER_SIZE * scaleY,
  7480. scaleX,
  7481. scaleY
  7482. };
  7483. }
  7484. getPattern(ctx, owner, inverse, pathType) {
  7485. applyBoundingBox(ctx, this._bbox);
  7486. let scale;
  7487. if (pathType === PathType.SHADING) {
  7488. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  7489. } else {
  7490. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  7491. if (this.matrix) {
  7492. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7493. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  7494. }
  7495. }
  7496. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  7497. if (pathType !== PathType.SHADING) {
  7498. ctx.setTransform(...owner.baseTransform);
  7499. if (this.matrix) {
  7500. ctx.transform(...this.matrix);
  7501. }
  7502. }
  7503. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7504. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  7505. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  7506. }
  7507. }
  7508. class DummyShadingPattern extends BaseShadingPattern {
  7509. getPattern() {
  7510. return "hotpink";
  7511. }
  7512. }
  7513. function getShadingPattern(IR) {
  7514. switch (IR[0]) {
  7515. case "RadialAxial":
  7516. return new RadialAxialShadingPattern(IR);
  7517. case "Mesh":
  7518. return new MeshShadingPattern(IR);
  7519. case "Dummy":
  7520. return new DummyShadingPattern();
  7521. }
  7522. throw new Error(`Unknown IR type: ${IR[0]}`);
  7523. }
  7524. const PaintType = {
  7525. COLORED: 1,
  7526. UNCOLORED: 2
  7527. };
  7528. class TilingPattern {
  7529. static get MAX_PATTERN_SIZE() {
  7530. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  7531. }
  7532. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  7533. this.operatorList = IR[2];
  7534. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7535. this.bbox = IR[4];
  7536. this.xstep = IR[5];
  7537. this.ystep = IR[6];
  7538. this.paintType = IR[7];
  7539. this.tilingType = IR[8];
  7540. this.color = color;
  7541. this.ctx = ctx;
  7542. this.canvasGraphicsFactory = canvasGraphicsFactory;
  7543. this.baseTransform = baseTransform;
  7544. }
  7545. createPatternCanvas(owner) {
  7546. const operatorList = this.operatorList;
  7547. const bbox = this.bbox;
  7548. const xstep = this.xstep;
  7549. const ystep = this.ystep;
  7550. const paintType = this.paintType;
  7551. const tilingType = this.tilingType;
  7552. const color = this.color;
  7553. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  7554. (0, _util.info)("TilingType: " + tilingType);
  7555. const x0 = bbox[0],
  7556. y0 = bbox[1],
  7557. x1 = bbox[2],
  7558. y1 = bbox[3];
  7559. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  7560. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  7561. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  7562. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  7563. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  7564. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  7565. const tmpCtx = tmpCanvas.context;
  7566. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  7567. graphics.groupLevel = owner.groupLevel;
  7568. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  7569. let adjustedX0 = x0;
  7570. let adjustedY0 = y0;
  7571. let adjustedX1 = x1;
  7572. let adjustedY1 = y1;
  7573. if (x0 < 0) {
  7574. adjustedX0 = 0;
  7575. adjustedX1 += Math.abs(x0);
  7576. }
  7577. if (y0 < 0) {
  7578. adjustedY0 = 0;
  7579. adjustedY1 += Math.abs(y0);
  7580. }
  7581. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  7582. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  7583. tmpCtx.save();
  7584. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  7585. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  7586. graphics.executeOperatorList(operatorList);
  7587. graphics.endDrawing();
  7588. return {
  7589. canvas: tmpCanvas.canvas,
  7590. scaleX: dimx.scale,
  7591. scaleY: dimy.scale,
  7592. offsetX: adjustedX0,
  7593. offsetY: adjustedY0
  7594. };
  7595. }
  7596. getSizeAndScale(step, realOutputSize, scale) {
  7597. step = Math.abs(step);
  7598. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  7599. let size = Math.ceil(step * scale);
  7600. if (size >= maxSize) {
  7601. size = maxSize;
  7602. } else {
  7603. scale = size / step;
  7604. }
  7605. return {
  7606. scale,
  7607. size
  7608. };
  7609. }
  7610. clipBbox(graphics, x0, y0, x1, y1) {
  7611. const bboxWidth = x1 - x0;
  7612. const bboxHeight = y1 - y0;
  7613. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  7614. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  7615. graphics.clip();
  7616. graphics.endPath();
  7617. }
  7618. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  7619. const context = graphics.ctx,
  7620. current = graphics.current;
  7621. switch (paintType) {
  7622. case PaintType.COLORED:
  7623. const ctx = this.ctx;
  7624. context.fillStyle = ctx.fillStyle;
  7625. context.strokeStyle = ctx.strokeStyle;
  7626. current.fillColor = ctx.fillStyle;
  7627. current.strokeColor = ctx.strokeStyle;
  7628. break;
  7629. case PaintType.UNCOLORED:
  7630. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  7631. context.fillStyle = cssColor;
  7632. context.strokeStyle = cssColor;
  7633. current.fillColor = cssColor;
  7634. current.strokeColor = cssColor;
  7635. break;
  7636. default:
  7637. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  7638. }
  7639. }
  7640. getPattern(ctx, owner, inverse, pathType) {
  7641. let matrix = inverse;
  7642. if (pathType !== PathType.SHADING) {
  7643. matrix = _util.Util.transform(matrix, owner.baseTransform);
  7644. if (this.matrix) {
  7645. matrix = _util.Util.transform(matrix, this.matrix);
  7646. }
  7647. }
  7648. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  7649. let domMatrix = new DOMMatrix(matrix);
  7650. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  7651. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  7652. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  7653. pattern.setTransform(domMatrix);
  7654. return pattern;
  7655. }
  7656. }
  7657. exports.TilingPattern = TilingPattern;
  7658. /***/ }),
  7659. /* 13 */
  7660. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7661. Object.defineProperty(exports, "__esModule", ({
  7662. value: true
  7663. }));
  7664. exports.convertBlackAndWhiteToRGBA = convertBlackAndWhiteToRGBA;
  7665. exports.convertToRGBA = convertToRGBA;
  7666. exports.grayToRGBA = grayToRGBA;
  7667. var _util = __w_pdfjs_require__(1);
  7668. function convertToRGBA(params) {
  7669. switch (params.kind) {
  7670. case _util.ImageKind.GRAYSCALE_1BPP:
  7671. return convertBlackAndWhiteToRGBA(params);
  7672. case _util.ImageKind.RGB_24BPP:
  7673. return convertRGBToRGBA(params);
  7674. }
  7675. return null;
  7676. }
  7677. function convertBlackAndWhiteToRGBA({
  7678. src,
  7679. srcPos = 0,
  7680. dest,
  7681. width,
  7682. height,
  7683. nonBlackColor = 0xffffffff,
  7684. inverseDecode = false
  7685. }) {
  7686. const black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  7687. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  7688. const widthInSource = width >> 3;
  7689. const widthRemainder = width & 7;
  7690. const srcLength = src.length;
  7691. dest = new Uint32Array(dest.buffer);
  7692. let destPos = 0;
  7693. for (let i = 0; i < height; i++) {
  7694. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  7695. const elem = srcPos < srcLength ? src[srcPos] : 255;
  7696. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  7697. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  7698. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  7699. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  7700. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  7701. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  7702. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  7703. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  7704. }
  7705. if (widthRemainder === 0) {
  7706. continue;
  7707. }
  7708. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  7709. for (let j = 0; j < widthRemainder; j++) {
  7710. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  7711. }
  7712. }
  7713. return {
  7714. srcPos,
  7715. destPos
  7716. };
  7717. }
  7718. function convertRGBToRGBA({
  7719. src,
  7720. srcPos = 0,
  7721. dest,
  7722. destPos = 0,
  7723. width,
  7724. height
  7725. }) {
  7726. let i = 0;
  7727. const len32 = src.length >> 2;
  7728. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  7729. if (_util.FeatureTest.isLittleEndian) {
  7730. for (; i < len32 - 2; i += 3, destPos += 4) {
  7731. const s1 = src32[i];
  7732. const s2 = src32[i + 1];
  7733. const s3 = src32[i + 2];
  7734. dest[destPos] = s1 | 0xff000000;
  7735. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  7736. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  7737. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  7738. }
  7739. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  7740. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  7741. }
  7742. } else {
  7743. for (; i < len32 - 2; i += 3, destPos += 4) {
  7744. const s1 = src32[i];
  7745. const s2 = src32[i + 1];
  7746. const s3 = src32[i + 2];
  7747. dest[destPos] = s1 | 0xff;
  7748. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  7749. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  7750. dest[destPos + 3] = s3 << 8 | 0xff;
  7751. }
  7752. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  7753. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  7754. }
  7755. }
  7756. return {
  7757. srcPos,
  7758. destPos
  7759. };
  7760. }
  7761. function grayToRGBA(src, dest) {
  7762. if (_util.FeatureTest.isLittleEndian) {
  7763. for (let i = 0, ii = src.length; i < ii; i++) {
  7764. dest[i] = src[i] * 0x10101 | 0xff000000;
  7765. }
  7766. } else {
  7767. for (let i = 0, ii = src.length; i < ii; i++) {
  7768. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  7769. }
  7770. }
  7771. }
  7772. /***/ }),
  7773. /* 14 */
  7774. /***/ ((__unused_webpack_module, exports) => {
  7775. Object.defineProperty(exports, "__esModule", ({
  7776. value: true
  7777. }));
  7778. exports.GlobalWorkerOptions = void 0;
  7779. const GlobalWorkerOptions = Object.create(null);
  7780. exports.GlobalWorkerOptions = GlobalWorkerOptions;
  7781. GlobalWorkerOptions.workerPort = null;
  7782. GlobalWorkerOptions.workerSrc = "";
  7783. /***/ }),
  7784. /* 15 */
  7785. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7786. Object.defineProperty(exports, "__esModule", ({
  7787. value: true
  7788. }));
  7789. exports.MessageHandler = void 0;
  7790. var _util = __w_pdfjs_require__(1);
  7791. const CallbackKind = {
  7792. UNKNOWN: 0,
  7793. DATA: 1,
  7794. ERROR: 2
  7795. };
  7796. const StreamKind = {
  7797. UNKNOWN: 0,
  7798. CANCEL: 1,
  7799. CANCEL_COMPLETE: 2,
  7800. CLOSE: 3,
  7801. ENQUEUE: 4,
  7802. ERROR: 5,
  7803. PULL: 6,
  7804. PULL_COMPLETE: 7,
  7805. START_COMPLETE: 8
  7806. };
  7807. function wrapReason(reason) {
  7808. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  7809. (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  7810. }
  7811. switch (reason.name) {
  7812. case "AbortException":
  7813. return new _util.AbortException(reason.message);
  7814. case "MissingPDFException":
  7815. return new _util.MissingPDFException(reason.message);
  7816. case "PasswordException":
  7817. return new _util.PasswordException(reason.message, reason.code);
  7818. case "UnexpectedResponseException":
  7819. return new _util.UnexpectedResponseException(reason.message, reason.status);
  7820. case "UnknownErrorException":
  7821. return new _util.UnknownErrorException(reason.message, reason.details);
  7822. default:
  7823. return new _util.UnknownErrorException(reason.message, reason.toString());
  7824. }
  7825. }
  7826. class MessageHandler {
  7827. constructor(sourceName, targetName, comObj) {
  7828. this.sourceName = sourceName;
  7829. this.targetName = targetName;
  7830. this.comObj = comObj;
  7831. this.callbackId = 1;
  7832. this.streamId = 1;
  7833. this.streamSinks = Object.create(null);
  7834. this.streamControllers = Object.create(null);
  7835. this.callbackCapabilities = Object.create(null);
  7836. this.actionHandler = Object.create(null);
  7837. this._onComObjOnMessage = event => {
  7838. const data = event.data;
  7839. if (data.targetName !== this.sourceName) {
  7840. return;
  7841. }
  7842. if (data.stream) {
  7843. this._processStreamMessage(data);
  7844. return;
  7845. }
  7846. if (data.callback) {
  7847. const callbackId = data.callbackId;
  7848. const capability = this.callbackCapabilities[callbackId];
  7849. if (!capability) {
  7850. throw new Error(`Cannot resolve callback ${callbackId}`);
  7851. }
  7852. delete this.callbackCapabilities[callbackId];
  7853. if (data.callback === CallbackKind.DATA) {
  7854. capability.resolve(data.data);
  7855. } else if (data.callback === CallbackKind.ERROR) {
  7856. capability.reject(wrapReason(data.reason));
  7857. } else {
  7858. throw new Error("Unexpected callback case");
  7859. }
  7860. return;
  7861. }
  7862. const action = this.actionHandler[data.action];
  7863. if (!action) {
  7864. throw new Error(`Unknown action from worker: ${data.action}`);
  7865. }
  7866. if (data.callbackId) {
  7867. const cbSourceName = this.sourceName;
  7868. const cbTargetName = data.sourceName;
  7869. new Promise(function (resolve) {
  7870. resolve(action(data.data));
  7871. }).then(function (result) {
  7872. comObj.postMessage({
  7873. sourceName: cbSourceName,
  7874. targetName: cbTargetName,
  7875. callback: CallbackKind.DATA,
  7876. callbackId: data.callbackId,
  7877. data: result
  7878. });
  7879. }, function (reason) {
  7880. comObj.postMessage({
  7881. sourceName: cbSourceName,
  7882. targetName: cbTargetName,
  7883. callback: CallbackKind.ERROR,
  7884. callbackId: data.callbackId,
  7885. reason: wrapReason(reason)
  7886. });
  7887. });
  7888. return;
  7889. }
  7890. if (data.streamId) {
  7891. this._createStreamSink(data);
  7892. return;
  7893. }
  7894. action(data.data);
  7895. };
  7896. comObj.addEventListener("message", this._onComObjOnMessage);
  7897. }
  7898. on(actionName, handler) {
  7899. const ah = this.actionHandler;
  7900. if (ah[actionName]) {
  7901. throw new Error(`There is already an actionName called "${actionName}"`);
  7902. }
  7903. ah[actionName] = handler;
  7904. }
  7905. send(actionName, data, transfers) {
  7906. this.comObj.postMessage({
  7907. sourceName: this.sourceName,
  7908. targetName: this.targetName,
  7909. action: actionName,
  7910. data
  7911. }, transfers);
  7912. }
  7913. sendWithPromise(actionName, data, transfers) {
  7914. const callbackId = this.callbackId++;
  7915. const capability = (0, _util.createPromiseCapability)();
  7916. this.callbackCapabilities[callbackId] = capability;
  7917. try {
  7918. this.comObj.postMessage({
  7919. sourceName: this.sourceName,
  7920. targetName: this.targetName,
  7921. action: actionName,
  7922. callbackId,
  7923. data
  7924. }, transfers);
  7925. } catch (ex) {
  7926. capability.reject(ex);
  7927. }
  7928. return capability.promise;
  7929. }
  7930. sendWithStream(actionName, data, queueingStrategy, transfers) {
  7931. const streamId = this.streamId++,
  7932. sourceName = this.sourceName,
  7933. targetName = this.targetName,
  7934. comObj = this.comObj;
  7935. return new ReadableStream({
  7936. start: controller => {
  7937. const startCapability = (0, _util.createPromiseCapability)();
  7938. this.streamControllers[streamId] = {
  7939. controller,
  7940. startCall: startCapability,
  7941. pullCall: null,
  7942. cancelCall: null,
  7943. isClosed: false
  7944. };
  7945. comObj.postMessage({
  7946. sourceName,
  7947. targetName,
  7948. action: actionName,
  7949. streamId,
  7950. data,
  7951. desiredSize: controller.desiredSize
  7952. }, transfers);
  7953. return startCapability.promise;
  7954. },
  7955. pull: controller => {
  7956. const pullCapability = (0, _util.createPromiseCapability)();
  7957. this.streamControllers[streamId].pullCall = pullCapability;
  7958. comObj.postMessage({
  7959. sourceName,
  7960. targetName,
  7961. stream: StreamKind.PULL,
  7962. streamId,
  7963. desiredSize: controller.desiredSize
  7964. });
  7965. return pullCapability.promise;
  7966. },
  7967. cancel: reason => {
  7968. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  7969. const cancelCapability = (0, _util.createPromiseCapability)();
  7970. this.streamControllers[streamId].cancelCall = cancelCapability;
  7971. this.streamControllers[streamId].isClosed = true;
  7972. comObj.postMessage({
  7973. sourceName,
  7974. targetName,
  7975. stream: StreamKind.CANCEL,
  7976. streamId,
  7977. reason: wrapReason(reason)
  7978. });
  7979. return cancelCapability.promise;
  7980. }
  7981. }, queueingStrategy);
  7982. }
  7983. _createStreamSink(data) {
  7984. const streamId = data.streamId,
  7985. sourceName = this.sourceName,
  7986. targetName = data.sourceName,
  7987. comObj = this.comObj;
  7988. const self = this,
  7989. action = this.actionHandler[data.action];
  7990. const streamSink = {
  7991. enqueue(chunk, size = 1, transfers) {
  7992. if (this.isCancelled) {
  7993. return;
  7994. }
  7995. const lastDesiredSize = this.desiredSize;
  7996. this.desiredSize -= size;
  7997. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  7998. this.sinkCapability = (0, _util.createPromiseCapability)();
  7999. this.ready = this.sinkCapability.promise;
  8000. }
  8001. comObj.postMessage({
  8002. sourceName,
  8003. targetName,
  8004. stream: StreamKind.ENQUEUE,
  8005. streamId,
  8006. chunk
  8007. }, transfers);
  8008. },
  8009. close() {
  8010. if (this.isCancelled) {
  8011. return;
  8012. }
  8013. this.isCancelled = true;
  8014. comObj.postMessage({
  8015. sourceName,
  8016. targetName,
  8017. stream: StreamKind.CLOSE,
  8018. streamId
  8019. });
  8020. delete self.streamSinks[streamId];
  8021. },
  8022. error(reason) {
  8023. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  8024. if (this.isCancelled) {
  8025. return;
  8026. }
  8027. this.isCancelled = true;
  8028. comObj.postMessage({
  8029. sourceName,
  8030. targetName,
  8031. stream: StreamKind.ERROR,
  8032. streamId,
  8033. reason: wrapReason(reason)
  8034. });
  8035. },
  8036. sinkCapability: (0, _util.createPromiseCapability)(),
  8037. onPull: null,
  8038. onCancel: null,
  8039. isCancelled: false,
  8040. desiredSize: data.desiredSize,
  8041. ready: null
  8042. };
  8043. streamSink.sinkCapability.resolve();
  8044. streamSink.ready = streamSink.sinkCapability.promise;
  8045. this.streamSinks[streamId] = streamSink;
  8046. new Promise(function (resolve) {
  8047. resolve(action(data.data, streamSink));
  8048. }).then(function () {
  8049. comObj.postMessage({
  8050. sourceName,
  8051. targetName,
  8052. stream: StreamKind.START_COMPLETE,
  8053. streamId,
  8054. success: true
  8055. });
  8056. }, function (reason) {
  8057. comObj.postMessage({
  8058. sourceName,
  8059. targetName,
  8060. stream: StreamKind.START_COMPLETE,
  8061. streamId,
  8062. reason: wrapReason(reason)
  8063. });
  8064. });
  8065. }
  8066. _processStreamMessage(data) {
  8067. const streamId = data.streamId,
  8068. sourceName = this.sourceName,
  8069. targetName = data.sourceName,
  8070. comObj = this.comObj;
  8071. const streamController = this.streamControllers[streamId],
  8072. streamSink = this.streamSinks[streamId];
  8073. switch (data.stream) {
  8074. case StreamKind.START_COMPLETE:
  8075. if (data.success) {
  8076. streamController.startCall.resolve();
  8077. } else {
  8078. streamController.startCall.reject(wrapReason(data.reason));
  8079. }
  8080. break;
  8081. case StreamKind.PULL_COMPLETE:
  8082. if (data.success) {
  8083. streamController.pullCall.resolve();
  8084. } else {
  8085. streamController.pullCall.reject(wrapReason(data.reason));
  8086. }
  8087. break;
  8088. case StreamKind.PULL:
  8089. if (!streamSink) {
  8090. comObj.postMessage({
  8091. sourceName,
  8092. targetName,
  8093. stream: StreamKind.PULL_COMPLETE,
  8094. streamId,
  8095. success: true
  8096. });
  8097. break;
  8098. }
  8099. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  8100. streamSink.sinkCapability.resolve();
  8101. }
  8102. streamSink.desiredSize = data.desiredSize;
  8103. new Promise(function (resolve) {
  8104. resolve(streamSink.onPull && streamSink.onPull());
  8105. }).then(function () {
  8106. comObj.postMessage({
  8107. sourceName,
  8108. targetName,
  8109. stream: StreamKind.PULL_COMPLETE,
  8110. streamId,
  8111. success: true
  8112. });
  8113. }, function (reason) {
  8114. comObj.postMessage({
  8115. sourceName,
  8116. targetName,
  8117. stream: StreamKind.PULL_COMPLETE,
  8118. streamId,
  8119. reason: wrapReason(reason)
  8120. });
  8121. });
  8122. break;
  8123. case StreamKind.ENQUEUE:
  8124. (0, _util.assert)(streamController, "enqueue should have stream controller");
  8125. if (streamController.isClosed) {
  8126. break;
  8127. }
  8128. streamController.controller.enqueue(data.chunk);
  8129. break;
  8130. case StreamKind.CLOSE:
  8131. (0, _util.assert)(streamController, "close should have stream controller");
  8132. if (streamController.isClosed) {
  8133. break;
  8134. }
  8135. streamController.isClosed = true;
  8136. streamController.controller.close();
  8137. this._deleteStreamController(streamController, streamId);
  8138. break;
  8139. case StreamKind.ERROR:
  8140. (0, _util.assert)(streamController, "error should have stream controller");
  8141. streamController.controller.error(wrapReason(data.reason));
  8142. this._deleteStreamController(streamController, streamId);
  8143. break;
  8144. case StreamKind.CANCEL_COMPLETE:
  8145. if (data.success) {
  8146. streamController.cancelCall.resolve();
  8147. } else {
  8148. streamController.cancelCall.reject(wrapReason(data.reason));
  8149. }
  8150. this._deleteStreamController(streamController, streamId);
  8151. break;
  8152. case StreamKind.CANCEL:
  8153. if (!streamSink) {
  8154. break;
  8155. }
  8156. new Promise(function (resolve) {
  8157. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  8158. }).then(function () {
  8159. comObj.postMessage({
  8160. sourceName,
  8161. targetName,
  8162. stream: StreamKind.CANCEL_COMPLETE,
  8163. streamId,
  8164. success: true
  8165. });
  8166. }, function (reason) {
  8167. comObj.postMessage({
  8168. sourceName,
  8169. targetName,
  8170. stream: StreamKind.CANCEL_COMPLETE,
  8171. streamId,
  8172. reason: wrapReason(reason)
  8173. });
  8174. });
  8175. streamSink.sinkCapability.reject(wrapReason(data.reason));
  8176. streamSink.isCancelled = true;
  8177. delete this.streamSinks[streamId];
  8178. break;
  8179. default:
  8180. throw new Error("Unexpected stream case");
  8181. }
  8182. }
  8183. async _deleteStreamController(streamController, streamId) {
  8184. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  8185. delete this.streamControllers[streamId];
  8186. }
  8187. destroy() {
  8188. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  8189. }
  8190. }
  8191. exports.MessageHandler = MessageHandler;
  8192. /***/ }),
  8193. /* 16 */
  8194. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8195. Object.defineProperty(exports, "__esModule", ({
  8196. value: true
  8197. }));
  8198. exports.Metadata = void 0;
  8199. var _util = __w_pdfjs_require__(1);
  8200. class Metadata {
  8201. #metadataMap;
  8202. #data;
  8203. constructor({
  8204. parsedData,
  8205. rawData
  8206. }) {
  8207. this.#metadataMap = parsedData;
  8208. this.#data = rawData;
  8209. }
  8210. getRaw() {
  8211. return this.#data;
  8212. }
  8213. get(name) {
  8214. return this.#metadataMap.get(name) ?? null;
  8215. }
  8216. getAll() {
  8217. return (0, _util.objectFromMap)(this.#metadataMap);
  8218. }
  8219. has(name) {
  8220. return this.#metadataMap.has(name);
  8221. }
  8222. }
  8223. exports.Metadata = Metadata;
  8224. /***/ }),
  8225. /* 17 */
  8226. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8227. Object.defineProperty(exports, "__esModule", ({
  8228. value: true
  8229. }));
  8230. exports.OptionalContentConfig = void 0;
  8231. var _util = __w_pdfjs_require__(1);
  8232. var _murmurhash = __w_pdfjs_require__(8);
  8233. const INTERNAL = Symbol("INTERNAL");
  8234. class OptionalContentGroup {
  8235. #visible = true;
  8236. constructor(name, intent) {
  8237. this.name = name;
  8238. this.intent = intent;
  8239. }
  8240. get visible() {
  8241. return this.#visible;
  8242. }
  8243. _setVisible(internal, visible) {
  8244. if (internal !== INTERNAL) {
  8245. (0, _util.unreachable)("Internal method `_setVisible` called.");
  8246. }
  8247. this.#visible = visible;
  8248. }
  8249. }
  8250. class OptionalContentConfig {
  8251. #cachedGetHash = null;
  8252. #groups = new Map();
  8253. #initialHash = null;
  8254. #order = null;
  8255. constructor(data) {
  8256. this.name = null;
  8257. this.creator = null;
  8258. if (data === null) {
  8259. return;
  8260. }
  8261. this.name = data.name;
  8262. this.creator = data.creator;
  8263. this.#order = data.order;
  8264. for (const group of data.groups) {
  8265. this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
  8266. }
  8267. if (data.baseState === "OFF") {
  8268. for (const group of this.#groups.values()) {
  8269. group._setVisible(INTERNAL, false);
  8270. }
  8271. }
  8272. for (const on of data.on) {
  8273. this.#groups.get(on)._setVisible(INTERNAL, true);
  8274. }
  8275. for (const off of data.off) {
  8276. this.#groups.get(off)._setVisible(INTERNAL, false);
  8277. }
  8278. this.#initialHash = this.getHash();
  8279. }
  8280. #evaluateVisibilityExpression(array) {
  8281. const length = array.length;
  8282. if (length < 2) {
  8283. return true;
  8284. }
  8285. const operator = array[0];
  8286. for (let i = 1; i < length; i++) {
  8287. const element = array[i];
  8288. let state;
  8289. if (Array.isArray(element)) {
  8290. state = this.#evaluateVisibilityExpression(element);
  8291. } else if (this.#groups.has(element)) {
  8292. state = this.#groups.get(element).visible;
  8293. } else {
  8294. (0, _util.warn)(`Optional content group not found: ${element}`);
  8295. return true;
  8296. }
  8297. switch (operator) {
  8298. case "And":
  8299. if (!state) {
  8300. return false;
  8301. }
  8302. break;
  8303. case "Or":
  8304. if (state) {
  8305. return true;
  8306. }
  8307. break;
  8308. case "Not":
  8309. return !state;
  8310. default:
  8311. return true;
  8312. }
  8313. }
  8314. return operator === "And";
  8315. }
  8316. isVisible(group) {
  8317. if (this.#groups.size === 0) {
  8318. return true;
  8319. }
  8320. if (!group) {
  8321. (0, _util.warn)("Optional content group not defined.");
  8322. return true;
  8323. }
  8324. if (group.type === "OCG") {
  8325. if (!this.#groups.has(group.id)) {
  8326. (0, _util.warn)(`Optional content group not found: ${group.id}`);
  8327. return true;
  8328. }
  8329. return this.#groups.get(group.id).visible;
  8330. } else if (group.type === "OCMD") {
  8331. if (group.expression) {
  8332. return this.#evaluateVisibilityExpression(group.expression);
  8333. }
  8334. if (!group.policy || group.policy === "AnyOn") {
  8335. for (const id of group.ids) {
  8336. if (!this.#groups.has(id)) {
  8337. (0, _util.warn)(`Optional content group not found: ${id}`);
  8338. return true;
  8339. }
  8340. if (this.#groups.get(id).visible) {
  8341. return true;
  8342. }
  8343. }
  8344. return false;
  8345. } else if (group.policy === "AllOn") {
  8346. for (const id of group.ids) {
  8347. if (!this.#groups.has(id)) {
  8348. (0, _util.warn)(`Optional content group not found: ${id}`);
  8349. return true;
  8350. }
  8351. if (!this.#groups.get(id).visible) {
  8352. return false;
  8353. }
  8354. }
  8355. return true;
  8356. } else if (group.policy === "AnyOff") {
  8357. for (const id of group.ids) {
  8358. if (!this.#groups.has(id)) {
  8359. (0, _util.warn)(`Optional content group not found: ${id}`);
  8360. return true;
  8361. }
  8362. if (!this.#groups.get(id).visible) {
  8363. return true;
  8364. }
  8365. }
  8366. return false;
  8367. } else if (group.policy === "AllOff") {
  8368. for (const id of group.ids) {
  8369. if (!this.#groups.has(id)) {
  8370. (0, _util.warn)(`Optional content group not found: ${id}`);
  8371. return true;
  8372. }
  8373. if (this.#groups.get(id).visible) {
  8374. return false;
  8375. }
  8376. }
  8377. return true;
  8378. }
  8379. (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
  8380. return true;
  8381. }
  8382. (0, _util.warn)(`Unknown group type ${group.type}.`);
  8383. return true;
  8384. }
  8385. setVisibility(id, visible = true) {
  8386. if (!this.#groups.has(id)) {
  8387. (0, _util.warn)(`Optional content group not found: ${id}`);
  8388. return;
  8389. }
  8390. this.#groups.get(id)._setVisible(INTERNAL, !!visible);
  8391. this.#cachedGetHash = null;
  8392. }
  8393. get hasInitialVisibility() {
  8394. return this.getHash() === this.#initialHash;
  8395. }
  8396. getOrder() {
  8397. if (!this.#groups.size) {
  8398. return null;
  8399. }
  8400. if (this.#order) {
  8401. return this.#order.slice();
  8402. }
  8403. return [...this.#groups.keys()];
  8404. }
  8405. getGroups() {
  8406. return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  8407. }
  8408. getGroup(id) {
  8409. return this.#groups.get(id) || null;
  8410. }
  8411. getHash() {
  8412. if (this.#cachedGetHash !== null) {
  8413. return this.#cachedGetHash;
  8414. }
  8415. const hash = new _murmurhash.MurmurHash3_64();
  8416. for (const [id, group] of this.#groups) {
  8417. hash.update(`${id}:${group.visible}`);
  8418. }
  8419. return this.#cachedGetHash = hash.hexdigest();
  8420. }
  8421. }
  8422. exports.OptionalContentConfig = OptionalContentConfig;
  8423. /***/ }),
  8424. /* 18 */
  8425. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8426. Object.defineProperty(exports, "__esModule", ({
  8427. value: true
  8428. }));
  8429. exports.PDFDataTransportStream = void 0;
  8430. var _util = __w_pdfjs_require__(1);
  8431. var _display_utils = __w_pdfjs_require__(6);
  8432. class PDFDataTransportStream {
  8433. constructor({
  8434. length,
  8435. initialData,
  8436. progressiveDone = false,
  8437. contentDispositionFilename = null,
  8438. disableRange = false,
  8439. disableStream = false
  8440. }, pdfDataRangeTransport) {
  8441. (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  8442. this._queuedChunks = [];
  8443. this._progressiveDone = progressiveDone;
  8444. this._contentDispositionFilename = contentDispositionFilename;
  8445. if (initialData?.length > 0) {
  8446. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  8447. this._queuedChunks.push(buffer);
  8448. }
  8449. this._pdfDataRangeTransport = pdfDataRangeTransport;
  8450. this._isStreamingSupported = !disableStream;
  8451. this._isRangeSupported = !disableRange;
  8452. this._contentLength = length;
  8453. this._fullRequestReader = null;
  8454. this._rangeReaders = [];
  8455. this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  8456. this._onReceiveData({
  8457. begin,
  8458. chunk
  8459. });
  8460. });
  8461. this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
  8462. this._onProgress({
  8463. loaded,
  8464. total
  8465. });
  8466. });
  8467. this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  8468. this._onReceiveData({
  8469. chunk
  8470. });
  8471. });
  8472. this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
  8473. this._onProgressiveDone();
  8474. });
  8475. this._pdfDataRangeTransport.transportReady();
  8476. }
  8477. _onReceiveData({
  8478. begin,
  8479. chunk
  8480. }) {
  8481. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  8482. if (begin === undefined) {
  8483. if (this._fullRequestReader) {
  8484. this._fullRequestReader._enqueue(buffer);
  8485. } else {
  8486. this._queuedChunks.push(buffer);
  8487. }
  8488. } else {
  8489. const found = this._rangeReaders.some(function (rangeReader) {
  8490. if (rangeReader._begin !== begin) {
  8491. return false;
  8492. }
  8493. rangeReader._enqueue(buffer);
  8494. return true;
  8495. });
  8496. (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  8497. }
  8498. }
  8499. get _progressiveDataLength() {
  8500. return this._fullRequestReader?._loaded ?? 0;
  8501. }
  8502. _onProgress(evt) {
  8503. if (evt.total === undefined) {
  8504. this._rangeReaders[0]?.onProgress?.({
  8505. loaded: evt.loaded
  8506. });
  8507. } else {
  8508. this._fullRequestReader?.onProgress?.({
  8509. loaded: evt.loaded,
  8510. total: evt.total
  8511. });
  8512. }
  8513. }
  8514. _onProgressiveDone() {
  8515. this._fullRequestReader?.progressiveDone();
  8516. this._progressiveDone = true;
  8517. }
  8518. _removeRangeReader(reader) {
  8519. const i = this._rangeReaders.indexOf(reader);
  8520. if (i >= 0) {
  8521. this._rangeReaders.splice(i, 1);
  8522. }
  8523. }
  8524. getFullReader() {
  8525. (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  8526. const queuedChunks = this._queuedChunks;
  8527. this._queuedChunks = null;
  8528. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  8529. }
  8530. getRangeReader(begin, end) {
  8531. if (end <= this._progressiveDataLength) {
  8532. return null;
  8533. }
  8534. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  8535. this._pdfDataRangeTransport.requestDataRange(begin, end);
  8536. this._rangeReaders.push(reader);
  8537. return reader;
  8538. }
  8539. cancelAllRequests(reason) {
  8540. this._fullRequestReader?.cancel(reason);
  8541. for (const reader of this._rangeReaders.slice(0)) {
  8542. reader.cancel(reason);
  8543. }
  8544. this._pdfDataRangeTransport.abort();
  8545. }
  8546. }
  8547. exports.PDFDataTransportStream = PDFDataTransportStream;
  8548. class PDFDataTransportStreamReader {
  8549. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  8550. this._stream = stream;
  8551. this._done = progressiveDone || false;
  8552. this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
  8553. this._queuedChunks = queuedChunks || [];
  8554. this._loaded = 0;
  8555. for (const chunk of this._queuedChunks) {
  8556. this._loaded += chunk.byteLength;
  8557. }
  8558. this._requests = [];
  8559. this._headersReady = Promise.resolve();
  8560. stream._fullRequestReader = this;
  8561. this.onProgress = null;
  8562. }
  8563. _enqueue(chunk) {
  8564. if (this._done) {
  8565. return;
  8566. }
  8567. if (this._requests.length > 0) {
  8568. const requestCapability = this._requests.shift();
  8569. requestCapability.resolve({
  8570. value: chunk,
  8571. done: false
  8572. });
  8573. } else {
  8574. this._queuedChunks.push(chunk);
  8575. }
  8576. this._loaded += chunk.byteLength;
  8577. }
  8578. get headersReady() {
  8579. return this._headersReady;
  8580. }
  8581. get filename() {
  8582. return this._filename;
  8583. }
  8584. get isRangeSupported() {
  8585. return this._stream._isRangeSupported;
  8586. }
  8587. get isStreamingSupported() {
  8588. return this._stream._isStreamingSupported;
  8589. }
  8590. get contentLength() {
  8591. return this._stream._contentLength;
  8592. }
  8593. async read() {
  8594. if (this._queuedChunks.length > 0) {
  8595. const chunk = this._queuedChunks.shift();
  8596. return {
  8597. value: chunk,
  8598. done: false
  8599. };
  8600. }
  8601. if (this._done) {
  8602. return {
  8603. value: undefined,
  8604. done: true
  8605. };
  8606. }
  8607. const requestCapability = (0, _util.createPromiseCapability)();
  8608. this._requests.push(requestCapability);
  8609. return requestCapability.promise;
  8610. }
  8611. cancel(reason) {
  8612. this._done = true;
  8613. for (const requestCapability of this._requests) {
  8614. requestCapability.resolve({
  8615. value: undefined,
  8616. done: true
  8617. });
  8618. }
  8619. this._requests.length = 0;
  8620. }
  8621. progressiveDone() {
  8622. if (this._done) {
  8623. return;
  8624. }
  8625. this._done = true;
  8626. }
  8627. }
  8628. class PDFDataTransportStreamRangeReader {
  8629. constructor(stream, begin, end) {
  8630. this._stream = stream;
  8631. this._begin = begin;
  8632. this._end = end;
  8633. this._queuedChunk = null;
  8634. this._requests = [];
  8635. this._done = false;
  8636. this.onProgress = null;
  8637. }
  8638. _enqueue(chunk) {
  8639. if (this._done) {
  8640. return;
  8641. }
  8642. if (this._requests.length === 0) {
  8643. this._queuedChunk = chunk;
  8644. } else {
  8645. const requestsCapability = this._requests.shift();
  8646. requestsCapability.resolve({
  8647. value: chunk,
  8648. done: false
  8649. });
  8650. for (const requestCapability of this._requests) {
  8651. requestCapability.resolve({
  8652. value: undefined,
  8653. done: true
  8654. });
  8655. }
  8656. this._requests.length = 0;
  8657. }
  8658. this._done = true;
  8659. this._stream._removeRangeReader(this);
  8660. }
  8661. get isStreamingSupported() {
  8662. return false;
  8663. }
  8664. async read() {
  8665. if (this._queuedChunk) {
  8666. const chunk = this._queuedChunk;
  8667. this._queuedChunk = null;
  8668. return {
  8669. value: chunk,
  8670. done: false
  8671. };
  8672. }
  8673. if (this._done) {
  8674. return {
  8675. value: undefined,
  8676. done: true
  8677. };
  8678. }
  8679. const requestCapability = (0, _util.createPromiseCapability)();
  8680. this._requests.push(requestCapability);
  8681. return requestCapability.promise;
  8682. }
  8683. cancel(reason) {
  8684. this._done = true;
  8685. for (const requestCapability of this._requests) {
  8686. requestCapability.resolve({
  8687. value: undefined,
  8688. done: true
  8689. });
  8690. }
  8691. this._requests.length = 0;
  8692. this._stream._removeRangeReader(this);
  8693. }
  8694. }
  8695. /***/ }),
  8696. /* 19 */
  8697. /***/ ((__unused_webpack_module, exports) => {
  8698. Object.defineProperty(exports, "__esModule", ({
  8699. value: true
  8700. }));
  8701. exports.XfaText = void 0;
  8702. class XfaText {
  8703. static textContent(xfa) {
  8704. const items = [];
  8705. const output = {
  8706. items,
  8707. styles: Object.create(null)
  8708. };
  8709. function walk(node) {
  8710. if (!node) {
  8711. return;
  8712. }
  8713. let str = null;
  8714. const name = node.name;
  8715. if (name === "#text") {
  8716. str = node.value;
  8717. } else if (!XfaText.shouldBuildText(name)) {
  8718. return;
  8719. } else if (node?.attributes?.textContent) {
  8720. str = node.attributes.textContent;
  8721. } else if (node.value) {
  8722. str = node.value;
  8723. }
  8724. if (str !== null) {
  8725. items.push({
  8726. str
  8727. });
  8728. }
  8729. if (!node.children) {
  8730. return;
  8731. }
  8732. for (const child of node.children) {
  8733. walk(child);
  8734. }
  8735. }
  8736. walk(xfa);
  8737. return output;
  8738. }
  8739. static shouldBuildText(name) {
  8740. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  8741. }
  8742. }
  8743. exports.XfaText = XfaText;
  8744. /***/ }),
  8745. /* 20 */
  8746. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8747. Object.defineProperty(exports, "__esModule", ({
  8748. value: true
  8749. }));
  8750. exports.NodeStandardFontDataFactory = exports.NodeFilterFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
  8751. var _base_factory = __w_pdfjs_require__(7);
  8752. ;
  8753. const fetchData = function (url) {
  8754. return new Promise((resolve, reject) => {
  8755. const fs = require("fs");
  8756. fs.readFile(url, (error, data) => {
  8757. if (error || !data) {
  8758. reject(new Error(error));
  8759. return;
  8760. }
  8761. resolve(new Uint8Array(data));
  8762. });
  8763. });
  8764. };
  8765. class NodeFilterFactory extends _base_factory.BaseFilterFactory {}
  8766. exports.NodeFilterFactory = NodeFilterFactory;
  8767. class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  8768. _createCanvas(width, height) {
  8769. const Canvas = require("canvas");
  8770. return Canvas.createCanvas(width, height);
  8771. }
  8772. }
  8773. exports.NodeCanvasFactory = NodeCanvasFactory;
  8774. class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  8775. _fetchData(url, compressionType) {
  8776. return fetchData(url).then(data => {
  8777. return {
  8778. cMapData: data,
  8779. compressionType
  8780. };
  8781. });
  8782. }
  8783. }
  8784. exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
  8785. class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  8786. _fetchData(url) {
  8787. return fetchData(url);
  8788. }
  8789. }
  8790. exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
  8791. /***/ }),
  8792. /* 21 */
  8793. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  8794. Object.defineProperty(exports, "__esModule", ({
  8795. value: true
  8796. }));
  8797. exports.PDFNodeStream = void 0;
  8798. var _util = __w_pdfjs_require__(1);
  8799. var _network_utils = __w_pdfjs_require__(22);
  8800. ;
  8801. const fs = require("fs");
  8802. const http = require("http");
  8803. const https = require("https");
  8804. const url = require("url");
  8805. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  8806. function parseUrl(sourceUrl) {
  8807. const parsedUrl = url.parse(sourceUrl);
  8808. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  8809. return parsedUrl;
  8810. }
  8811. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  8812. return url.parse(`file:///${sourceUrl}`);
  8813. }
  8814. if (!parsedUrl.host) {
  8815. parsedUrl.protocol = "file:";
  8816. }
  8817. return parsedUrl;
  8818. }
  8819. class PDFNodeStream {
  8820. constructor(source) {
  8821. this.source = source;
  8822. this.url = parseUrl(source.url);
  8823. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  8824. this.isFsUrl = this.url.protocol === "file:";
  8825. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  8826. this._fullRequestReader = null;
  8827. this._rangeRequestReaders = [];
  8828. }
  8829. get _progressiveDataLength() {
  8830. return this._fullRequestReader?._loaded ?? 0;
  8831. }
  8832. getFullReader() {
  8833. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  8834. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  8835. return this._fullRequestReader;
  8836. }
  8837. getRangeReader(start, end) {
  8838. if (end <= this._progressiveDataLength) {
  8839. return null;
  8840. }
  8841. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  8842. this._rangeRequestReaders.push(rangeReader);
  8843. return rangeReader;
  8844. }
  8845. cancelAllRequests(reason) {
  8846. this._fullRequestReader?.cancel(reason);
  8847. for (const reader of this._rangeRequestReaders.slice(0)) {
  8848. reader.cancel(reason);
  8849. }
  8850. }
  8851. }
  8852. exports.PDFNodeStream = PDFNodeStream;
  8853. class BaseFullReader {
  8854. constructor(stream) {
  8855. this._url = stream.url;
  8856. this._done = false;
  8857. this._storedError = null;
  8858. this.onProgress = null;
  8859. const source = stream.source;
  8860. this._contentLength = source.length;
  8861. this._loaded = 0;
  8862. this._filename = null;
  8863. this._disableRange = source.disableRange || false;
  8864. this._rangeChunkSize = source.rangeChunkSize;
  8865. if (!this._rangeChunkSize && !this._disableRange) {
  8866. this._disableRange = true;
  8867. }
  8868. this._isStreamingSupported = !source.disableStream;
  8869. this._isRangeSupported = !source.disableRange;
  8870. this._readableStream = null;
  8871. this._readCapability = (0, _util.createPromiseCapability)();
  8872. this._headersCapability = (0, _util.createPromiseCapability)();
  8873. }
  8874. get headersReady() {
  8875. return this._headersCapability.promise;
  8876. }
  8877. get filename() {
  8878. return this._filename;
  8879. }
  8880. get contentLength() {
  8881. return this._contentLength;
  8882. }
  8883. get isRangeSupported() {
  8884. return this._isRangeSupported;
  8885. }
  8886. get isStreamingSupported() {
  8887. return this._isStreamingSupported;
  8888. }
  8889. async read() {
  8890. await this._readCapability.promise;
  8891. if (this._done) {
  8892. return {
  8893. value: undefined,
  8894. done: true
  8895. };
  8896. }
  8897. if (this._storedError) {
  8898. throw this._storedError;
  8899. }
  8900. const chunk = this._readableStream.read();
  8901. if (chunk === null) {
  8902. this._readCapability = (0, _util.createPromiseCapability)();
  8903. return this.read();
  8904. }
  8905. this._loaded += chunk.length;
  8906. this.onProgress?.({
  8907. loaded: this._loaded,
  8908. total: this._contentLength
  8909. });
  8910. const buffer = new Uint8Array(chunk).buffer;
  8911. return {
  8912. value: buffer,
  8913. done: false
  8914. };
  8915. }
  8916. cancel(reason) {
  8917. if (!this._readableStream) {
  8918. this._error(reason);
  8919. return;
  8920. }
  8921. this._readableStream.destroy(reason);
  8922. }
  8923. _error(reason) {
  8924. this._storedError = reason;
  8925. this._readCapability.resolve();
  8926. }
  8927. _setReadableStream(readableStream) {
  8928. this._readableStream = readableStream;
  8929. readableStream.on("readable", () => {
  8930. this._readCapability.resolve();
  8931. });
  8932. readableStream.on("end", () => {
  8933. readableStream.destroy();
  8934. this._done = true;
  8935. this._readCapability.resolve();
  8936. });
  8937. readableStream.on("error", reason => {
  8938. this._error(reason);
  8939. });
  8940. if (!this._isStreamingSupported && this._isRangeSupported) {
  8941. this._error(new _util.AbortException("streaming is disabled"));
  8942. }
  8943. if (this._storedError) {
  8944. this._readableStream.destroy(this._storedError);
  8945. }
  8946. }
  8947. }
  8948. class BaseRangeReader {
  8949. constructor(stream) {
  8950. this._url = stream.url;
  8951. this._done = false;
  8952. this._storedError = null;
  8953. this.onProgress = null;
  8954. this._loaded = 0;
  8955. this._readableStream = null;
  8956. this._readCapability = (0, _util.createPromiseCapability)();
  8957. const source = stream.source;
  8958. this._isStreamingSupported = !source.disableStream;
  8959. }
  8960. get isStreamingSupported() {
  8961. return this._isStreamingSupported;
  8962. }
  8963. async read() {
  8964. await this._readCapability.promise;
  8965. if (this._done) {
  8966. return {
  8967. value: undefined,
  8968. done: true
  8969. };
  8970. }
  8971. if (this._storedError) {
  8972. throw this._storedError;
  8973. }
  8974. const chunk = this._readableStream.read();
  8975. if (chunk === null) {
  8976. this._readCapability = (0, _util.createPromiseCapability)();
  8977. return this.read();
  8978. }
  8979. this._loaded += chunk.length;
  8980. this.onProgress?.({
  8981. loaded: this._loaded
  8982. });
  8983. const buffer = new Uint8Array(chunk).buffer;
  8984. return {
  8985. value: buffer,
  8986. done: false
  8987. };
  8988. }
  8989. cancel(reason) {
  8990. if (!this._readableStream) {
  8991. this._error(reason);
  8992. return;
  8993. }
  8994. this._readableStream.destroy(reason);
  8995. }
  8996. _error(reason) {
  8997. this._storedError = reason;
  8998. this._readCapability.resolve();
  8999. }
  9000. _setReadableStream(readableStream) {
  9001. this._readableStream = readableStream;
  9002. readableStream.on("readable", () => {
  9003. this._readCapability.resolve();
  9004. });
  9005. readableStream.on("end", () => {
  9006. readableStream.destroy();
  9007. this._done = true;
  9008. this._readCapability.resolve();
  9009. });
  9010. readableStream.on("error", reason => {
  9011. this._error(reason);
  9012. });
  9013. if (this._storedError) {
  9014. this._readableStream.destroy(this._storedError);
  9015. }
  9016. }
  9017. }
  9018. function createRequestOptions(parsedUrl, headers) {
  9019. return {
  9020. protocol: parsedUrl.protocol,
  9021. auth: parsedUrl.auth,
  9022. host: parsedUrl.hostname,
  9023. port: parsedUrl.port,
  9024. path: parsedUrl.path,
  9025. method: "GET",
  9026. headers
  9027. };
  9028. }
  9029. class PDFNodeStreamFullReader extends BaseFullReader {
  9030. constructor(stream) {
  9031. super(stream);
  9032. const handleResponse = response => {
  9033. if (response.statusCode === 404) {
  9034. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  9035. this._storedError = error;
  9036. this._headersCapability.reject(error);
  9037. return;
  9038. }
  9039. this._headersCapability.resolve();
  9040. this._setReadableStream(response);
  9041. const getResponseHeader = name => {
  9042. return this._readableStream.headers[name.toLowerCase()];
  9043. };
  9044. const {
  9045. allowRangeRequests,
  9046. suggestedLength
  9047. } = (0, _network_utils.validateRangeRequestCapabilities)({
  9048. getResponseHeader,
  9049. isHttp: stream.isHttp,
  9050. rangeChunkSize: this._rangeChunkSize,
  9051. disableRange: this._disableRange
  9052. });
  9053. this._isRangeSupported = allowRangeRequests;
  9054. this._contentLength = suggestedLength || this._contentLength;
  9055. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  9056. };
  9057. this._request = null;
  9058. if (this._url.protocol === "http:") {
  9059. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  9060. } else {
  9061. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  9062. }
  9063. this._request.on("error", reason => {
  9064. this._storedError = reason;
  9065. this._headersCapability.reject(reason);
  9066. });
  9067. this._request.end();
  9068. }
  9069. }
  9070. class PDFNodeStreamRangeReader extends BaseRangeReader {
  9071. constructor(stream, start, end) {
  9072. super(stream);
  9073. this._httpHeaders = {};
  9074. for (const property in stream.httpHeaders) {
  9075. const value = stream.httpHeaders[property];
  9076. if (value === undefined) {
  9077. continue;
  9078. }
  9079. this._httpHeaders[property] = value;
  9080. }
  9081. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  9082. const handleResponse = response => {
  9083. if (response.statusCode === 404) {
  9084. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  9085. this._storedError = error;
  9086. return;
  9087. }
  9088. this._setReadableStream(response);
  9089. };
  9090. this._request = null;
  9091. if (this._url.protocol === "http:") {
  9092. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  9093. } else {
  9094. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  9095. }
  9096. this._request.on("error", reason => {
  9097. this._storedError = reason;
  9098. });
  9099. this._request.end();
  9100. }
  9101. }
  9102. class PDFNodeStreamFsFullReader extends BaseFullReader {
  9103. constructor(stream) {
  9104. super(stream);
  9105. let path = decodeURIComponent(this._url.path);
  9106. if (fileUriRegex.test(this._url.href)) {
  9107. path = path.replace(/^\//, "");
  9108. }
  9109. fs.lstat(path, (error, stat) => {
  9110. if (error) {
  9111. if (error.code === "ENOENT") {
  9112. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  9113. }
  9114. this._storedError = error;
  9115. this._headersCapability.reject(error);
  9116. return;
  9117. }
  9118. this._contentLength = stat.size;
  9119. this._setReadableStream(fs.createReadStream(path));
  9120. this._headersCapability.resolve();
  9121. });
  9122. }
  9123. }
  9124. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  9125. constructor(stream, start, end) {
  9126. super(stream);
  9127. let path = decodeURIComponent(this._url.path);
  9128. if (fileUriRegex.test(this._url.href)) {
  9129. path = path.replace(/^\//, "");
  9130. }
  9131. this._setReadableStream(fs.createReadStream(path, {
  9132. start,
  9133. end: end - 1
  9134. }));
  9135. }
  9136. }
  9137. /***/ }),
  9138. /* 22 */
  9139. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9140. Object.defineProperty(exports, "__esModule", ({
  9141. value: true
  9142. }));
  9143. exports.createResponseStatusError = createResponseStatusError;
  9144. exports.extractFilenameFromHeader = extractFilenameFromHeader;
  9145. exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
  9146. exports.validateResponseStatus = validateResponseStatus;
  9147. var _util = __w_pdfjs_require__(1);
  9148. var _content_disposition = __w_pdfjs_require__(23);
  9149. var _display_utils = __w_pdfjs_require__(6);
  9150. function validateRangeRequestCapabilities({
  9151. getResponseHeader,
  9152. isHttp,
  9153. rangeChunkSize,
  9154. disableRange
  9155. }) {
  9156. const returnValues = {
  9157. allowRangeRequests: false,
  9158. suggestedLength: undefined
  9159. };
  9160. const length = parseInt(getResponseHeader("Content-Length"), 10);
  9161. if (!Number.isInteger(length)) {
  9162. return returnValues;
  9163. }
  9164. returnValues.suggestedLength = length;
  9165. if (length <= 2 * rangeChunkSize) {
  9166. return returnValues;
  9167. }
  9168. if (disableRange || !isHttp) {
  9169. return returnValues;
  9170. }
  9171. if (getResponseHeader("Accept-Ranges") !== "bytes") {
  9172. return returnValues;
  9173. }
  9174. const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  9175. if (contentEncoding !== "identity") {
  9176. return returnValues;
  9177. }
  9178. returnValues.allowRangeRequests = true;
  9179. return returnValues;
  9180. }
  9181. function extractFilenameFromHeader(getResponseHeader) {
  9182. const contentDisposition = getResponseHeader("Content-Disposition");
  9183. if (contentDisposition) {
  9184. let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
  9185. if (filename.includes("%")) {
  9186. try {
  9187. filename = decodeURIComponent(filename);
  9188. } catch (ex) {}
  9189. }
  9190. if ((0, _display_utils.isPdfFile)(filename)) {
  9191. return filename;
  9192. }
  9193. }
  9194. return null;
  9195. }
  9196. function createResponseStatusError(status, url) {
  9197. if (status === 404 || status === 0 && url.startsWith("file:")) {
  9198. return new _util.MissingPDFException('Missing PDF "' + url + '".');
  9199. }
  9200. return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  9201. }
  9202. function validateResponseStatus(status) {
  9203. return status === 200 || status === 206;
  9204. }
  9205. /***/ }),
  9206. /* 23 */
  9207. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9208. Object.defineProperty(exports, "__esModule", ({
  9209. value: true
  9210. }));
  9211. exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
  9212. var _util = __w_pdfjs_require__(1);
  9213. function getFilenameFromContentDispositionHeader(contentDisposition) {
  9214. let needsEncodingFixup = true;
  9215. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  9216. if (tmp) {
  9217. tmp = tmp[1];
  9218. let filename = rfc2616unquote(tmp);
  9219. filename = unescape(filename);
  9220. filename = rfc5987decode(filename);
  9221. filename = rfc2047decode(filename);
  9222. return fixupEncoding(filename);
  9223. }
  9224. tmp = rfc2231getparam(contentDisposition);
  9225. if (tmp) {
  9226. const filename = rfc2047decode(tmp);
  9227. return fixupEncoding(filename);
  9228. }
  9229. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  9230. if (tmp) {
  9231. tmp = tmp[1];
  9232. let filename = rfc2616unquote(tmp);
  9233. filename = rfc2047decode(filename);
  9234. return fixupEncoding(filename);
  9235. }
  9236. function toParamRegExp(attributePattern, flags) {
  9237. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  9238. }
  9239. function textdecode(encoding, value) {
  9240. if (encoding) {
  9241. if (!/^[\x00-\xFF]+$/.test(value)) {
  9242. return value;
  9243. }
  9244. try {
  9245. const decoder = new TextDecoder(encoding, {
  9246. fatal: true
  9247. });
  9248. const buffer = (0, _util.stringToBytes)(value);
  9249. value = decoder.decode(buffer);
  9250. needsEncodingFixup = false;
  9251. } catch (e) {}
  9252. }
  9253. return value;
  9254. }
  9255. function fixupEncoding(value) {
  9256. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  9257. value = textdecode("utf-8", value);
  9258. if (needsEncodingFixup) {
  9259. value = textdecode("iso-8859-1", value);
  9260. }
  9261. }
  9262. return value;
  9263. }
  9264. function rfc2231getparam(contentDispositionStr) {
  9265. const matches = [];
  9266. let match;
  9267. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  9268. while ((match = iter.exec(contentDispositionStr)) !== null) {
  9269. let [, n, quot, part] = match;
  9270. n = parseInt(n, 10);
  9271. if (n in matches) {
  9272. if (n === 0) {
  9273. break;
  9274. }
  9275. continue;
  9276. }
  9277. matches[n] = [quot, part];
  9278. }
  9279. const parts = [];
  9280. for (let n = 0; n < matches.length; ++n) {
  9281. if (!(n in matches)) {
  9282. break;
  9283. }
  9284. let [quot, part] = matches[n];
  9285. part = rfc2616unquote(part);
  9286. if (quot) {
  9287. part = unescape(part);
  9288. if (n === 0) {
  9289. part = rfc5987decode(part);
  9290. }
  9291. }
  9292. parts.push(part);
  9293. }
  9294. return parts.join("");
  9295. }
  9296. function rfc2616unquote(value) {
  9297. if (value.startsWith('"')) {
  9298. const parts = value.slice(1).split('\\"');
  9299. for (let i = 0; i < parts.length; ++i) {
  9300. const quotindex = parts[i].indexOf('"');
  9301. if (quotindex !== -1) {
  9302. parts[i] = parts[i].slice(0, quotindex);
  9303. parts.length = i + 1;
  9304. }
  9305. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  9306. }
  9307. value = parts.join('"');
  9308. }
  9309. return value;
  9310. }
  9311. function rfc5987decode(extvalue) {
  9312. const encodingend = extvalue.indexOf("'");
  9313. if (encodingend === -1) {
  9314. return extvalue;
  9315. }
  9316. const encoding = extvalue.slice(0, encodingend);
  9317. const langvalue = extvalue.slice(encodingend + 1);
  9318. const value = langvalue.replace(/^[^']*'/, "");
  9319. return textdecode(encoding, value);
  9320. }
  9321. function rfc2047decode(value) {
  9322. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  9323. return value;
  9324. }
  9325. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  9326. if (encoding === "q" || encoding === "Q") {
  9327. text = text.replaceAll("_", " ");
  9328. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  9329. return String.fromCharCode(parseInt(hex, 16));
  9330. });
  9331. return textdecode(charset, text);
  9332. }
  9333. try {
  9334. text = atob(text);
  9335. } catch (e) {}
  9336. return textdecode(charset, text);
  9337. });
  9338. }
  9339. return "";
  9340. }
  9341. /***/ }),
  9342. /* 24 */
  9343. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9344. Object.defineProperty(exports, "__esModule", ({
  9345. value: true
  9346. }));
  9347. exports.PDFNetworkStream = void 0;
  9348. var _util = __w_pdfjs_require__(1);
  9349. var _network_utils = __w_pdfjs_require__(22);
  9350. ;
  9351. const OK_RESPONSE = 200;
  9352. const PARTIAL_CONTENT_RESPONSE = 206;
  9353. function getArrayBuffer(xhr) {
  9354. const data = xhr.response;
  9355. if (typeof data !== "string") {
  9356. return data;
  9357. }
  9358. return (0, _util.stringToBytes)(data).buffer;
  9359. }
  9360. class NetworkManager {
  9361. constructor(url, args = {}) {
  9362. this.url = url;
  9363. this.isHttp = /^https?:/i.test(url);
  9364. this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
  9365. this.withCredentials = args.withCredentials || false;
  9366. this.getXhr = args.getXhr || function NetworkManager_getXhr() {
  9367. return new XMLHttpRequest();
  9368. };
  9369. this.currXhrId = 0;
  9370. this.pendingRequests = Object.create(null);
  9371. }
  9372. requestRange(begin, end, listeners) {
  9373. const args = {
  9374. begin,
  9375. end
  9376. };
  9377. for (const prop in listeners) {
  9378. args[prop] = listeners[prop];
  9379. }
  9380. return this.request(args);
  9381. }
  9382. requestFull(listeners) {
  9383. return this.request(listeners);
  9384. }
  9385. request(args) {
  9386. const xhr = this.getXhr();
  9387. const xhrId = this.currXhrId++;
  9388. const pendingRequest = this.pendingRequests[xhrId] = {
  9389. xhr
  9390. };
  9391. xhr.open("GET", this.url);
  9392. xhr.withCredentials = this.withCredentials;
  9393. for (const property in this.httpHeaders) {
  9394. const value = this.httpHeaders[property];
  9395. if (value === undefined) {
  9396. continue;
  9397. }
  9398. xhr.setRequestHeader(property, value);
  9399. }
  9400. if (this.isHttp && "begin" in args && "end" in args) {
  9401. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  9402. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  9403. } else {
  9404. pendingRequest.expectedStatus = OK_RESPONSE;
  9405. }
  9406. xhr.responseType = "arraybuffer";
  9407. if (args.onError) {
  9408. xhr.onerror = function (evt) {
  9409. args.onError(xhr.status);
  9410. };
  9411. }
  9412. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  9413. xhr.onprogress = this.onProgress.bind(this, xhrId);
  9414. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  9415. pendingRequest.onDone = args.onDone;
  9416. pendingRequest.onError = args.onError;
  9417. pendingRequest.onProgress = args.onProgress;
  9418. xhr.send(null);
  9419. return xhrId;
  9420. }
  9421. onProgress(xhrId, evt) {
  9422. const pendingRequest = this.pendingRequests[xhrId];
  9423. if (!pendingRequest) {
  9424. return;
  9425. }
  9426. pendingRequest.onProgress?.(evt);
  9427. }
  9428. onStateChange(xhrId, evt) {
  9429. const pendingRequest = this.pendingRequests[xhrId];
  9430. if (!pendingRequest) {
  9431. return;
  9432. }
  9433. const xhr = pendingRequest.xhr;
  9434. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  9435. pendingRequest.onHeadersReceived();
  9436. delete pendingRequest.onHeadersReceived;
  9437. }
  9438. if (xhr.readyState !== 4) {
  9439. return;
  9440. }
  9441. if (!(xhrId in this.pendingRequests)) {
  9442. return;
  9443. }
  9444. delete this.pendingRequests[xhrId];
  9445. if (xhr.status === 0 && this.isHttp) {
  9446. pendingRequest.onError?.(xhr.status);
  9447. return;
  9448. }
  9449. const xhrStatus = xhr.status || OK_RESPONSE;
  9450. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  9451. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  9452. pendingRequest.onError?.(xhr.status);
  9453. return;
  9454. }
  9455. const chunk = getArrayBuffer(xhr);
  9456. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  9457. const rangeHeader = xhr.getResponseHeader("Content-Range");
  9458. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  9459. pendingRequest.onDone({
  9460. begin: parseInt(matches[1], 10),
  9461. chunk
  9462. });
  9463. } else if (chunk) {
  9464. pendingRequest.onDone({
  9465. begin: 0,
  9466. chunk
  9467. });
  9468. } else {
  9469. pendingRequest.onError?.(xhr.status);
  9470. }
  9471. }
  9472. getRequestXhr(xhrId) {
  9473. return this.pendingRequests[xhrId].xhr;
  9474. }
  9475. isPendingRequest(xhrId) {
  9476. return xhrId in this.pendingRequests;
  9477. }
  9478. abortRequest(xhrId) {
  9479. const xhr = this.pendingRequests[xhrId].xhr;
  9480. delete this.pendingRequests[xhrId];
  9481. xhr.abort();
  9482. }
  9483. }
  9484. class PDFNetworkStream {
  9485. constructor(source) {
  9486. this._source = source;
  9487. this._manager = new NetworkManager(source.url, {
  9488. httpHeaders: source.httpHeaders,
  9489. withCredentials: source.withCredentials
  9490. });
  9491. this._rangeChunkSize = source.rangeChunkSize;
  9492. this._fullRequestReader = null;
  9493. this._rangeRequestReaders = [];
  9494. }
  9495. _onRangeRequestReaderClosed(reader) {
  9496. const i = this._rangeRequestReaders.indexOf(reader);
  9497. if (i >= 0) {
  9498. this._rangeRequestReaders.splice(i, 1);
  9499. }
  9500. }
  9501. getFullReader() {
  9502. (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  9503. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  9504. return this._fullRequestReader;
  9505. }
  9506. getRangeReader(begin, end) {
  9507. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  9508. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  9509. this._rangeRequestReaders.push(reader);
  9510. return reader;
  9511. }
  9512. cancelAllRequests(reason) {
  9513. this._fullRequestReader?.cancel(reason);
  9514. for (const reader of this._rangeRequestReaders.slice(0)) {
  9515. reader.cancel(reason);
  9516. }
  9517. }
  9518. }
  9519. exports.PDFNetworkStream = PDFNetworkStream;
  9520. class PDFNetworkStreamFullRequestReader {
  9521. constructor(manager, source) {
  9522. this._manager = manager;
  9523. const args = {
  9524. onHeadersReceived: this._onHeadersReceived.bind(this),
  9525. onDone: this._onDone.bind(this),
  9526. onError: this._onError.bind(this),
  9527. onProgress: this._onProgress.bind(this)
  9528. };
  9529. this._url = source.url;
  9530. this._fullRequestId = manager.requestFull(args);
  9531. this._headersReceivedCapability = (0, _util.createPromiseCapability)();
  9532. this._disableRange = source.disableRange || false;
  9533. this._contentLength = source.length;
  9534. this._rangeChunkSize = source.rangeChunkSize;
  9535. if (!this._rangeChunkSize && !this._disableRange) {
  9536. this._disableRange = true;
  9537. }
  9538. this._isStreamingSupported = false;
  9539. this._isRangeSupported = false;
  9540. this._cachedChunks = [];
  9541. this._requests = [];
  9542. this._done = false;
  9543. this._storedError = undefined;
  9544. this._filename = null;
  9545. this.onProgress = null;
  9546. }
  9547. _onHeadersReceived() {
  9548. const fullRequestXhrId = this._fullRequestId;
  9549. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  9550. const getResponseHeader = name => {
  9551. return fullRequestXhr.getResponseHeader(name);
  9552. };
  9553. const {
  9554. allowRangeRequests,
  9555. suggestedLength
  9556. } = (0, _network_utils.validateRangeRequestCapabilities)({
  9557. getResponseHeader,
  9558. isHttp: this._manager.isHttp,
  9559. rangeChunkSize: this._rangeChunkSize,
  9560. disableRange: this._disableRange
  9561. });
  9562. if (allowRangeRequests) {
  9563. this._isRangeSupported = true;
  9564. }
  9565. this._contentLength = suggestedLength || this._contentLength;
  9566. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  9567. if (this._isRangeSupported) {
  9568. this._manager.abortRequest(fullRequestXhrId);
  9569. }
  9570. this._headersReceivedCapability.resolve();
  9571. }
  9572. _onDone(data) {
  9573. if (data) {
  9574. if (this._requests.length > 0) {
  9575. const requestCapability = this._requests.shift();
  9576. requestCapability.resolve({
  9577. value: data.chunk,
  9578. done: false
  9579. });
  9580. } else {
  9581. this._cachedChunks.push(data.chunk);
  9582. }
  9583. }
  9584. this._done = true;
  9585. if (this._cachedChunks.length > 0) {
  9586. return;
  9587. }
  9588. for (const requestCapability of this._requests) {
  9589. requestCapability.resolve({
  9590. value: undefined,
  9591. done: true
  9592. });
  9593. }
  9594. this._requests.length = 0;
  9595. }
  9596. _onError(status) {
  9597. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  9598. this._headersReceivedCapability.reject(this._storedError);
  9599. for (const requestCapability of this._requests) {
  9600. requestCapability.reject(this._storedError);
  9601. }
  9602. this._requests.length = 0;
  9603. this._cachedChunks.length = 0;
  9604. }
  9605. _onProgress(evt) {
  9606. this.onProgress?.({
  9607. loaded: evt.loaded,
  9608. total: evt.lengthComputable ? evt.total : this._contentLength
  9609. });
  9610. }
  9611. get filename() {
  9612. return this._filename;
  9613. }
  9614. get isRangeSupported() {
  9615. return this._isRangeSupported;
  9616. }
  9617. get isStreamingSupported() {
  9618. return this._isStreamingSupported;
  9619. }
  9620. get contentLength() {
  9621. return this._contentLength;
  9622. }
  9623. get headersReady() {
  9624. return this._headersReceivedCapability.promise;
  9625. }
  9626. async read() {
  9627. if (this._storedError) {
  9628. throw this._storedError;
  9629. }
  9630. if (this._cachedChunks.length > 0) {
  9631. const chunk = this._cachedChunks.shift();
  9632. return {
  9633. value: chunk,
  9634. done: false
  9635. };
  9636. }
  9637. if (this._done) {
  9638. return {
  9639. value: undefined,
  9640. done: true
  9641. };
  9642. }
  9643. const requestCapability = (0, _util.createPromiseCapability)();
  9644. this._requests.push(requestCapability);
  9645. return requestCapability.promise;
  9646. }
  9647. cancel(reason) {
  9648. this._done = true;
  9649. this._headersReceivedCapability.reject(reason);
  9650. for (const requestCapability of this._requests) {
  9651. requestCapability.resolve({
  9652. value: undefined,
  9653. done: true
  9654. });
  9655. }
  9656. this._requests.length = 0;
  9657. if (this._manager.isPendingRequest(this._fullRequestId)) {
  9658. this._manager.abortRequest(this._fullRequestId);
  9659. }
  9660. this._fullRequestReader = null;
  9661. }
  9662. }
  9663. class PDFNetworkStreamRangeRequestReader {
  9664. constructor(manager, begin, end) {
  9665. this._manager = manager;
  9666. const args = {
  9667. onDone: this._onDone.bind(this),
  9668. onError: this._onError.bind(this),
  9669. onProgress: this._onProgress.bind(this)
  9670. };
  9671. this._url = manager.url;
  9672. this._requestId = manager.requestRange(begin, end, args);
  9673. this._requests = [];
  9674. this._queuedChunk = null;
  9675. this._done = false;
  9676. this._storedError = undefined;
  9677. this.onProgress = null;
  9678. this.onClosed = null;
  9679. }
  9680. _close() {
  9681. this.onClosed?.(this);
  9682. }
  9683. _onDone(data) {
  9684. const chunk = data.chunk;
  9685. if (this._requests.length > 0) {
  9686. const requestCapability = this._requests.shift();
  9687. requestCapability.resolve({
  9688. value: chunk,
  9689. done: false
  9690. });
  9691. } else {
  9692. this._queuedChunk = chunk;
  9693. }
  9694. this._done = true;
  9695. for (const requestCapability of this._requests) {
  9696. requestCapability.resolve({
  9697. value: undefined,
  9698. done: true
  9699. });
  9700. }
  9701. this._requests.length = 0;
  9702. this._close();
  9703. }
  9704. _onError(status) {
  9705. this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
  9706. for (const requestCapability of this._requests) {
  9707. requestCapability.reject(this._storedError);
  9708. }
  9709. this._requests.length = 0;
  9710. this._queuedChunk = null;
  9711. }
  9712. _onProgress(evt) {
  9713. if (!this.isStreamingSupported) {
  9714. this.onProgress?.({
  9715. loaded: evt.loaded
  9716. });
  9717. }
  9718. }
  9719. get isStreamingSupported() {
  9720. return false;
  9721. }
  9722. async read() {
  9723. if (this._storedError) {
  9724. throw this._storedError;
  9725. }
  9726. if (this._queuedChunk !== null) {
  9727. const chunk = this._queuedChunk;
  9728. this._queuedChunk = null;
  9729. return {
  9730. value: chunk,
  9731. done: false
  9732. };
  9733. }
  9734. if (this._done) {
  9735. return {
  9736. value: undefined,
  9737. done: true
  9738. };
  9739. }
  9740. const requestCapability = (0, _util.createPromiseCapability)();
  9741. this._requests.push(requestCapability);
  9742. return requestCapability.promise;
  9743. }
  9744. cancel(reason) {
  9745. this._done = true;
  9746. for (const requestCapability of this._requests) {
  9747. requestCapability.resolve({
  9748. value: undefined,
  9749. done: true
  9750. });
  9751. }
  9752. this._requests.length = 0;
  9753. if (this._manager.isPendingRequest(this._requestId)) {
  9754. this._manager.abortRequest(this._requestId);
  9755. }
  9756. this._close();
  9757. }
  9758. }
  9759. /***/ }),
  9760. /* 25 */
  9761. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9762. Object.defineProperty(exports, "__esModule", ({
  9763. value: true
  9764. }));
  9765. exports.PDFFetchStream = void 0;
  9766. var _util = __w_pdfjs_require__(1);
  9767. var _network_utils = __w_pdfjs_require__(22);
  9768. ;
  9769. function createFetchOptions(headers, withCredentials, abortController) {
  9770. return {
  9771. method: "GET",
  9772. headers,
  9773. signal: abortController.signal,
  9774. mode: "cors",
  9775. credentials: withCredentials ? "include" : "same-origin",
  9776. redirect: "follow"
  9777. };
  9778. }
  9779. function createHeaders(httpHeaders) {
  9780. const headers = new Headers();
  9781. for (const property in httpHeaders) {
  9782. const value = httpHeaders[property];
  9783. if (value === undefined) {
  9784. continue;
  9785. }
  9786. headers.append(property, value);
  9787. }
  9788. return headers;
  9789. }
  9790. function getArrayBuffer(val) {
  9791. if (val instanceof Uint8Array) {
  9792. return val.buffer;
  9793. }
  9794. if (val instanceof ArrayBuffer) {
  9795. return val;
  9796. }
  9797. (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`);
  9798. return new Uint8Array(val).buffer;
  9799. }
  9800. class PDFFetchStream {
  9801. constructor(source) {
  9802. this.source = source;
  9803. this.isHttp = /^https?:/i.test(source.url);
  9804. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  9805. this._fullRequestReader = null;
  9806. this._rangeRequestReaders = [];
  9807. }
  9808. get _progressiveDataLength() {
  9809. return this._fullRequestReader?._loaded ?? 0;
  9810. }
  9811. getFullReader() {
  9812. (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  9813. this._fullRequestReader = new PDFFetchStreamReader(this);
  9814. return this._fullRequestReader;
  9815. }
  9816. getRangeReader(begin, end) {
  9817. if (end <= this._progressiveDataLength) {
  9818. return null;
  9819. }
  9820. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  9821. this._rangeRequestReaders.push(reader);
  9822. return reader;
  9823. }
  9824. cancelAllRequests(reason) {
  9825. this._fullRequestReader?.cancel(reason);
  9826. for (const reader of this._rangeRequestReaders.slice(0)) {
  9827. reader.cancel(reason);
  9828. }
  9829. }
  9830. }
  9831. exports.PDFFetchStream = PDFFetchStream;
  9832. class PDFFetchStreamReader {
  9833. constructor(stream) {
  9834. this._stream = stream;
  9835. this._reader = null;
  9836. this._loaded = 0;
  9837. this._filename = null;
  9838. const source = stream.source;
  9839. this._withCredentials = source.withCredentials || false;
  9840. this._contentLength = source.length;
  9841. this._headersCapability = (0, _util.createPromiseCapability)();
  9842. this._disableRange = source.disableRange || false;
  9843. this._rangeChunkSize = source.rangeChunkSize;
  9844. if (!this._rangeChunkSize && !this._disableRange) {
  9845. this._disableRange = true;
  9846. }
  9847. this._abortController = new AbortController();
  9848. this._isStreamingSupported = !source.disableStream;
  9849. this._isRangeSupported = !source.disableRange;
  9850. this._headers = createHeaders(this._stream.httpHeaders);
  9851. const url = source.url;
  9852. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  9853. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  9854. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  9855. }
  9856. this._reader = response.body.getReader();
  9857. this._headersCapability.resolve();
  9858. const getResponseHeader = name => {
  9859. return response.headers.get(name);
  9860. };
  9861. const {
  9862. allowRangeRequests,
  9863. suggestedLength
  9864. } = (0, _network_utils.validateRangeRequestCapabilities)({
  9865. getResponseHeader,
  9866. isHttp: this._stream.isHttp,
  9867. rangeChunkSize: this._rangeChunkSize,
  9868. disableRange: this._disableRange
  9869. });
  9870. this._isRangeSupported = allowRangeRequests;
  9871. this._contentLength = suggestedLength || this._contentLength;
  9872. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  9873. if (!this._isStreamingSupported && this._isRangeSupported) {
  9874. this.cancel(new _util.AbortException("Streaming is disabled."));
  9875. }
  9876. }).catch(this._headersCapability.reject);
  9877. this.onProgress = null;
  9878. }
  9879. get headersReady() {
  9880. return this._headersCapability.promise;
  9881. }
  9882. get filename() {
  9883. return this._filename;
  9884. }
  9885. get contentLength() {
  9886. return this._contentLength;
  9887. }
  9888. get isRangeSupported() {
  9889. return this._isRangeSupported;
  9890. }
  9891. get isStreamingSupported() {
  9892. return this._isStreamingSupported;
  9893. }
  9894. async read() {
  9895. await this._headersCapability.promise;
  9896. const {
  9897. value,
  9898. done
  9899. } = await this._reader.read();
  9900. if (done) {
  9901. return {
  9902. value,
  9903. done
  9904. };
  9905. }
  9906. this._loaded += value.byteLength;
  9907. this.onProgress?.({
  9908. loaded: this._loaded,
  9909. total: this._contentLength
  9910. });
  9911. return {
  9912. value: getArrayBuffer(value),
  9913. done: false
  9914. };
  9915. }
  9916. cancel(reason) {
  9917. this._reader?.cancel(reason);
  9918. this._abortController.abort();
  9919. }
  9920. }
  9921. class PDFFetchStreamRangeReader {
  9922. constructor(stream, begin, end) {
  9923. this._stream = stream;
  9924. this._reader = null;
  9925. this._loaded = 0;
  9926. const source = stream.source;
  9927. this._withCredentials = source.withCredentials || false;
  9928. this._readCapability = (0, _util.createPromiseCapability)();
  9929. this._isStreamingSupported = !source.disableStream;
  9930. this._abortController = new AbortController();
  9931. this._headers = createHeaders(this._stream.httpHeaders);
  9932. this._headers.append("Range", `bytes=${begin}-${end - 1}`);
  9933. const url = source.url;
  9934. fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
  9935. if (!(0, _network_utils.validateResponseStatus)(response.status)) {
  9936. throw (0, _network_utils.createResponseStatusError)(response.status, url);
  9937. }
  9938. this._readCapability.resolve();
  9939. this._reader = response.body.getReader();
  9940. }).catch(this._readCapability.reject);
  9941. this.onProgress = null;
  9942. }
  9943. get isStreamingSupported() {
  9944. return this._isStreamingSupported;
  9945. }
  9946. async read() {
  9947. await this._readCapability.promise;
  9948. const {
  9949. value,
  9950. done
  9951. } = await this._reader.read();
  9952. if (done) {
  9953. return {
  9954. value,
  9955. done
  9956. };
  9957. }
  9958. this._loaded += value.byteLength;
  9959. this.onProgress?.({
  9960. loaded: this._loaded
  9961. });
  9962. return {
  9963. value: getArrayBuffer(value),
  9964. done: false
  9965. };
  9966. }
  9967. cancel(reason) {
  9968. this._reader?.cancel(reason);
  9969. this._abortController.abort();
  9970. }
  9971. }
  9972. /***/ }),
  9973. /* 26 */
  9974. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  9975. Object.defineProperty(exports, "__esModule", ({
  9976. value: true
  9977. }));
  9978. exports.TextLayerRenderTask = void 0;
  9979. exports.renderTextLayer = renderTextLayer;
  9980. exports.updateTextLayer = updateTextLayer;
  9981. var _util = __w_pdfjs_require__(1);
  9982. var _display_utils = __w_pdfjs_require__(6);
  9983. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  9984. const DEFAULT_FONT_SIZE = 30;
  9985. const DEFAULT_FONT_ASCENT = 0.8;
  9986. const ascentCache = new Map();
  9987. function getCtx(size, isOffscreenCanvasSupported) {
  9988. let ctx;
  9989. if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
  9990. ctx = new OffscreenCanvas(size, size).getContext("2d", {
  9991. alpha: false
  9992. });
  9993. } else {
  9994. const canvas = document.createElement("canvas");
  9995. canvas.width = canvas.height = size;
  9996. ctx = canvas.getContext("2d", {
  9997. alpha: false
  9998. });
  9999. }
  10000. return ctx;
  10001. }
  10002. function getAscent(fontFamily, isOffscreenCanvasSupported) {
  10003. const cachedAscent = ascentCache.get(fontFamily);
  10004. if (cachedAscent) {
  10005. return cachedAscent;
  10006. }
  10007. const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
  10008. ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  10009. const metrics = ctx.measureText("");
  10010. let ascent = metrics.fontBoundingBoxAscent;
  10011. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  10012. if (ascent) {
  10013. const ratio = ascent / (ascent + descent);
  10014. ascentCache.set(fontFamily, ratio);
  10015. ctx.canvas.width = ctx.canvas.height = 0;
  10016. return ratio;
  10017. }
  10018. ctx.strokeStyle = "red";
  10019. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  10020. ctx.strokeText("g", 0, 0);
  10021. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  10022. descent = 0;
  10023. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  10024. if (pixels[i] > 0) {
  10025. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  10026. break;
  10027. }
  10028. }
  10029. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  10030. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  10031. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  10032. ascent = 0;
  10033. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  10034. if (pixels[i] > 0) {
  10035. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  10036. break;
  10037. }
  10038. }
  10039. ctx.canvas.width = ctx.canvas.height = 0;
  10040. if (ascent) {
  10041. const ratio = ascent / (ascent + descent);
  10042. ascentCache.set(fontFamily, ratio);
  10043. return ratio;
  10044. }
  10045. ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  10046. return DEFAULT_FONT_ASCENT;
  10047. }
  10048. function appendText(task, geom, styles) {
  10049. const textDiv = document.createElement("span");
  10050. const textDivProperties = {
  10051. angle: 0,
  10052. canvasWidth: 0,
  10053. hasText: geom.str !== "",
  10054. hasEOL: geom.hasEOL,
  10055. fontSize: 0
  10056. };
  10057. task._textDivs.push(textDiv);
  10058. const tx = _util.Util.transform(task._transform, geom.transform);
  10059. let angle = Math.atan2(tx[1], tx[0]);
  10060. const style = styles[geom.fontName];
  10061. if (style.vertical) {
  10062. angle += Math.PI / 2;
  10063. }
  10064. const fontHeight = Math.hypot(tx[2], tx[3]);
  10065. const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
  10066. let left, top;
  10067. if (angle === 0) {
  10068. left = tx[4];
  10069. top = tx[5] - fontAscent;
  10070. } else {
  10071. left = tx[4] + fontAscent * Math.sin(angle);
  10072. top = tx[5] - fontAscent * Math.cos(angle);
  10073. }
  10074. const scaleFactorStr = "calc(var(--scale-factor)*";
  10075. const divStyle = textDiv.style;
  10076. if (task._container === task._rootContainer) {
  10077. divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
  10078. divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
  10079. } else {
  10080. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  10081. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  10082. }
  10083. divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
  10084. divStyle.fontFamily = style.fontFamily;
  10085. textDivProperties.fontSize = fontHeight;
  10086. textDiv.setAttribute("role", "presentation");
  10087. textDiv.textContent = geom.str;
  10088. textDiv.dir = geom.dir;
  10089. if (task._fontInspectorEnabled) {
  10090. textDiv.dataset.fontName = geom.fontName;
  10091. }
  10092. if (angle !== 0) {
  10093. textDivProperties.angle = angle * (180 / Math.PI);
  10094. }
  10095. let shouldScaleText = false;
  10096. if (geom.str.length > 1) {
  10097. shouldScaleText = true;
  10098. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  10099. const absScaleX = Math.abs(geom.transform[0]),
  10100. absScaleY = Math.abs(geom.transform[3]);
  10101. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  10102. shouldScaleText = true;
  10103. }
  10104. }
  10105. if (shouldScaleText) {
  10106. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  10107. }
  10108. task._textDivProperties.set(textDiv, textDivProperties);
  10109. if (task._isReadableStream) {
  10110. task._layoutText(textDiv);
  10111. }
  10112. }
  10113. function layout(params) {
  10114. const {
  10115. div,
  10116. scale,
  10117. properties,
  10118. ctx,
  10119. prevFontSize,
  10120. prevFontFamily
  10121. } = params;
  10122. const {
  10123. style
  10124. } = div;
  10125. let transform = "";
  10126. if (properties.canvasWidth !== 0 && properties.hasText) {
  10127. const {
  10128. fontFamily
  10129. } = style;
  10130. const {
  10131. canvasWidth,
  10132. fontSize
  10133. } = properties;
  10134. if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
  10135. ctx.font = `${fontSize * scale}px ${fontFamily}`;
  10136. params.prevFontSize = fontSize;
  10137. params.prevFontFamily = fontFamily;
  10138. }
  10139. const {
  10140. width
  10141. } = ctx.measureText(div.textContent);
  10142. if (width > 0) {
  10143. transform = `scaleX(${canvasWidth * scale / width})`;
  10144. }
  10145. }
  10146. if (properties.angle !== 0) {
  10147. transform = `rotate(${properties.angle}deg) ${transform}`;
  10148. }
  10149. if (transform.length > 0) {
  10150. style.transform = transform;
  10151. }
  10152. }
  10153. function render(task) {
  10154. if (task._canceled) {
  10155. return;
  10156. }
  10157. const textDivs = task._textDivs;
  10158. const capability = task._capability;
  10159. const textDivsLength = textDivs.length;
  10160. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  10161. capability.resolve();
  10162. return;
  10163. }
  10164. if (!task._isReadableStream) {
  10165. for (const textDiv of textDivs) {
  10166. task._layoutText(textDiv);
  10167. }
  10168. }
  10169. capability.resolve();
  10170. }
  10171. class TextLayerRenderTask {
  10172. constructor({
  10173. textContentSource,
  10174. container,
  10175. viewport,
  10176. textDivs,
  10177. textDivProperties,
  10178. textContentItemsStr,
  10179. isOffscreenCanvasSupported
  10180. }) {
  10181. this._textContentSource = textContentSource;
  10182. this._isReadableStream = textContentSource instanceof ReadableStream;
  10183. this._container = this._rootContainer = container;
  10184. this._textDivs = textDivs || [];
  10185. this._textContentItemsStr = textContentItemsStr || [];
  10186. this._isOffscreenCanvasSupported = isOffscreenCanvasSupported;
  10187. this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  10188. this._reader = null;
  10189. this._textDivProperties = textDivProperties || new WeakMap();
  10190. this._canceled = false;
  10191. this._capability = (0, _util.createPromiseCapability)();
  10192. this._layoutTextParams = {
  10193. prevFontSize: null,
  10194. prevFontFamily: null,
  10195. div: null,
  10196. scale: viewport.scale * (globalThis.devicePixelRatio || 1),
  10197. properties: null,
  10198. ctx: getCtx(0, isOffscreenCanvasSupported)
  10199. };
  10200. const {
  10201. pageWidth,
  10202. pageHeight,
  10203. pageX,
  10204. pageY
  10205. } = viewport.rawDims;
  10206. this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  10207. this._pageWidth = pageWidth;
  10208. this._pageHeight = pageHeight;
  10209. (0, _display_utils.setLayerDimensions)(container, viewport);
  10210. this._capability.promise.finally(() => {
  10211. this._layoutTextParams = null;
  10212. }).catch(() => {});
  10213. }
  10214. get promise() {
  10215. return this._capability.promise;
  10216. }
  10217. cancel() {
  10218. this._canceled = true;
  10219. if (this._reader) {
  10220. this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
  10221. this._reader = null;
  10222. }
  10223. this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
  10224. }
  10225. _processItems(items, styleCache) {
  10226. for (const item of items) {
  10227. if (item.str === undefined) {
  10228. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  10229. const parent = this._container;
  10230. this._container = document.createElement("span");
  10231. this._container.classList.add("markedContent");
  10232. if (item.id !== null) {
  10233. this._container.setAttribute("id", `${item.id}`);
  10234. }
  10235. parent.append(this._container);
  10236. } else if (item.type === "endMarkedContent") {
  10237. this._container = this._container.parentNode;
  10238. }
  10239. continue;
  10240. }
  10241. this._textContentItemsStr.push(item.str);
  10242. appendText(this, item, styleCache);
  10243. }
  10244. }
  10245. _layoutText(textDiv) {
  10246. const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
  10247. this._layoutTextParams.div = textDiv;
  10248. layout(this._layoutTextParams);
  10249. if (textDivProperties.hasText) {
  10250. this._container.append(textDiv);
  10251. }
  10252. if (textDivProperties.hasEOL) {
  10253. const br = document.createElement("br");
  10254. br.setAttribute("role", "presentation");
  10255. this._container.append(br);
  10256. }
  10257. }
  10258. _render() {
  10259. const capability = (0, _util.createPromiseCapability)();
  10260. let styleCache = Object.create(null);
  10261. if (this._isReadableStream) {
  10262. const pump = () => {
  10263. this._reader.read().then(({
  10264. value,
  10265. done
  10266. }) => {
  10267. if (done) {
  10268. capability.resolve();
  10269. return;
  10270. }
  10271. Object.assign(styleCache, value.styles);
  10272. this._processItems(value.items, styleCache);
  10273. pump();
  10274. }, capability.reject);
  10275. };
  10276. this._reader = this._textContentSource.getReader();
  10277. pump();
  10278. } else if (this._textContentSource) {
  10279. const {
  10280. items,
  10281. styles
  10282. } = this._textContentSource;
  10283. this._processItems(items, styles);
  10284. capability.resolve();
  10285. } else {
  10286. throw new Error('No "textContentSource" parameter specified.');
  10287. }
  10288. capability.promise.then(() => {
  10289. styleCache = null;
  10290. render(this);
  10291. }, this._capability.reject);
  10292. }
  10293. }
  10294. exports.TextLayerRenderTask = TextLayerRenderTask;
  10295. function renderTextLayer(params) {
  10296. if (!params.textContentSource && (params.textContent || params.textContentStream)) {
  10297. (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
  10298. params.textContentSource = params.textContent || params.textContentStream;
  10299. }
  10300. const {
  10301. container,
  10302. viewport
  10303. } = params;
  10304. const style = getComputedStyle(container);
  10305. const visibility = style.getPropertyValue("visibility");
  10306. const scaleFactor = parseFloat(style.getPropertyValue("--scale-factor"));
  10307. if (visibility === "visible" && (!scaleFactor || Math.abs(scaleFactor - viewport.scale) > 1e-15)) {
  10308. console.error("The `--scale-factor` CSS-variable must be set, " + "to the same value as `viewport.scale`, " + "either on the `container`-element itself or higher up in the DOM.");
  10309. }
  10310. const task = new TextLayerRenderTask(params);
  10311. task._render();
  10312. return task;
  10313. }
  10314. function updateTextLayer({
  10315. container,
  10316. viewport,
  10317. textDivs,
  10318. textDivProperties,
  10319. isOffscreenCanvasSupported,
  10320. mustRotate = true,
  10321. mustRescale = true
  10322. }) {
  10323. if (mustRotate) {
  10324. (0, _display_utils.setLayerDimensions)(container, {
  10325. rotation: viewport.rotation
  10326. });
  10327. }
  10328. if (mustRescale) {
  10329. const ctx = getCtx(0, isOffscreenCanvasSupported);
  10330. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  10331. const params = {
  10332. prevFontSize: null,
  10333. prevFontFamily: null,
  10334. div: null,
  10335. scale,
  10336. properties: null,
  10337. ctx
  10338. };
  10339. for (const div of textDivs) {
  10340. params.properties = textDivProperties.get(div);
  10341. params.div = div;
  10342. layout(params);
  10343. }
  10344. }
  10345. }
  10346. /***/ }),
  10347. /* 27 */
  10348. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10349. Object.defineProperty(exports, "__esModule", ({
  10350. value: true
  10351. }));
  10352. exports.AnnotationEditorLayer = void 0;
  10353. var _util = __w_pdfjs_require__(1);
  10354. var _tools = __w_pdfjs_require__(5);
  10355. var _freetext = __w_pdfjs_require__(28);
  10356. var _ink = __w_pdfjs_require__(29);
  10357. var _display_utils = __w_pdfjs_require__(6);
  10358. class AnnotationEditorLayer {
  10359. #accessibilityManager;
  10360. #allowClick = false;
  10361. #boundPointerup = this.pointerup.bind(this);
  10362. #boundPointerdown = this.pointerdown.bind(this);
  10363. #editors = new Map();
  10364. #hadPointerDown = false;
  10365. #isCleaningUp = false;
  10366. #uiManager;
  10367. static _initialized = false;
  10368. constructor(options) {
  10369. if (!AnnotationEditorLayer._initialized) {
  10370. AnnotationEditorLayer._initialized = true;
  10371. _freetext.FreeTextEditor.initialize(options.l10n);
  10372. _ink.InkEditor.initialize(options.l10n);
  10373. }
  10374. options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
  10375. this.#uiManager = options.uiManager;
  10376. this.pageIndex = options.pageIndex;
  10377. this.div = options.div;
  10378. this.#accessibilityManager = options.accessibilityManager;
  10379. this.#uiManager.addLayer(this);
  10380. }
  10381. get isEmpty() {
  10382. return this.#editors.size === 0;
  10383. }
  10384. updateToolbar(mode) {
  10385. this.#uiManager.updateToolbar(mode);
  10386. }
  10387. updateMode(mode = this.#uiManager.getMode()) {
  10388. this.#cleanup();
  10389. if (mode === _util.AnnotationEditorType.INK) {
  10390. this.addInkEditorIfNeeded(false);
  10391. this.disableClick();
  10392. } else {
  10393. this.enableClick();
  10394. }
  10395. this.#uiManager.unselectAll();
  10396. if (mode !== _util.AnnotationEditorType.NONE) {
  10397. this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
  10398. this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
  10399. this.div.hidden = false;
  10400. }
  10401. }
  10402. addInkEditorIfNeeded(isCommitting) {
  10403. if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
  10404. return;
  10405. }
  10406. if (!isCommitting) {
  10407. for (const editor of this.#editors.values()) {
  10408. if (editor.isEmpty()) {
  10409. editor.setInBackground();
  10410. return;
  10411. }
  10412. }
  10413. }
  10414. const editor = this.#createAndAddNewEditor({
  10415. offsetX: 0,
  10416. offsetY: 0
  10417. });
  10418. editor.setInBackground();
  10419. }
  10420. setEditingState(isEditing) {
  10421. this.#uiManager.setEditingState(isEditing);
  10422. }
  10423. addCommands(params) {
  10424. this.#uiManager.addCommands(params);
  10425. }
  10426. enable() {
  10427. this.div.style.pointerEvents = "auto";
  10428. for (const editor of this.#editors.values()) {
  10429. editor.enableEditing();
  10430. }
  10431. }
  10432. disable() {
  10433. this.div.style.pointerEvents = "none";
  10434. for (const editor of this.#editors.values()) {
  10435. editor.disableEditing();
  10436. }
  10437. this.#cleanup();
  10438. if (this.isEmpty) {
  10439. this.div.hidden = true;
  10440. }
  10441. }
  10442. setActiveEditor(editor) {
  10443. const currentActive = this.#uiManager.getActive();
  10444. if (currentActive === editor) {
  10445. return;
  10446. }
  10447. this.#uiManager.setActiveEditor(editor);
  10448. }
  10449. enableClick() {
  10450. this.div.addEventListener("pointerdown", this.#boundPointerdown);
  10451. this.div.addEventListener("pointerup", this.#boundPointerup);
  10452. }
  10453. disableClick() {
  10454. this.div.removeEventListener("pointerdown", this.#boundPointerdown);
  10455. this.div.removeEventListener("pointerup", this.#boundPointerup);
  10456. }
  10457. attach(editor) {
  10458. this.#editors.set(editor.id, editor);
  10459. }
  10460. detach(editor) {
  10461. this.#editors.delete(editor.id);
  10462. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  10463. }
  10464. remove(editor) {
  10465. this.#uiManager.removeEditor(editor);
  10466. this.detach(editor);
  10467. editor.div.style.display = "none";
  10468. setTimeout(() => {
  10469. editor.div.style.display = "";
  10470. editor.div.remove();
  10471. editor.isAttachedToDOM = false;
  10472. if (document.activeElement === document.body) {
  10473. this.#uiManager.focusMainContainer();
  10474. }
  10475. }, 0);
  10476. if (!this.#isCleaningUp) {
  10477. this.addInkEditorIfNeeded(false);
  10478. }
  10479. }
  10480. #changeParent(editor) {
  10481. if (editor.parent === this) {
  10482. return;
  10483. }
  10484. this.attach(editor);
  10485. editor.parent?.detach(editor);
  10486. editor.setParent(this);
  10487. if (editor.div && editor.isAttachedToDOM) {
  10488. editor.div.remove();
  10489. this.div.append(editor.div);
  10490. }
  10491. }
  10492. add(editor) {
  10493. this.#changeParent(editor);
  10494. this.#uiManager.addEditor(editor);
  10495. this.attach(editor);
  10496. if (!editor.isAttachedToDOM) {
  10497. const div = editor.render();
  10498. this.div.append(div);
  10499. editor.isAttachedToDOM = true;
  10500. }
  10501. this.moveEditorInDOM(editor);
  10502. editor.onceAdded();
  10503. this.#uiManager.addToAnnotationStorage(editor);
  10504. }
  10505. moveEditorInDOM(editor) {
  10506. this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  10507. }
  10508. addOrRebuild(editor) {
  10509. if (editor.needsToBeRebuilt()) {
  10510. editor.rebuild();
  10511. } else {
  10512. this.add(editor);
  10513. }
  10514. }
  10515. addANewEditor(editor) {
  10516. const cmd = () => {
  10517. this.addOrRebuild(editor);
  10518. };
  10519. const undo = () => {
  10520. editor.remove();
  10521. };
  10522. this.addCommands({
  10523. cmd,
  10524. undo,
  10525. mustExec: true
  10526. });
  10527. }
  10528. addUndoableEditor(editor) {
  10529. const cmd = () => {
  10530. this.addOrRebuild(editor);
  10531. };
  10532. const undo = () => {
  10533. editor.remove();
  10534. };
  10535. this.addCommands({
  10536. cmd,
  10537. undo,
  10538. mustExec: false
  10539. });
  10540. }
  10541. getNextId() {
  10542. return this.#uiManager.getId();
  10543. }
  10544. #createNewEditor(params) {
  10545. switch (this.#uiManager.getMode()) {
  10546. case _util.AnnotationEditorType.FREETEXT:
  10547. return new _freetext.FreeTextEditor(params);
  10548. case _util.AnnotationEditorType.INK:
  10549. return new _ink.InkEditor(params);
  10550. }
  10551. return null;
  10552. }
  10553. deserialize(data) {
  10554. switch (data.annotationType) {
  10555. case _util.AnnotationEditorType.FREETEXT:
  10556. return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
  10557. case _util.AnnotationEditorType.INK:
  10558. return _ink.InkEditor.deserialize(data, this, this.#uiManager);
  10559. }
  10560. return null;
  10561. }
  10562. #createAndAddNewEditor(event) {
  10563. const id = this.getNextId();
  10564. const editor = this.#createNewEditor({
  10565. parent: this,
  10566. id,
  10567. x: event.offsetX,
  10568. y: event.offsetY,
  10569. uiManager: this.#uiManager
  10570. });
  10571. if (editor) {
  10572. this.add(editor);
  10573. }
  10574. return editor;
  10575. }
  10576. setSelected(editor) {
  10577. this.#uiManager.setSelected(editor);
  10578. }
  10579. toggleSelected(editor) {
  10580. this.#uiManager.toggleSelected(editor);
  10581. }
  10582. isSelected(editor) {
  10583. return this.#uiManager.isSelected(editor);
  10584. }
  10585. unselect(editor) {
  10586. this.#uiManager.unselect(editor);
  10587. }
  10588. pointerup(event) {
  10589. const {
  10590. isMac
  10591. } = _util.FeatureTest.platform;
  10592. if (event.button !== 0 || event.ctrlKey && isMac) {
  10593. return;
  10594. }
  10595. if (event.target !== this.div) {
  10596. return;
  10597. }
  10598. if (!this.#hadPointerDown) {
  10599. return;
  10600. }
  10601. this.#hadPointerDown = false;
  10602. if (!this.#allowClick) {
  10603. this.#allowClick = true;
  10604. return;
  10605. }
  10606. this.#createAndAddNewEditor(event);
  10607. }
  10608. pointerdown(event) {
  10609. const {
  10610. isMac
  10611. } = _util.FeatureTest.platform;
  10612. if (event.button !== 0 || event.ctrlKey && isMac) {
  10613. return;
  10614. }
  10615. if (event.target !== this.div) {
  10616. return;
  10617. }
  10618. this.#hadPointerDown = true;
  10619. const editor = this.#uiManager.getActive();
  10620. this.#allowClick = !editor || editor.isEmpty();
  10621. }
  10622. drop(event) {
  10623. const id = event.dataTransfer.getData("text/plain");
  10624. const editor = this.#uiManager.getEditor(id);
  10625. if (!editor) {
  10626. return;
  10627. }
  10628. event.preventDefault();
  10629. event.dataTransfer.dropEffect = "move";
  10630. this.#changeParent(editor);
  10631. const rect = this.div.getBoundingClientRect();
  10632. const endX = event.clientX - rect.x;
  10633. const endY = event.clientY - rect.y;
  10634. editor.translate(endX - editor.startX, endY - editor.startY);
  10635. this.moveEditorInDOM(editor);
  10636. editor.div.focus();
  10637. }
  10638. dragover(event) {
  10639. event.preventDefault();
  10640. }
  10641. destroy() {
  10642. if (this.#uiManager.getActive()?.parent === this) {
  10643. this.#uiManager.setActiveEditor(null);
  10644. }
  10645. for (const editor of this.#editors.values()) {
  10646. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  10647. editor.setParent(null);
  10648. editor.isAttachedToDOM = false;
  10649. editor.div.remove();
  10650. }
  10651. this.div = null;
  10652. this.#editors.clear();
  10653. this.#uiManager.removeLayer(this);
  10654. }
  10655. #cleanup() {
  10656. this.#isCleaningUp = true;
  10657. for (const editor of this.#editors.values()) {
  10658. if (editor.isEmpty()) {
  10659. editor.remove();
  10660. }
  10661. }
  10662. this.#isCleaningUp = false;
  10663. }
  10664. render({
  10665. viewport
  10666. }) {
  10667. this.viewport = viewport;
  10668. (0, _display_utils.setLayerDimensions)(this.div, viewport);
  10669. (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
  10670. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  10671. this.add(editor);
  10672. }
  10673. this.updateMode();
  10674. }
  10675. update({
  10676. viewport
  10677. }) {
  10678. this.#uiManager.commitOrRemove();
  10679. this.viewport = viewport;
  10680. (0, _display_utils.setLayerDimensions)(this.div, {
  10681. rotation: viewport.rotation
  10682. });
  10683. this.updateMode();
  10684. }
  10685. get pageDimensions() {
  10686. const {
  10687. pageWidth,
  10688. pageHeight
  10689. } = this.viewport.rawDims;
  10690. return [pageWidth, pageHeight];
  10691. }
  10692. }
  10693. exports.AnnotationEditorLayer = AnnotationEditorLayer;
  10694. /***/ }),
  10695. /* 28 */
  10696. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  10697. Object.defineProperty(exports, "__esModule", ({
  10698. value: true
  10699. }));
  10700. exports.FreeTextEditor = void 0;
  10701. var _util = __w_pdfjs_require__(1);
  10702. var _tools = __w_pdfjs_require__(5);
  10703. var _editor = __w_pdfjs_require__(4);
  10704. class FreeTextEditor extends _editor.AnnotationEditor {
  10705. #boundEditorDivBlur = this.editorDivBlur.bind(this);
  10706. #boundEditorDivFocus = this.editorDivFocus.bind(this);
  10707. #boundEditorDivInput = this.editorDivInput.bind(this);
  10708. #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  10709. #color;
  10710. #content = "";
  10711. #editorDivId = `${this.id}-editor`;
  10712. #hasAlreadyBeenCommitted = false;
  10713. #fontSize;
  10714. static _freeTextDefaultContent = "";
  10715. static _l10nPromise;
  10716. static _internalPadding = 0;
  10717. static _defaultColor = null;
  10718. static _defaultFontSize = 10;
  10719. static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  10720. static _type = "freetext";
  10721. constructor(params) {
  10722. super({
  10723. ...params,
  10724. name: "freeTextEditor"
  10725. });
  10726. this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  10727. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  10728. }
  10729. static initialize(l10n) {
  10730. this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
  10731. const style = getComputedStyle(document.documentElement);
  10732. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  10733. }
  10734. static updateDefaultParams(type, value) {
  10735. switch (type) {
  10736. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  10737. FreeTextEditor._defaultFontSize = value;
  10738. break;
  10739. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  10740. FreeTextEditor._defaultColor = value;
  10741. break;
  10742. }
  10743. }
  10744. updateParams(type, value) {
  10745. switch (type) {
  10746. case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
  10747. this.#updateFontSize(value);
  10748. break;
  10749. case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
  10750. this.#updateColor(value);
  10751. break;
  10752. }
  10753. }
  10754. static get defaultPropertiesToUpdate() {
  10755. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  10756. }
  10757. get propertiesToUpdate() {
  10758. return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  10759. }
  10760. #updateFontSize(fontSize) {
  10761. const setFontsize = size => {
  10762. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  10763. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  10764. this.#fontSize = size;
  10765. this.#setEditorDimensions();
  10766. };
  10767. const savedFontsize = this.#fontSize;
  10768. this.addCommands({
  10769. cmd: () => {
  10770. setFontsize(fontSize);
  10771. },
  10772. undo: () => {
  10773. setFontsize(savedFontsize);
  10774. },
  10775. mustExec: true,
  10776. type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
  10777. overwriteIfSameType: true,
  10778. keepUndo: true
  10779. });
  10780. }
  10781. #updateColor(color) {
  10782. const savedColor = this.#color;
  10783. this.addCommands({
  10784. cmd: () => {
  10785. this.#color = this.editorDiv.style.color = color;
  10786. },
  10787. undo: () => {
  10788. this.#color = this.editorDiv.style.color = savedColor;
  10789. },
  10790. mustExec: true,
  10791. type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
  10792. overwriteIfSameType: true,
  10793. keepUndo: true
  10794. });
  10795. }
  10796. getInitialTranslation() {
  10797. const scale = this.parentScale;
  10798. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  10799. }
  10800. rebuild() {
  10801. super.rebuild();
  10802. if (this.div === null) {
  10803. return;
  10804. }
  10805. if (!this.isAttachedToDOM) {
  10806. this.parent.add(this);
  10807. }
  10808. }
  10809. enableEditMode() {
  10810. if (this.isInEditMode()) {
  10811. return;
  10812. }
  10813. this.parent.setEditingState(false);
  10814. this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
  10815. super.enableEditMode();
  10816. this.overlayDiv.classList.remove("enabled");
  10817. this.editorDiv.contentEditable = true;
  10818. this.div.draggable = false;
  10819. this.div.removeAttribute("aria-activedescendant");
  10820. this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
  10821. this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
  10822. this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
  10823. this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  10824. }
  10825. disableEditMode() {
  10826. if (!this.isInEditMode()) {
  10827. return;
  10828. }
  10829. this.parent.setEditingState(true);
  10830. super.disableEditMode();
  10831. this.overlayDiv.classList.add("enabled");
  10832. this.editorDiv.contentEditable = false;
  10833. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  10834. this.div.draggable = true;
  10835. this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
  10836. this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
  10837. this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
  10838. this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
  10839. this.div.focus({
  10840. preventScroll: true
  10841. });
  10842. this.isEditing = false;
  10843. this.parent.div.classList.add("freeTextEditing");
  10844. }
  10845. focusin(event) {
  10846. super.focusin(event);
  10847. if (event.target !== this.editorDiv) {
  10848. this.editorDiv.focus();
  10849. }
  10850. }
  10851. onceAdded() {
  10852. if (this.width) {
  10853. return;
  10854. }
  10855. this.enableEditMode();
  10856. this.editorDiv.focus();
  10857. }
  10858. isEmpty() {
  10859. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  10860. }
  10861. remove() {
  10862. this.isEditing = false;
  10863. this.parent.setEditingState(true);
  10864. this.parent.div.classList.add("freeTextEditing");
  10865. super.remove();
  10866. }
  10867. #extractText() {
  10868. const divs = this.editorDiv.getElementsByTagName("div");
  10869. if (divs.length === 0) {
  10870. return this.editorDiv.innerText;
  10871. }
  10872. const buffer = [];
  10873. for (const div of divs) {
  10874. buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
  10875. }
  10876. return buffer.join("\n");
  10877. }
  10878. #setEditorDimensions() {
  10879. const [parentWidth, parentHeight] = this.parentDimensions;
  10880. let rect;
  10881. if (this.isAttachedToDOM) {
  10882. rect = this.div.getBoundingClientRect();
  10883. } else {
  10884. const {
  10885. currentLayer,
  10886. div
  10887. } = this;
  10888. const savedDisplay = div.style.display;
  10889. div.style.display = "hidden";
  10890. currentLayer.div.append(this.div);
  10891. rect = div.getBoundingClientRect();
  10892. div.remove();
  10893. div.style.display = savedDisplay;
  10894. }
  10895. this.width = rect.width / parentWidth;
  10896. this.height = rect.height / parentHeight;
  10897. }
  10898. commit() {
  10899. if (!this.isInEditMode()) {
  10900. return;
  10901. }
  10902. super.commit();
  10903. if (!this.#hasAlreadyBeenCommitted) {
  10904. this.#hasAlreadyBeenCommitted = true;
  10905. this.parent.addUndoableEditor(this);
  10906. }
  10907. this.disableEditMode();
  10908. this.#content = this.#extractText().trimEnd();
  10909. this.#setEditorDimensions();
  10910. }
  10911. shouldGetKeyboardEvents() {
  10912. return this.isInEditMode();
  10913. }
  10914. dblclick(event) {
  10915. this.enableEditMode();
  10916. this.editorDiv.focus();
  10917. }
  10918. keydown(event) {
  10919. if (event.target === this.div && event.key === "Enter") {
  10920. this.enableEditMode();
  10921. this.editorDiv.focus();
  10922. }
  10923. }
  10924. editorDivKeydown(event) {
  10925. FreeTextEditor._keyboardManager.exec(this, event);
  10926. }
  10927. editorDivFocus(event) {
  10928. this.isEditing = true;
  10929. }
  10930. editorDivBlur(event) {
  10931. this.isEditing = false;
  10932. }
  10933. editorDivInput(event) {
  10934. this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  10935. }
  10936. disableEditing() {
  10937. this.editorDiv.setAttribute("role", "comment");
  10938. this.editorDiv.removeAttribute("aria-multiline");
  10939. }
  10940. enableEditing() {
  10941. this.editorDiv.setAttribute("role", "textbox");
  10942. this.editorDiv.setAttribute("aria-multiline", true);
  10943. }
  10944. render() {
  10945. if (this.div) {
  10946. return this.div;
  10947. }
  10948. let baseX, baseY;
  10949. if (this.width) {
  10950. baseX = this.x;
  10951. baseY = this.y;
  10952. }
  10953. super.render();
  10954. this.editorDiv = document.createElement("div");
  10955. this.editorDiv.className = "internal";
  10956. this.editorDiv.setAttribute("id", this.#editorDivId);
  10957. this.enableEditing();
  10958. FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
  10959. FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  10960. this.editorDiv.contentEditable = true;
  10961. const {
  10962. style
  10963. } = this.editorDiv;
  10964. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  10965. style.color = this.#color;
  10966. this.div.append(this.editorDiv);
  10967. this.overlayDiv = document.createElement("div");
  10968. this.overlayDiv.classList.add("overlay", "enabled");
  10969. this.div.append(this.overlayDiv);
  10970. (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
  10971. if (this.width) {
  10972. const [parentWidth, parentHeight] = this.parentDimensions;
  10973. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  10974. for (const line of this.#content.split("\n")) {
  10975. const div = document.createElement("div");
  10976. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  10977. this.editorDiv.append(div);
  10978. }
  10979. this.div.draggable = true;
  10980. this.editorDiv.contentEditable = false;
  10981. } else {
  10982. this.div.draggable = false;
  10983. this.editorDiv.contentEditable = true;
  10984. }
  10985. return this.div;
  10986. }
  10987. get contentDiv() {
  10988. return this.editorDiv;
  10989. }
  10990. static deserialize(data, parent, uiManager) {
  10991. const editor = super.deserialize(data, parent, uiManager);
  10992. editor.#fontSize = data.fontSize;
  10993. editor.#color = _util.Util.makeHexColor(...data.color);
  10994. editor.#content = data.value;
  10995. return editor;
  10996. }
  10997. serialize() {
  10998. if (this.isEmpty()) {
  10999. return null;
  11000. }
  11001. const padding = FreeTextEditor._internalPadding * this.parentScale;
  11002. const rect = this.getRect(padding, padding);
  11003. const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  11004. return {
  11005. annotationType: _util.AnnotationEditorType.FREETEXT,
  11006. color,
  11007. fontSize: this.#fontSize,
  11008. value: this.#content,
  11009. pageIndex: this.pageIndex,
  11010. rect,
  11011. rotation: this.rotation
  11012. };
  11013. }
  11014. }
  11015. exports.FreeTextEditor = FreeTextEditor;
  11016. /***/ }),
  11017. /* 29 */
  11018. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11019. Object.defineProperty(exports, "__esModule", ({
  11020. value: true
  11021. }));
  11022. exports.InkEditor = void 0;
  11023. Object.defineProperty(exports, "fitCurve", ({
  11024. enumerable: true,
  11025. get: function () {
  11026. return _pdfjsFitCurve.fitCurve;
  11027. }
  11028. }));
  11029. var _util = __w_pdfjs_require__(1);
  11030. var _editor = __w_pdfjs_require__(4);
  11031. var _pdfjsFitCurve = __w_pdfjs_require__(30);
  11032. var _tools = __w_pdfjs_require__(5);
  11033. const RESIZER_SIZE = 16;
  11034. class InkEditor extends _editor.AnnotationEditor {
  11035. #aspectRatio = 0;
  11036. #baseHeight = 0;
  11037. #baseWidth = 0;
  11038. #boundCanvasPointermove = this.canvasPointermove.bind(this);
  11039. #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  11040. #boundCanvasPointerup = this.canvasPointerup.bind(this);
  11041. #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  11042. #disableEditing = false;
  11043. #isCanvasInitialized = false;
  11044. #lastPoint = null;
  11045. #observer = null;
  11046. #realWidth = 0;
  11047. #realHeight = 0;
  11048. #requestFrameCallback = null;
  11049. static _defaultColor = null;
  11050. static _defaultOpacity = 1;
  11051. static _defaultThickness = 1;
  11052. static _l10nPromise;
  11053. static _type = "ink";
  11054. constructor(params) {
  11055. super({
  11056. ...params,
  11057. name: "inkEditor"
  11058. });
  11059. this.color = params.color || null;
  11060. this.thickness = params.thickness || null;
  11061. this.opacity = params.opacity || null;
  11062. this.paths = [];
  11063. this.bezierPath2D = [];
  11064. this.currentPath = [];
  11065. this.scaleFactor = 1;
  11066. this.translationX = this.translationY = 0;
  11067. this.x = 0;
  11068. this.y = 0;
  11069. }
  11070. static initialize(l10n) {
  11071. this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  11072. }
  11073. static updateDefaultParams(type, value) {
  11074. switch (type) {
  11075. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  11076. InkEditor._defaultThickness = value;
  11077. break;
  11078. case _util.AnnotationEditorParamsType.INK_COLOR:
  11079. InkEditor._defaultColor = value;
  11080. break;
  11081. case _util.AnnotationEditorParamsType.INK_OPACITY:
  11082. InkEditor._defaultOpacity = value / 100;
  11083. break;
  11084. }
  11085. }
  11086. updateParams(type, value) {
  11087. switch (type) {
  11088. case _util.AnnotationEditorParamsType.INK_THICKNESS:
  11089. this.#updateThickness(value);
  11090. break;
  11091. case _util.AnnotationEditorParamsType.INK_COLOR:
  11092. this.#updateColor(value);
  11093. break;
  11094. case _util.AnnotationEditorParamsType.INK_OPACITY:
  11095. this.#updateOpacity(value);
  11096. break;
  11097. }
  11098. }
  11099. static get defaultPropertiesToUpdate() {
  11100. 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)]];
  11101. }
  11102. get propertiesToUpdate() {
  11103. 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))]];
  11104. }
  11105. #updateThickness(thickness) {
  11106. const savedThickness = this.thickness;
  11107. this.addCommands({
  11108. cmd: () => {
  11109. this.thickness = thickness;
  11110. this.#fitToContent();
  11111. },
  11112. undo: () => {
  11113. this.thickness = savedThickness;
  11114. this.#fitToContent();
  11115. },
  11116. mustExec: true,
  11117. type: _util.AnnotationEditorParamsType.INK_THICKNESS,
  11118. overwriteIfSameType: true,
  11119. keepUndo: true
  11120. });
  11121. }
  11122. #updateColor(color) {
  11123. const savedColor = this.color;
  11124. this.addCommands({
  11125. cmd: () => {
  11126. this.color = color;
  11127. this.#redraw();
  11128. },
  11129. undo: () => {
  11130. this.color = savedColor;
  11131. this.#redraw();
  11132. },
  11133. mustExec: true,
  11134. type: _util.AnnotationEditorParamsType.INK_COLOR,
  11135. overwriteIfSameType: true,
  11136. keepUndo: true
  11137. });
  11138. }
  11139. #updateOpacity(opacity) {
  11140. opacity /= 100;
  11141. const savedOpacity = this.opacity;
  11142. this.addCommands({
  11143. cmd: () => {
  11144. this.opacity = opacity;
  11145. this.#redraw();
  11146. },
  11147. undo: () => {
  11148. this.opacity = savedOpacity;
  11149. this.#redraw();
  11150. },
  11151. mustExec: true,
  11152. type: _util.AnnotationEditorParamsType.INK_OPACITY,
  11153. overwriteIfSameType: true,
  11154. keepUndo: true
  11155. });
  11156. }
  11157. rebuild() {
  11158. super.rebuild();
  11159. if (this.div === null) {
  11160. return;
  11161. }
  11162. if (!this.canvas) {
  11163. this.#createCanvas();
  11164. this.#createObserver();
  11165. }
  11166. if (!this.isAttachedToDOM) {
  11167. this.parent.add(this);
  11168. this.#setCanvasDims();
  11169. }
  11170. this.#fitToContent();
  11171. }
  11172. remove() {
  11173. if (this.canvas === null) {
  11174. return;
  11175. }
  11176. if (!this.isEmpty()) {
  11177. this.commit();
  11178. }
  11179. this.canvas.width = this.canvas.height = 0;
  11180. this.canvas.remove();
  11181. this.canvas = null;
  11182. this.#observer.disconnect();
  11183. this.#observer = null;
  11184. super.remove();
  11185. }
  11186. setParent(parent) {
  11187. if (!this.parent && parent) {
  11188. this._uiManager.removeShouldRescale(this);
  11189. } else if (this.parent && parent === null) {
  11190. this._uiManager.addShouldRescale(this);
  11191. }
  11192. super.setParent(parent);
  11193. }
  11194. onScaleChanging() {
  11195. const [parentWidth, parentHeight] = this.parentDimensions;
  11196. const width = this.width * parentWidth;
  11197. const height = this.height * parentHeight;
  11198. this.setDimensions(width, height);
  11199. }
  11200. enableEditMode() {
  11201. if (this.#disableEditing || this.canvas === null) {
  11202. return;
  11203. }
  11204. super.enableEditMode();
  11205. this.div.draggable = false;
  11206. this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
  11207. this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  11208. }
  11209. disableEditMode() {
  11210. if (!this.isInEditMode() || this.canvas === null) {
  11211. return;
  11212. }
  11213. super.disableEditMode();
  11214. this.div.draggable = !this.isEmpty();
  11215. this.div.classList.remove("editing");
  11216. this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
  11217. this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  11218. }
  11219. onceAdded() {
  11220. this.div.draggable = !this.isEmpty();
  11221. }
  11222. isEmpty() {
  11223. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  11224. }
  11225. #getInitialBBox() {
  11226. const {
  11227. parentRotation,
  11228. parentDimensions: [width, height]
  11229. } = this;
  11230. switch (parentRotation) {
  11231. case 90:
  11232. return [0, height, height, width];
  11233. case 180:
  11234. return [width, height, width, height];
  11235. case 270:
  11236. return [width, 0, height, width];
  11237. default:
  11238. return [0, 0, width, height];
  11239. }
  11240. }
  11241. #setStroke() {
  11242. const {
  11243. ctx,
  11244. color,
  11245. opacity,
  11246. thickness,
  11247. parentScale,
  11248. scaleFactor
  11249. } = this;
  11250. ctx.lineWidth = thickness * parentScale / scaleFactor;
  11251. ctx.lineCap = "round";
  11252. ctx.lineJoin = "round";
  11253. ctx.miterLimit = 10;
  11254. ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
  11255. }
  11256. #startDrawing(x, y) {
  11257. this.isEditing = true;
  11258. if (!this.#isCanvasInitialized) {
  11259. this.#isCanvasInitialized = true;
  11260. this.#setCanvasDims();
  11261. this.thickness ||= InkEditor._defaultThickness;
  11262. this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
  11263. this.opacity ??= InkEditor._defaultOpacity;
  11264. }
  11265. this.currentPath.push([x, y]);
  11266. this.#lastPoint = null;
  11267. this.#setStroke();
  11268. this.ctx.beginPath();
  11269. this.ctx.moveTo(x, y);
  11270. this.#requestFrameCallback = () => {
  11271. if (!this.#requestFrameCallback) {
  11272. return;
  11273. }
  11274. if (this.#lastPoint) {
  11275. if (this.isEmpty()) {
  11276. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  11277. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  11278. } else {
  11279. this.#redraw();
  11280. }
  11281. this.ctx.lineTo(...this.#lastPoint);
  11282. this.#lastPoint = null;
  11283. this.ctx.stroke();
  11284. }
  11285. window.requestAnimationFrame(this.#requestFrameCallback);
  11286. };
  11287. window.requestAnimationFrame(this.#requestFrameCallback);
  11288. }
  11289. #draw(x, y) {
  11290. const [lastX, lastY] = this.currentPath.at(-1);
  11291. if (x === lastX && y === lastY) {
  11292. return;
  11293. }
  11294. this.currentPath.push([x, y]);
  11295. this.#lastPoint = [x, y];
  11296. }
  11297. #stopDrawing(x, y) {
  11298. this.ctx.closePath();
  11299. this.#requestFrameCallback = null;
  11300. x = Math.min(Math.max(x, 0), this.canvas.width);
  11301. y = Math.min(Math.max(y, 0), this.canvas.height);
  11302. const [lastX, lastY] = this.currentPath.at(-1);
  11303. if (x !== lastX || y !== lastY) {
  11304. this.currentPath.push([x, y]);
  11305. }
  11306. let bezier;
  11307. if (this.currentPath.length !== 1) {
  11308. bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
  11309. } else {
  11310. const xy = [x, y];
  11311. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  11312. }
  11313. const path2D = InkEditor.#buildPath2D(bezier);
  11314. this.currentPath.length = 0;
  11315. const cmd = () => {
  11316. this.paths.push(bezier);
  11317. this.bezierPath2D.push(path2D);
  11318. this.rebuild();
  11319. };
  11320. const undo = () => {
  11321. this.paths.pop();
  11322. this.bezierPath2D.pop();
  11323. if (this.paths.length === 0) {
  11324. this.remove();
  11325. } else {
  11326. if (!this.canvas) {
  11327. this.#createCanvas();
  11328. this.#createObserver();
  11329. }
  11330. this.#fitToContent();
  11331. }
  11332. };
  11333. this.addCommands({
  11334. cmd,
  11335. undo,
  11336. mustExec: true
  11337. });
  11338. }
  11339. #redraw() {
  11340. if (this.isEmpty()) {
  11341. this.#updateTransform();
  11342. return;
  11343. }
  11344. this.#setStroke();
  11345. const {
  11346. canvas,
  11347. ctx
  11348. } = this;
  11349. ctx.setTransform(1, 0, 0, 1, 0, 0);
  11350. ctx.clearRect(0, 0, canvas.width, canvas.height);
  11351. this.#updateTransform();
  11352. for (const path of this.bezierPath2D) {
  11353. ctx.stroke(path);
  11354. }
  11355. }
  11356. commit() {
  11357. if (this.#disableEditing) {
  11358. return;
  11359. }
  11360. super.commit();
  11361. this.isEditing = false;
  11362. this.disableEditMode();
  11363. this.setInForeground();
  11364. this.#disableEditing = true;
  11365. this.div.classList.add("disabled");
  11366. this.#fitToContent(true);
  11367. this.parent.addInkEditorIfNeeded(true);
  11368. this.parent.moveEditorInDOM(this);
  11369. this.div.focus({
  11370. preventScroll: true
  11371. });
  11372. }
  11373. focusin(event) {
  11374. super.focusin(event);
  11375. this.enableEditMode();
  11376. }
  11377. canvasPointerdown(event) {
  11378. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  11379. return;
  11380. }
  11381. this.setInForeground();
  11382. if (event.type !== "mouse") {
  11383. this.div.focus();
  11384. }
  11385. event.stopPropagation();
  11386. this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
  11387. this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
  11388. this.#startDrawing(event.offsetX, event.offsetY);
  11389. }
  11390. canvasPointermove(event) {
  11391. event.stopPropagation();
  11392. this.#draw(event.offsetX, event.offsetY);
  11393. }
  11394. canvasPointerup(event) {
  11395. if (event.button !== 0) {
  11396. return;
  11397. }
  11398. if (this.isInEditMode() && this.currentPath.length !== 0) {
  11399. event.stopPropagation();
  11400. this.#endDrawing(event);
  11401. this.setInBackground();
  11402. }
  11403. }
  11404. canvasPointerleave(event) {
  11405. this.#endDrawing(event);
  11406. this.setInBackground();
  11407. }
  11408. #endDrawing(event) {
  11409. this.#stopDrawing(event.offsetX, event.offsetY);
  11410. this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
  11411. this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
  11412. this.addToAnnotationStorage();
  11413. }
  11414. #createCanvas() {
  11415. this.canvas = document.createElement("canvas");
  11416. this.canvas.width = this.canvas.height = 0;
  11417. this.canvas.className = "inkEditorCanvas";
  11418. InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
  11419. this.div.append(this.canvas);
  11420. this.ctx = this.canvas.getContext("2d");
  11421. }
  11422. #createObserver() {
  11423. this.#observer = new ResizeObserver(entries => {
  11424. const rect = entries[0].contentRect;
  11425. if (rect.width && rect.height) {
  11426. this.setDimensions(rect.width, rect.height);
  11427. }
  11428. });
  11429. this.#observer.observe(this.div);
  11430. }
  11431. render() {
  11432. if (this.div) {
  11433. return this.div;
  11434. }
  11435. let baseX, baseY;
  11436. if (this.width) {
  11437. baseX = this.x;
  11438. baseY = this.y;
  11439. }
  11440. super.render();
  11441. InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
  11442. const [x, y, w, h] = this.#getInitialBBox();
  11443. this.setAt(x, y, 0, 0);
  11444. this.setDims(w, h);
  11445. this.#createCanvas();
  11446. if (this.width) {
  11447. const [parentWidth, parentHeight] = this.parentDimensions;
  11448. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  11449. this.#isCanvasInitialized = true;
  11450. this.#setCanvasDims();
  11451. this.setDims(this.width * parentWidth, this.height * parentHeight);
  11452. this.#redraw();
  11453. this.#setMinDims();
  11454. this.div.classList.add("disabled");
  11455. } else {
  11456. this.div.classList.add("editing");
  11457. this.enableEditMode();
  11458. }
  11459. this.#createObserver();
  11460. return this.div;
  11461. }
  11462. #setCanvasDims() {
  11463. if (!this.#isCanvasInitialized) {
  11464. return;
  11465. }
  11466. const [parentWidth, parentHeight] = this.parentDimensions;
  11467. this.canvas.width = Math.ceil(this.width * parentWidth);
  11468. this.canvas.height = Math.ceil(this.height * parentHeight);
  11469. this.#updateTransform();
  11470. }
  11471. setDimensions(width, height) {
  11472. const roundedWidth = Math.round(width);
  11473. const roundedHeight = Math.round(height);
  11474. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  11475. return;
  11476. }
  11477. this.#realWidth = roundedWidth;
  11478. this.#realHeight = roundedHeight;
  11479. this.canvas.style.visibility = "hidden";
  11480. if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
  11481. height = Math.ceil(width / this.#aspectRatio);
  11482. this.setDims(width, height);
  11483. }
  11484. const [parentWidth, parentHeight] = this.parentDimensions;
  11485. this.width = width / parentWidth;
  11486. this.height = height / parentHeight;
  11487. if (this.#disableEditing) {
  11488. this.#setScaleFactor(width, height);
  11489. }
  11490. this.#setCanvasDims();
  11491. this.#redraw();
  11492. this.canvas.style.visibility = "visible";
  11493. this.fixDims();
  11494. }
  11495. #setScaleFactor(width, height) {
  11496. const padding = this.#getPadding();
  11497. const scaleFactorW = (width - padding) / this.#baseWidth;
  11498. const scaleFactorH = (height - padding) / this.#baseHeight;
  11499. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  11500. }
  11501. #updateTransform() {
  11502. const padding = this.#getPadding() / 2;
  11503. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  11504. }
  11505. static #buildPath2D(bezier) {
  11506. const path2D = new Path2D();
  11507. for (let i = 0, ii = bezier.length; i < ii; i++) {
  11508. const [first, control1, control2, second] = bezier[i];
  11509. if (i === 0) {
  11510. path2D.moveTo(...first);
  11511. }
  11512. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  11513. }
  11514. return path2D;
  11515. }
  11516. #serializePaths(s, tx, ty, h) {
  11517. const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
  11518. const paths = [];
  11519. const padding = this.thickness / 2;
  11520. let buffer, points;
  11521. for (const bezier of this.paths) {
  11522. buffer = [];
  11523. points = [];
  11524. for (let i = 0, ii = bezier.length; i < ii; i++) {
  11525. const [first, control1, control2, second] = bezier[i];
  11526. const p10 = s * (first[0] + tx) + padding;
  11527. const p11 = h - s * (first[1] + ty) - padding;
  11528. const p20 = s * (control1[0] + tx) + padding;
  11529. const p21 = h - s * (control1[1] + ty) - padding;
  11530. const p30 = s * (control2[0] + tx) + padding;
  11531. const p31 = h - s * (control2[1] + ty) - padding;
  11532. const p40 = s * (second[0] + tx) + padding;
  11533. const p41 = h - s * (second[1] + ty) - padding;
  11534. if (i === 0) {
  11535. buffer.push(p10, p11);
  11536. points.push(p10, p11);
  11537. }
  11538. buffer.push(p20, p21, p30, p31, p40, p41);
  11539. this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
  11540. }
  11541. paths.push({
  11542. bezier: buffer,
  11543. points
  11544. });
  11545. }
  11546. return paths;
  11547. }
  11548. #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
  11549. if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
  11550. points.push(p40, p41);
  11551. return;
  11552. }
  11553. for (let i = 1; i < n - 1; i++) {
  11554. const t = i / n;
  11555. const mt = 1 - t;
  11556. let q10 = t * p10 + mt * p20;
  11557. let q11 = t * p11 + mt * p21;
  11558. let q20 = t * p20 + mt * p30;
  11559. let q21 = t * p21 + mt * p31;
  11560. const q30 = t * p30 + mt * p40;
  11561. const q31 = t * p31 + mt * p41;
  11562. q10 = t * q10 + mt * q20;
  11563. q11 = t * q11 + mt * q21;
  11564. q20 = t * q20 + mt * q30;
  11565. q21 = t * q21 + mt * q31;
  11566. q10 = t * q10 + mt * q20;
  11567. q11 = t * q11 + mt * q21;
  11568. points.push(q10, q11);
  11569. }
  11570. points.push(p40, p41);
  11571. }
  11572. #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
  11573. const tol = 10;
  11574. const ax = (3 * p20 - 2 * p10 - p40) ** 2;
  11575. const ay = (3 * p21 - 2 * p11 - p41) ** 2;
  11576. const bx = (3 * p30 - p10 - 2 * p40) ** 2;
  11577. const by = (3 * p31 - p11 - 2 * p41) ** 2;
  11578. return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  11579. }
  11580. #getBbox() {
  11581. let xMin = Infinity;
  11582. let xMax = -Infinity;
  11583. let yMin = Infinity;
  11584. let yMax = -Infinity;
  11585. for (const path of this.paths) {
  11586. for (const [first, control1, control2, second] of path) {
  11587. const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  11588. xMin = Math.min(xMin, bbox[0]);
  11589. yMin = Math.min(yMin, bbox[1]);
  11590. xMax = Math.max(xMax, bbox[2]);
  11591. yMax = Math.max(yMax, bbox[3]);
  11592. }
  11593. }
  11594. return [xMin, yMin, xMax, yMax];
  11595. }
  11596. #getPadding() {
  11597. return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  11598. }
  11599. #fitToContent(firstTime = false) {
  11600. if (this.isEmpty()) {
  11601. return;
  11602. }
  11603. if (!this.#disableEditing) {
  11604. this.#redraw();
  11605. return;
  11606. }
  11607. const bbox = this.#getBbox();
  11608. const padding = this.#getPadding();
  11609. this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  11610. this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  11611. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  11612. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  11613. const [parentWidth, parentHeight] = this.parentDimensions;
  11614. this.width = width / parentWidth;
  11615. this.height = height / parentHeight;
  11616. this.#aspectRatio = width / height;
  11617. this.#setMinDims();
  11618. const prevTranslationX = this.translationX;
  11619. const prevTranslationY = this.translationY;
  11620. this.translationX = -bbox[0];
  11621. this.translationY = -bbox[1];
  11622. this.#setCanvasDims();
  11623. this.#redraw();
  11624. this.#realWidth = width;
  11625. this.#realHeight = height;
  11626. this.setDims(width, height);
  11627. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  11628. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  11629. }
  11630. #setMinDims() {
  11631. const {
  11632. style
  11633. } = this.div;
  11634. if (this.#aspectRatio >= 1) {
  11635. style.minHeight = `${RESIZER_SIZE}px`;
  11636. style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
  11637. } else {
  11638. style.minWidth = `${RESIZER_SIZE}px`;
  11639. style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
  11640. }
  11641. }
  11642. static deserialize(data, parent, uiManager) {
  11643. const editor = super.deserialize(data, parent, uiManager);
  11644. editor.thickness = data.thickness;
  11645. editor.color = _util.Util.makeHexColor(...data.color);
  11646. editor.opacity = data.opacity;
  11647. const [pageWidth, pageHeight] = editor.pageDimensions;
  11648. const width = editor.width * pageWidth;
  11649. const height = editor.height * pageHeight;
  11650. const scaleFactor = editor.parentScale;
  11651. const padding = data.thickness / 2;
  11652. editor.#aspectRatio = width / height;
  11653. editor.#disableEditing = true;
  11654. editor.#realWidth = Math.round(width);
  11655. editor.#realHeight = Math.round(height);
  11656. for (const {
  11657. bezier
  11658. } of data.paths) {
  11659. const path = [];
  11660. editor.paths.push(path);
  11661. let p0 = scaleFactor * (bezier[0] - padding);
  11662. let p1 = scaleFactor * (height - bezier[1] - padding);
  11663. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  11664. const p10 = scaleFactor * (bezier[i] - padding);
  11665. const p11 = scaleFactor * (height - bezier[i + 1] - padding);
  11666. const p20 = scaleFactor * (bezier[i + 2] - padding);
  11667. const p21 = scaleFactor * (height - bezier[i + 3] - padding);
  11668. const p30 = scaleFactor * (bezier[i + 4] - padding);
  11669. const p31 = scaleFactor * (height - bezier[i + 5] - padding);
  11670. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  11671. p0 = p30;
  11672. p1 = p31;
  11673. }
  11674. const path2D = this.#buildPath2D(path);
  11675. editor.bezierPath2D.push(path2D);
  11676. }
  11677. const bbox = editor.#getBbox();
  11678. editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
  11679. editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
  11680. editor.#setScaleFactor(width, height);
  11681. return editor;
  11682. }
  11683. serialize() {
  11684. if (this.isEmpty()) {
  11685. return null;
  11686. }
  11687. const rect = this.getRect(0, 0);
  11688. const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
  11689. const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  11690. return {
  11691. annotationType: _util.AnnotationEditorType.INK,
  11692. color,
  11693. thickness: this.thickness,
  11694. opacity: this.opacity,
  11695. paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, height),
  11696. pageIndex: this.pageIndex,
  11697. rect,
  11698. rotation: this.rotation
  11699. };
  11700. }
  11701. }
  11702. exports.InkEditor = InkEditor;
  11703. /***/ }),
  11704. /* 30 */
  11705. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  11706. Object.defineProperty(exports, "__esModule", ({
  11707. value: true
  11708. }));
  11709. exports.fitCurve = void 0;
  11710. const fitCurve = __w_pdfjs_require__(31);
  11711. exports.fitCurve = fitCurve;
  11712. /***/ }),
  11713. /* 31 */
  11714. /***/ ((module) => {
  11715. function fitCurve(points, maxError, progressCallback) {
  11716. if (!Array.isArray(points)) {
  11717. throw new TypeError("First argument should be an array");
  11718. }
  11719. points.forEach(point => {
  11720. if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
  11721. throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
  11722. }
  11723. });
  11724. points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  11725. if (points.length < 2) {
  11726. return [];
  11727. }
  11728. const len = points.length;
  11729. const leftTangent = createTangent(points[1], points[0]);
  11730. const rightTangent = createTangent(points[len - 2], points[len - 1]);
  11731. return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
  11732. }
  11733. function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  11734. const MaxIterations = 20;
  11735. var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  11736. if (points.length === 2) {
  11737. dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
  11738. bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
  11739. return [bezCurve];
  11740. }
  11741. u = chordLengthParameterize(points);
  11742. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  11743. if (maxError === 0 || maxError < error) {
  11744. return [bezCurve];
  11745. }
  11746. if (maxError < error * error) {
  11747. uPrime = u;
  11748. prevErr = maxError;
  11749. prevSplit = splitPoint;
  11750. for (i = 0; i < MaxIterations; i++) {
  11751. uPrime = reparameterize(bezCurve, points, uPrime);
  11752. [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
  11753. if (maxError < error) {
  11754. return [bezCurve];
  11755. } else if (splitPoint === prevSplit) {
  11756. let errChange = maxError / prevErr;
  11757. if (errChange > .9999 && errChange < 1.0001) {
  11758. break;
  11759. }
  11760. }
  11761. prevErr = maxError;
  11762. prevSplit = splitPoint;
  11763. }
  11764. }
  11765. beziers = [];
  11766. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  11767. if (centerVector.every(val => val === 0)) {
  11768. centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
  11769. [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  11770. }
  11771. toCenterTangent = maths.normalize(centerVector);
  11772. fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  11773. beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  11774. beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  11775. return beziers;
  11776. }
  11777. ;
  11778. function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  11779. var bezCurve, maxError, splitPoint;
  11780. bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  11781. [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  11782. if (progressCallback) {
  11783. progressCallback({
  11784. bez: bezCurve,
  11785. points: points,
  11786. params: paramsOrig,
  11787. maxErr: maxError,
  11788. maxPoint: splitPoint
  11789. });
  11790. }
  11791. return [bezCurve, maxError, splitPoint];
  11792. }
  11793. function generateBezier(points, parameters, leftTangent, rightTangent) {
  11794. var bezCurve,
  11795. A,
  11796. a,
  11797. C,
  11798. X,
  11799. det_C0_C1,
  11800. det_C0_X,
  11801. det_X_C1,
  11802. alpha_l,
  11803. alpha_r,
  11804. epsilon,
  11805. segLength,
  11806. i,
  11807. len,
  11808. tmp,
  11809. u,
  11810. ux,
  11811. firstPoint = points[0],
  11812. lastPoint = points[points.length - 1];
  11813. bezCurve = [firstPoint, null, null, lastPoint];
  11814. A = maths.zeros_Xx2x2(parameters.length);
  11815. for (i = 0, len = parameters.length; i < len; i++) {
  11816. u = parameters[i];
  11817. ux = 1 - u;
  11818. a = A[i];
  11819. a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
  11820. a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  11821. }
  11822. C = [[0, 0], [0, 0]];
  11823. X = [0, 0];
  11824. for (i = 0, len = points.length; i < len; i++) {
  11825. u = parameters[i];
  11826. a = A[i];
  11827. C[0][0] += maths.dot(a[0], a[0]);
  11828. C[0][1] += maths.dot(a[0], a[1]);
  11829. C[1][0] += maths.dot(a[0], a[1]);
  11830. C[1][1] += maths.dot(a[1], a[1]);
  11831. tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
  11832. X[0] += maths.dot(a[0], tmp);
  11833. X[1] += maths.dot(a[1], tmp);
  11834. }
  11835. det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  11836. det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  11837. det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  11838. alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  11839. alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  11840. segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  11841. epsilon = 1.0e-6 * segLength;
  11842. if (alpha_l < epsilon || alpha_r < epsilon) {
  11843. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
  11844. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  11845. } else {
  11846. bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
  11847. bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  11848. }
  11849. return bezCurve;
  11850. }
  11851. ;
  11852. function reparameterize(bezier, points, parameters) {
  11853. return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
  11854. }
  11855. ;
  11856. function newtonRaphsonRootFind(bez, point, u) {
  11857. var d = maths.subtract(bezier.q(bez, u), point),
  11858. qprime = bezier.qprime(bez, u),
  11859. numerator = maths.mulMatrix(d, qprime),
  11860. denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  11861. if (denominator === 0) {
  11862. return u;
  11863. } else {
  11864. return u - numerator / denominator;
  11865. }
  11866. }
  11867. ;
  11868. function chordLengthParameterize(points) {
  11869. var u = [],
  11870. currU,
  11871. prevU,
  11872. prevP;
  11873. points.forEach((p, i) => {
  11874. currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
  11875. u.push(currU);
  11876. prevU = currU;
  11877. prevP = p;
  11878. });
  11879. u = u.map(x => x / prevU);
  11880. return u;
  11881. }
  11882. ;
  11883. function computeMaxError(points, bez, parameters) {
  11884. var dist, maxDist, splitPoint, v, i, count, point, t;
  11885. maxDist = 0;
  11886. splitPoint = Math.floor(points.length / 2);
  11887. const t_distMap = mapTtoRelativeDistances(bez, 10);
  11888. for (i = 0, count = points.length; i < count; i++) {
  11889. point = points[i];
  11890. t = find_t(bez, parameters[i], t_distMap, 10);
  11891. v = maths.subtract(bezier.q(bez, t), point);
  11892. dist = v[0] * v[0] + v[1] * v[1];
  11893. if (dist > maxDist) {
  11894. maxDist = dist;
  11895. splitPoint = i;
  11896. }
  11897. }
  11898. return [maxDist, splitPoint];
  11899. }
  11900. ;
  11901. var mapTtoRelativeDistances = function (bez, B_parts) {
  11902. var B_t_curr;
  11903. var B_t_dist = [0];
  11904. var B_t_prev = bez[0];
  11905. var sumLen = 0;
  11906. for (var i = 1; i <= B_parts; i++) {
  11907. B_t_curr = bezier.q(bez, i / B_parts);
  11908. sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
  11909. B_t_dist.push(sumLen);
  11910. B_t_prev = B_t_curr;
  11911. }
  11912. B_t_dist = B_t_dist.map(x => x / sumLen);
  11913. return B_t_dist;
  11914. };
  11915. function find_t(bez, param, t_distMap, B_parts) {
  11916. if (param < 0) {
  11917. return 0;
  11918. }
  11919. if (param > 1) {
  11920. return 1;
  11921. }
  11922. var lenMax, lenMin, tMax, tMin, t;
  11923. for (var i = 1; i <= B_parts; i++) {
  11924. if (param <= t_distMap[i]) {
  11925. tMin = (i - 1) / B_parts;
  11926. tMax = i / B_parts;
  11927. lenMin = t_distMap[i - 1];
  11928. lenMax = t_distMap[i];
  11929. t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
  11930. break;
  11931. }
  11932. }
  11933. return t;
  11934. }
  11935. function createTangent(pointA, pointB) {
  11936. return maths.normalize(maths.subtract(pointA, pointB));
  11937. }
  11938. class maths {
  11939. static zeros_Xx2x2(x) {
  11940. var zs = [];
  11941. while (x--) {
  11942. zs.push([0, 0]);
  11943. }
  11944. return zs;
  11945. }
  11946. static mulItems(items, multiplier) {
  11947. return items.map(x => x * multiplier);
  11948. }
  11949. static mulMatrix(m1, m2) {
  11950. return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  11951. }
  11952. static subtract(arr1, arr2) {
  11953. return arr1.map((x1, i) => x1 - arr2[i]);
  11954. }
  11955. static addArrays(arr1, arr2) {
  11956. return arr1.map((x1, i) => x1 + arr2[i]);
  11957. }
  11958. static addItems(items, addition) {
  11959. return items.map(x => x + addition);
  11960. }
  11961. static sum(items) {
  11962. return items.reduce((sum, x) => sum + x);
  11963. }
  11964. static dot(m1, m2) {
  11965. return maths.mulMatrix(m1, m2);
  11966. }
  11967. static vectorLen(v) {
  11968. return Math.hypot(...v);
  11969. }
  11970. static divItems(items, divisor) {
  11971. return items.map(x => x / divisor);
  11972. }
  11973. static squareItems(items) {
  11974. return items.map(x => x * x);
  11975. }
  11976. static normalize(v) {
  11977. return this.divItems(v, this.vectorLen(v));
  11978. }
  11979. }
  11980. class bezier {
  11981. static q(ctrlPoly, t) {
  11982. var tx = 1.0 - t;
  11983. var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
  11984. pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
  11985. pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
  11986. pD = maths.mulItems(ctrlPoly[3], t * t * t);
  11987. return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  11988. }
  11989. static qprime(ctrlPoly, t) {
  11990. var tx = 1.0 - t;
  11991. var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
  11992. pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
  11993. pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
  11994. return maths.addArrays(maths.addArrays(pA, pB), pC);
  11995. }
  11996. static qprimeprime(ctrlPoly, t) {
  11997. 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));
  11998. }
  11999. }
  12000. module.exports = fitCurve;
  12001. module.exports.fitCubic = fitCubic;
  12002. module.exports.createTangent = createTangent;
  12003. /***/ }),
  12004. /* 32 */
  12005. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  12006. Object.defineProperty(exports, "__esModule", ({
  12007. value: true
  12008. }));
  12009. exports.AnnotationLayer = void 0;
  12010. var _util = __w_pdfjs_require__(1);
  12011. var _display_utils = __w_pdfjs_require__(6);
  12012. var _annotation_storage = __w_pdfjs_require__(3);
  12013. var _scripting_utils = __w_pdfjs_require__(33);
  12014. var _xfa_layer = __w_pdfjs_require__(34);
  12015. const DEFAULT_TAB_INDEX = 1000;
  12016. const DEFAULT_FONT_SIZE = 9;
  12017. const GetElementsByNameSet = new WeakSet();
  12018. function getRectDims(rect) {
  12019. return {
  12020. width: rect[2] - rect[0],
  12021. height: rect[3] - rect[1]
  12022. };
  12023. }
  12024. class AnnotationElementFactory {
  12025. static create(parameters) {
  12026. const subtype = parameters.data.annotationType;
  12027. switch (subtype) {
  12028. case _util.AnnotationType.LINK:
  12029. return new LinkAnnotationElement(parameters);
  12030. case _util.AnnotationType.TEXT:
  12031. return new TextAnnotationElement(parameters);
  12032. case _util.AnnotationType.WIDGET:
  12033. const fieldType = parameters.data.fieldType;
  12034. switch (fieldType) {
  12035. case "Tx":
  12036. return new TextWidgetAnnotationElement(parameters);
  12037. case "Btn":
  12038. if (parameters.data.radioButton) {
  12039. return new RadioButtonWidgetAnnotationElement(parameters);
  12040. } else if (parameters.data.checkBox) {
  12041. return new CheckboxWidgetAnnotationElement(parameters);
  12042. }
  12043. return new PushButtonWidgetAnnotationElement(parameters);
  12044. case "Ch":
  12045. return new ChoiceWidgetAnnotationElement(parameters);
  12046. }
  12047. return new WidgetAnnotationElement(parameters);
  12048. case _util.AnnotationType.POPUP:
  12049. return new PopupAnnotationElement(parameters);
  12050. case _util.AnnotationType.FREETEXT:
  12051. return new FreeTextAnnotationElement(parameters);
  12052. case _util.AnnotationType.LINE:
  12053. return new LineAnnotationElement(parameters);
  12054. case _util.AnnotationType.SQUARE:
  12055. return new SquareAnnotationElement(parameters);
  12056. case _util.AnnotationType.CIRCLE:
  12057. return new CircleAnnotationElement(parameters);
  12058. case _util.AnnotationType.POLYLINE:
  12059. return new PolylineAnnotationElement(parameters);
  12060. case _util.AnnotationType.CARET:
  12061. return new CaretAnnotationElement(parameters);
  12062. case _util.AnnotationType.INK:
  12063. return new InkAnnotationElement(parameters);
  12064. case _util.AnnotationType.POLYGON:
  12065. return new PolygonAnnotationElement(parameters);
  12066. case _util.AnnotationType.HIGHLIGHT:
  12067. return new HighlightAnnotationElement(parameters);
  12068. case _util.AnnotationType.UNDERLINE:
  12069. return new UnderlineAnnotationElement(parameters);
  12070. case _util.AnnotationType.SQUIGGLY:
  12071. return new SquigglyAnnotationElement(parameters);
  12072. case _util.AnnotationType.STRIKEOUT:
  12073. return new StrikeOutAnnotationElement(parameters);
  12074. case _util.AnnotationType.STAMP:
  12075. return new StampAnnotationElement(parameters);
  12076. case _util.AnnotationType.FILEATTACHMENT:
  12077. return new FileAttachmentAnnotationElement(parameters);
  12078. default:
  12079. return new AnnotationElement(parameters);
  12080. }
  12081. }
  12082. }
  12083. class AnnotationElement {
  12084. constructor(parameters, {
  12085. isRenderable = false,
  12086. ignoreBorder = false,
  12087. createQuadrilaterals = false
  12088. } = {}) {
  12089. this.isRenderable = isRenderable;
  12090. this.data = parameters.data;
  12091. this.layer = parameters.layer;
  12092. this.page = parameters.page;
  12093. this.viewport = parameters.viewport;
  12094. this.linkService = parameters.linkService;
  12095. this.downloadManager = parameters.downloadManager;
  12096. this.imageResourcesPath = parameters.imageResourcesPath;
  12097. this.renderForms = parameters.renderForms;
  12098. this.svgFactory = parameters.svgFactory;
  12099. this.annotationStorage = parameters.annotationStorage;
  12100. this.enableScripting = parameters.enableScripting;
  12101. this.hasJSActions = parameters.hasJSActions;
  12102. this._fieldObjects = parameters.fieldObjects;
  12103. if (isRenderable) {
  12104. this.container = this._createContainer(ignoreBorder);
  12105. }
  12106. if (createQuadrilaterals) {
  12107. this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
  12108. }
  12109. }
  12110. _createContainer(ignoreBorder = false) {
  12111. const {
  12112. data,
  12113. page,
  12114. viewport
  12115. } = this;
  12116. const container = document.createElement("section");
  12117. container.setAttribute("data-annotation-id", data.id);
  12118. if (data.noRotate) {
  12119. container.classList.add("norotate");
  12120. }
  12121. const {
  12122. pageWidth,
  12123. pageHeight,
  12124. pageX,
  12125. pageY
  12126. } = viewport.rawDims;
  12127. const {
  12128. width,
  12129. height
  12130. } = getRectDims(data.rect);
  12131. 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]]);
  12132. if (!ignoreBorder && data.borderStyle.width > 0) {
  12133. container.style.borderWidth = `${data.borderStyle.width}px`;
  12134. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  12135. const verticalRadius = data.borderStyle.verticalCornerRadius;
  12136. if (horizontalRadius > 0 || verticalRadius > 0) {
  12137. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  12138. container.style.borderRadius = radius;
  12139. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  12140. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  12141. container.style.borderRadius = radius;
  12142. }
  12143. switch (data.borderStyle.style) {
  12144. case _util.AnnotationBorderStyleType.SOLID:
  12145. container.style.borderStyle = "solid";
  12146. break;
  12147. case _util.AnnotationBorderStyleType.DASHED:
  12148. container.style.borderStyle = "dashed";
  12149. break;
  12150. case _util.AnnotationBorderStyleType.BEVELED:
  12151. (0, _util.warn)("Unimplemented border style: beveled");
  12152. break;
  12153. case _util.AnnotationBorderStyleType.INSET:
  12154. (0, _util.warn)("Unimplemented border style: inset");
  12155. break;
  12156. case _util.AnnotationBorderStyleType.UNDERLINE:
  12157. container.style.borderBottomStyle = "solid";
  12158. break;
  12159. default:
  12160. break;
  12161. }
  12162. const borderColor = data.borderColor || null;
  12163. if (borderColor) {
  12164. container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  12165. } else {
  12166. container.style.borderWidth = 0;
  12167. }
  12168. }
  12169. container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  12170. container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  12171. const {
  12172. rotation
  12173. } = data;
  12174. if (data.hasOwnCanvas || rotation === 0) {
  12175. container.style.width = `${100 * width / pageWidth}%`;
  12176. container.style.height = `${100 * height / pageHeight}%`;
  12177. } else {
  12178. this.setRotation(rotation, container);
  12179. }
  12180. return container;
  12181. }
  12182. setRotation(angle, container = this.container) {
  12183. const {
  12184. pageWidth,
  12185. pageHeight
  12186. } = this.viewport.rawDims;
  12187. const {
  12188. width,
  12189. height
  12190. } = getRectDims(this.data.rect);
  12191. let elementWidth, elementHeight;
  12192. if (angle % 180 === 0) {
  12193. elementWidth = 100 * width / pageWidth;
  12194. elementHeight = 100 * height / pageHeight;
  12195. } else {
  12196. elementWidth = 100 * height / pageWidth;
  12197. elementHeight = 100 * width / pageHeight;
  12198. }
  12199. container.style.width = `${elementWidth}%`;
  12200. container.style.height = `${elementHeight}%`;
  12201. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  12202. }
  12203. get _commonActions() {
  12204. const setColor = (jsName, styleName, event) => {
  12205. const color = event.detail[jsName];
  12206. event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
  12207. };
  12208. return (0, _util.shadow)(this, "_commonActions", {
  12209. display: event => {
  12210. const hidden = event.detail.display % 2 === 1;
  12211. this.container.style.visibility = hidden ? "hidden" : "visible";
  12212. this.annotationStorage.setValue(this.data.id, {
  12213. hidden,
  12214. print: event.detail.display === 0 || event.detail.display === 3
  12215. });
  12216. },
  12217. print: event => {
  12218. this.annotationStorage.setValue(this.data.id, {
  12219. print: event.detail.print
  12220. });
  12221. },
  12222. hidden: event => {
  12223. this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
  12224. this.annotationStorage.setValue(this.data.id, {
  12225. hidden: event.detail.hidden
  12226. });
  12227. },
  12228. focus: event => {
  12229. setTimeout(() => event.target.focus({
  12230. preventScroll: false
  12231. }), 0);
  12232. },
  12233. userName: event => {
  12234. event.target.title = event.detail.userName;
  12235. },
  12236. readonly: event => {
  12237. if (event.detail.readonly) {
  12238. event.target.setAttribute("readonly", "");
  12239. } else {
  12240. event.target.removeAttribute("readonly");
  12241. }
  12242. },
  12243. required: event => {
  12244. this._setRequired(event.target, event.detail.required);
  12245. },
  12246. bgColor: event => {
  12247. setColor("bgColor", "backgroundColor", event);
  12248. },
  12249. fillColor: event => {
  12250. setColor("fillColor", "backgroundColor", event);
  12251. },
  12252. fgColor: event => {
  12253. setColor("fgColor", "color", event);
  12254. },
  12255. textColor: event => {
  12256. setColor("textColor", "color", event);
  12257. },
  12258. borderColor: event => {
  12259. setColor("borderColor", "borderColor", event);
  12260. },
  12261. strokeColor: event => {
  12262. setColor("strokeColor", "borderColor", event);
  12263. },
  12264. rotation: event => {
  12265. const angle = event.detail.rotation;
  12266. this.setRotation(angle);
  12267. this.annotationStorage.setValue(this.data.id, {
  12268. rotation: angle
  12269. });
  12270. }
  12271. });
  12272. }
  12273. _dispatchEventFromSandbox(actions, jsEvent) {
  12274. const commonActions = this._commonActions;
  12275. for (const name of Object.keys(jsEvent.detail)) {
  12276. const action = actions[name] || commonActions[name];
  12277. action?.(jsEvent);
  12278. }
  12279. }
  12280. _setDefaultPropertiesFromJS(element) {
  12281. if (!this.enableScripting) {
  12282. return;
  12283. }
  12284. const storedData = this.annotationStorage.getRawValue(this.data.id);
  12285. if (!storedData) {
  12286. return;
  12287. }
  12288. const commonActions = this._commonActions;
  12289. for (const [actionName, detail] of Object.entries(storedData)) {
  12290. const action = commonActions[actionName];
  12291. if (action) {
  12292. const eventProxy = {
  12293. detail: {
  12294. [actionName]: detail
  12295. },
  12296. target: element
  12297. };
  12298. action(eventProxy);
  12299. delete storedData[actionName];
  12300. }
  12301. }
  12302. }
  12303. _createQuadrilaterals(ignoreBorder = false) {
  12304. if (!this.data.quadPoints) {
  12305. return null;
  12306. }
  12307. const quadrilaterals = [];
  12308. const savedRect = this.data.rect;
  12309. for (const quadPoint of this.data.quadPoints) {
  12310. this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
  12311. quadrilaterals.push(this._createContainer(ignoreBorder));
  12312. }
  12313. this.data.rect = savedRect;
  12314. return quadrilaterals;
  12315. }
  12316. _createPopup(trigger, data) {
  12317. let container = this.container;
  12318. if (this.quadrilaterals) {
  12319. trigger = trigger || this.quadrilaterals;
  12320. container = this.quadrilaterals[0];
  12321. }
  12322. if (!trigger) {
  12323. trigger = document.createElement("div");
  12324. trigger.classList.add("popupTriggerArea");
  12325. container.append(trigger);
  12326. }
  12327. const popupElement = new PopupElement({
  12328. container,
  12329. trigger,
  12330. color: data.color,
  12331. titleObj: data.titleObj,
  12332. modificationDate: data.modificationDate,
  12333. contentsObj: data.contentsObj,
  12334. richText: data.richText,
  12335. hideWrapper: true
  12336. });
  12337. const popup = popupElement.render();
  12338. popup.style.left = "100%";
  12339. container.append(popup);
  12340. }
  12341. _renderQuadrilaterals(className) {
  12342. for (const quadrilateral of this.quadrilaterals) {
  12343. quadrilateral.classList.add(className);
  12344. }
  12345. return this.quadrilaterals;
  12346. }
  12347. render() {
  12348. (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  12349. }
  12350. _getElementsByName(name, skipId = null) {
  12351. const fields = [];
  12352. if (this._fieldObjects) {
  12353. const fieldObj = this._fieldObjects[name];
  12354. if (fieldObj) {
  12355. for (const {
  12356. page,
  12357. id,
  12358. exportValues
  12359. } of fieldObj) {
  12360. if (page === -1) {
  12361. continue;
  12362. }
  12363. if (id === skipId) {
  12364. continue;
  12365. }
  12366. const exportValue = typeof exportValues === "string" ? exportValues : null;
  12367. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  12368. if (domElement && !GetElementsByNameSet.has(domElement)) {
  12369. (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
  12370. continue;
  12371. }
  12372. fields.push({
  12373. id,
  12374. exportValue,
  12375. domElement
  12376. });
  12377. }
  12378. }
  12379. return fields;
  12380. }
  12381. for (const domElement of document.getElementsByName(name)) {
  12382. const {
  12383. exportValue
  12384. } = domElement;
  12385. const id = domElement.getAttribute("data-element-id");
  12386. if (id === skipId) {
  12387. continue;
  12388. }
  12389. if (!GetElementsByNameSet.has(domElement)) {
  12390. continue;
  12391. }
  12392. fields.push({
  12393. id,
  12394. exportValue,
  12395. domElement
  12396. });
  12397. }
  12398. return fields;
  12399. }
  12400. }
  12401. class LinkAnnotationElement extends AnnotationElement {
  12402. constructor(parameters, options = null) {
  12403. super(parameters, {
  12404. isRenderable: true,
  12405. ignoreBorder: !!options?.ignoreBorder,
  12406. createQuadrilaterals: true
  12407. });
  12408. this.isTooltipOnly = parameters.data.isTooltipOnly;
  12409. }
  12410. render() {
  12411. const {
  12412. data,
  12413. linkService
  12414. } = this;
  12415. const link = document.createElement("a");
  12416. link.setAttribute("data-element-id", data.id);
  12417. let isBound = false;
  12418. if (data.url) {
  12419. linkService.addLinkAttributes(link, data.url, data.newWindow);
  12420. isBound = true;
  12421. } else if (data.action) {
  12422. this._bindNamedAction(link, data.action);
  12423. isBound = true;
  12424. } else if (data.attachment) {
  12425. this._bindAttachment(link, data.attachment);
  12426. isBound = true;
  12427. } else if (data.setOCGState) {
  12428. this.#bindSetOCGState(link, data.setOCGState);
  12429. isBound = true;
  12430. } else if (data.dest) {
  12431. this._bindLink(link, data.dest);
  12432. isBound = true;
  12433. } else {
  12434. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  12435. this._bindJSAction(link, data);
  12436. isBound = true;
  12437. }
  12438. if (data.resetForm) {
  12439. this._bindResetFormAction(link, data.resetForm);
  12440. isBound = true;
  12441. } else if (this.isTooltipOnly && !isBound) {
  12442. this._bindLink(link, "");
  12443. isBound = true;
  12444. }
  12445. }
  12446. if (this.quadrilaterals) {
  12447. return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
  12448. const linkElement = index === 0 ? link : link.cloneNode();
  12449. quadrilateral.append(linkElement);
  12450. return quadrilateral;
  12451. });
  12452. }
  12453. this.container.classList.add("linkAnnotation");
  12454. if (isBound) {
  12455. this.container.append(link);
  12456. }
  12457. return this.container;
  12458. }
  12459. #setInternalLink() {
  12460. this.container.setAttribute("data-internal-link", "");
  12461. }
  12462. _bindLink(link, destination) {
  12463. link.href = this.linkService.getDestinationHash(destination);
  12464. link.onclick = () => {
  12465. if (destination) {
  12466. this.linkService.goToDestination(destination);
  12467. }
  12468. return false;
  12469. };
  12470. if (destination || destination === "") {
  12471. this.#setInternalLink();
  12472. }
  12473. }
  12474. _bindNamedAction(link, action) {
  12475. link.href = this.linkService.getAnchorUrl("");
  12476. link.onclick = () => {
  12477. this.linkService.executeNamedAction(action);
  12478. return false;
  12479. };
  12480. this.#setInternalLink();
  12481. }
  12482. _bindAttachment(link, attachment) {
  12483. link.href = this.linkService.getAnchorUrl("");
  12484. link.onclick = () => {
  12485. this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
  12486. return false;
  12487. };
  12488. this.#setInternalLink();
  12489. }
  12490. #bindSetOCGState(link, action) {
  12491. link.href = this.linkService.getAnchorUrl("");
  12492. link.onclick = () => {
  12493. this.linkService.executeSetOCGState(action);
  12494. return false;
  12495. };
  12496. this.#setInternalLink();
  12497. }
  12498. _bindJSAction(link, data) {
  12499. link.href = this.linkService.getAnchorUrl("");
  12500. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  12501. for (const name of Object.keys(data.actions)) {
  12502. const jsName = map.get(name);
  12503. if (!jsName) {
  12504. continue;
  12505. }
  12506. link[jsName] = () => {
  12507. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12508. source: this,
  12509. detail: {
  12510. id: data.id,
  12511. name
  12512. }
  12513. });
  12514. return false;
  12515. };
  12516. }
  12517. if (!link.onclick) {
  12518. link.onclick = () => false;
  12519. }
  12520. this.#setInternalLink();
  12521. }
  12522. _bindResetFormAction(link, resetForm) {
  12523. const otherClickAction = link.onclick;
  12524. if (!otherClickAction) {
  12525. link.href = this.linkService.getAnchorUrl("");
  12526. }
  12527. this.#setInternalLink();
  12528. if (!this._fieldObjects) {
  12529. (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  12530. if (!otherClickAction) {
  12531. link.onclick = () => false;
  12532. }
  12533. return;
  12534. }
  12535. link.onclick = () => {
  12536. otherClickAction?.();
  12537. const {
  12538. fields: resetFormFields,
  12539. refs: resetFormRefs,
  12540. include
  12541. } = resetForm;
  12542. const allFields = [];
  12543. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  12544. const fieldIds = new Set(resetFormRefs);
  12545. for (const fieldName of resetFormFields) {
  12546. const fields = this._fieldObjects[fieldName] || [];
  12547. for (const {
  12548. id
  12549. } of fields) {
  12550. fieldIds.add(id);
  12551. }
  12552. }
  12553. for (const fields of Object.values(this._fieldObjects)) {
  12554. for (const field of fields) {
  12555. if (fieldIds.has(field.id) === include) {
  12556. allFields.push(field);
  12557. }
  12558. }
  12559. }
  12560. } else {
  12561. for (const fields of Object.values(this._fieldObjects)) {
  12562. allFields.push(...fields);
  12563. }
  12564. }
  12565. const storage = this.annotationStorage;
  12566. const allIds = [];
  12567. for (const field of allFields) {
  12568. const {
  12569. id
  12570. } = field;
  12571. allIds.push(id);
  12572. switch (field.type) {
  12573. case "text":
  12574. {
  12575. const value = field.defaultValue || "";
  12576. storage.setValue(id, {
  12577. value
  12578. });
  12579. break;
  12580. }
  12581. case "checkbox":
  12582. case "radiobutton":
  12583. {
  12584. const value = field.defaultValue === field.exportValues;
  12585. storage.setValue(id, {
  12586. value
  12587. });
  12588. break;
  12589. }
  12590. case "combobox":
  12591. case "listbox":
  12592. {
  12593. const value = field.defaultValue || "";
  12594. storage.setValue(id, {
  12595. value
  12596. });
  12597. break;
  12598. }
  12599. default:
  12600. continue;
  12601. }
  12602. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  12603. if (!domElement) {
  12604. continue;
  12605. } else if (!GetElementsByNameSet.has(domElement)) {
  12606. (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
  12607. continue;
  12608. }
  12609. domElement.dispatchEvent(new Event("resetform"));
  12610. }
  12611. if (this.enableScripting) {
  12612. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12613. source: this,
  12614. detail: {
  12615. id: "app",
  12616. ids: allIds,
  12617. name: "ResetForm"
  12618. }
  12619. });
  12620. }
  12621. return false;
  12622. };
  12623. }
  12624. }
  12625. class TextAnnotationElement extends AnnotationElement {
  12626. constructor(parameters) {
  12627. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  12628. super(parameters, {
  12629. isRenderable
  12630. });
  12631. }
  12632. render() {
  12633. this.container.classList.add("textAnnotation");
  12634. const image = document.createElement("img");
  12635. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  12636. image.alt = "[{{type}} Annotation]";
  12637. image.dataset.l10nId = "text_annotation_type";
  12638. image.dataset.l10nArgs = JSON.stringify({
  12639. type: this.data.name
  12640. });
  12641. if (!this.data.hasPopup) {
  12642. this._createPopup(image, this.data);
  12643. }
  12644. this.container.append(image);
  12645. return this.container;
  12646. }
  12647. }
  12648. class WidgetAnnotationElement extends AnnotationElement {
  12649. render() {
  12650. if (this.data.alternativeText) {
  12651. this.container.title = this.data.alternativeText;
  12652. }
  12653. return this.container;
  12654. }
  12655. _getKeyModifier(event) {
  12656. const {
  12657. isWin,
  12658. isMac
  12659. } = _util.FeatureTest.platform;
  12660. return isWin && event.ctrlKey || isMac && event.metaKey;
  12661. }
  12662. _setEventListener(element, baseName, eventName, valueGetter) {
  12663. if (baseName.includes("mouse")) {
  12664. element.addEventListener(baseName, event => {
  12665. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12666. source: this,
  12667. detail: {
  12668. id: this.data.id,
  12669. name: eventName,
  12670. value: valueGetter(event),
  12671. shift: event.shiftKey,
  12672. modifier: this._getKeyModifier(event)
  12673. }
  12674. });
  12675. });
  12676. } else {
  12677. element.addEventListener(baseName, event => {
  12678. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12679. source: this,
  12680. detail: {
  12681. id: this.data.id,
  12682. name: eventName,
  12683. value: valueGetter(event)
  12684. }
  12685. });
  12686. });
  12687. }
  12688. }
  12689. _setEventListeners(element, names, getter) {
  12690. for (const [baseName, eventName] of names) {
  12691. if (eventName === "Action" || this.data.actions?.[eventName]) {
  12692. this._setEventListener(element, baseName, eventName, getter);
  12693. }
  12694. }
  12695. }
  12696. _setBackgroundColor(element) {
  12697. const color = this.data.backgroundColor || null;
  12698. element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  12699. }
  12700. _setTextStyle(element) {
  12701. const TEXT_ALIGNMENT = ["left", "center", "right"];
  12702. const {
  12703. fontColor
  12704. } = this.data.defaultAppearanceData;
  12705. const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
  12706. const style = element.style;
  12707. let computedFontSize;
  12708. const BORDER_SIZE = 2;
  12709. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  12710. if (this.data.multiLine) {
  12711. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  12712. const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
  12713. const lineHeight = height / numberOfLines;
  12714. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
  12715. } else {
  12716. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  12717. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
  12718. }
  12719. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  12720. style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  12721. if (this.data.textAlignment !== null) {
  12722. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  12723. }
  12724. }
  12725. _setRequired(element, isRequired) {
  12726. if (isRequired) {
  12727. element.setAttribute("required", true);
  12728. } else {
  12729. element.removeAttribute("required");
  12730. }
  12731. element.setAttribute("aria-required", isRequired);
  12732. }
  12733. }
  12734. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  12735. constructor(parameters) {
  12736. const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  12737. super(parameters, {
  12738. isRenderable
  12739. });
  12740. }
  12741. setPropertyOnSiblings(base, key, value, keyInStorage) {
  12742. const storage = this.annotationStorage;
  12743. for (const element of this._getElementsByName(base.name, base.id)) {
  12744. if (element.domElement) {
  12745. element.domElement[key] = value;
  12746. }
  12747. storage.setValue(element.id, {
  12748. [keyInStorage]: value
  12749. });
  12750. }
  12751. }
  12752. render() {
  12753. const storage = this.annotationStorage;
  12754. const id = this.data.id;
  12755. this.container.classList.add("textWidgetAnnotation");
  12756. let element = null;
  12757. if (this.renderForms) {
  12758. const storedData = storage.getValue(id, {
  12759. value: this.data.fieldValue
  12760. });
  12761. let textContent = storedData.formattedValue || storedData.value || "";
  12762. const maxLen = storage.getValue(id, {
  12763. charLimit: this.data.maxLen
  12764. }).charLimit;
  12765. if (maxLen && textContent.length > maxLen) {
  12766. textContent = textContent.slice(0, maxLen);
  12767. }
  12768. const elementData = {
  12769. userValue: textContent,
  12770. formattedValue: null,
  12771. lastCommittedValue: null,
  12772. commitKey: 1
  12773. };
  12774. if (this.data.multiLine) {
  12775. element = document.createElement("textarea");
  12776. element.textContent = textContent;
  12777. if (this.data.doNotScroll) {
  12778. element.style.overflowY = "hidden";
  12779. }
  12780. } else {
  12781. element = document.createElement("input");
  12782. element.type = "text";
  12783. element.setAttribute("value", textContent);
  12784. if (this.data.doNotScroll) {
  12785. element.style.overflowX = "hidden";
  12786. }
  12787. }
  12788. GetElementsByNameSet.add(element);
  12789. element.setAttribute("data-element-id", id);
  12790. element.disabled = this.data.readOnly;
  12791. element.name = this.data.fieldName;
  12792. element.tabIndex = DEFAULT_TAB_INDEX;
  12793. this._setRequired(element, this.data.required);
  12794. if (maxLen) {
  12795. element.maxLength = maxLen;
  12796. }
  12797. element.addEventListener("input", event => {
  12798. storage.setValue(id, {
  12799. value: event.target.value
  12800. });
  12801. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  12802. });
  12803. element.addEventListener("resetform", event => {
  12804. const defaultValue = this.data.defaultFieldValue ?? "";
  12805. element.value = elementData.userValue = defaultValue;
  12806. elementData.formattedValue = null;
  12807. });
  12808. let blurListener = event => {
  12809. const {
  12810. formattedValue
  12811. } = elementData;
  12812. if (formattedValue !== null && formattedValue !== undefined) {
  12813. event.target.value = formattedValue;
  12814. }
  12815. event.target.scrollLeft = 0;
  12816. };
  12817. if (this.enableScripting && this.hasJSActions) {
  12818. element.addEventListener("focus", event => {
  12819. const {
  12820. target
  12821. } = event;
  12822. if (elementData.userValue) {
  12823. target.value = elementData.userValue;
  12824. }
  12825. elementData.lastCommittedValue = target.value;
  12826. elementData.commitKey = 1;
  12827. });
  12828. element.addEventListener("updatefromsandbox", jsEvent => {
  12829. const actions = {
  12830. value(event) {
  12831. elementData.userValue = event.detail.value ?? "";
  12832. storage.setValue(id, {
  12833. value: elementData.userValue.toString()
  12834. });
  12835. event.target.value = elementData.userValue;
  12836. },
  12837. formattedValue(event) {
  12838. const {
  12839. formattedValue
  12840. } = event.detail;
  12841. elementData.formattedValue = formattedValue;
  12842. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  12843. event.target.value = formattedValue;
  12844. }
  12845. storage.setValue(id, {
  12846. formattedValue
  12847. });
  12848. },
  12849. selRange(event) {
  12850. event.target.setSelectionRange(...event.detail.selRange);
  12851. },
  12852. charLimit: event => {
  12853. const {
  12854. charLimit
  12855. } = event.detail;
  12856. const {
  12857. target
  12858. } = event;
  12859. if (charLimit === 0) {
  12860. target.removeAttribute("maxLength");
  12861. return;
  12862. }
  12863. target.setAttribute("maxLength", charLimit);
  12864. let value = elementData.userValue;
  12865. if (!value || value.length <= charLimit) {
  12866. return;
  12867. }
  12868. value = value.slice(0, charLimit);
  12869. target.value = elementData.userValue = value;
  12870. storage.setValue(id, {
  12871. value
  12872. });
  12873. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12874. source: this,
  12875. detail: {
  12876. id,
  12877. name: "Keystroke",
  12878. value,
  12879. willCommit: true,
  12880. commitKey: 1,
  12881. selStart: target.selectionStart,
  12882. selEnd: target.selectionEnd
  12883. }
  12884. });
  12885. }
  12886. };
  12887. this._dispatchEventFromSandbox(actions, jsEvent);
  12888. });
  12889. element.addEventListener("keydown", event => {
  12890. elementData.commitKey = 1;
  12891. let commitKey = -1;
  12892. if (event.key === "Escape") {
  12893. commitKey = 0;
  12894. } else if (event.key === "Enter" && !this.data.multiLine) {
  12895. commitKey = 2;
  12896. } else if (event.key === "Tab") {
  12897. elementData.commitKey = 3;
  12898. }
  12899. if (commitKey === -1) {
  12900. return;
  12901. }
  12902. const {
  12903. value
  12904. } = event.target;
  12905. if (elementData.lastCommittedValue === value) {
  12906. return;
  12907. }
  12908. elementData.lastCommittedValue = value;
  12909. elementData.userValue = value;
  12910. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12911. source: this,
  12912. detail: {
  12913. id,
  12914. name: "Keystroke",
  12915. value,
  12916. willCommit: true,
  12917. commitKey,
  12918. selStart: event.target.selectionStart,
  12919. selEnd: event.target.selectionEnd
  12920. }
  12921. });
  12922. });
  12923. const _blurListener = blurListener;
  12924. blurListener = null;
  12925. element.addEventListener("blur", event => {
  12926. if (!event.relatedTarget) {
  12927. return;
  12928. }
  12929. const {
  12930. value
  12931. } = event.target;
  12932. elementData.userValue = value;
  12933. if (elementData.lastCommittedValue !== value) {
  12934. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12935. source: this,
  12936. detail: {
  12937. id,
  12938. name: "Keystroke",
  12939. value,
  12940. willCommit: true,
  12941. commitKey: elementData.commitKey,
  12942. selStart: event.target.selectionStart,
  12943. selEnd: event.target.selectionEnd
  12944. }
  12945. });
  12946. }
  12947. _blurListener(event);
  12948. });
  12949. if (this.data.actions?.Keystroke) {
  12950. element.addEventListener("beforeinput", event => {
  12951. elementData.lastCommittedValue = null;
  12952. const {
  12953. data,
  12954. target
  12955. } = event;
  12956. const {
  12957. value,
  12958. selectionStart,
  12959. selectionEnd
  12960. } = target;
  12961. let selStart = selectionStart,
  12962. selEnd = selectionEnd;
  12963. switch (event.inputType) {
  12964. case "deleteWordBackward":
  12965. {
  12966. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  12967. if (match) {
  12968. selStart -= match[0].length;
  12969. }
  12970. break;
  12971. }
  12972. case "deleteWordForward":
  12973. {
  12974. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  12975. if (match) {
  12976. selEnd += match[0].length;
  12977. }
  12978. break;
  12979. }
  12980. case "deleteContentBackward":
  12981. if (selectionStart === selectionEnd) {
  12982. selStart -= 1;
  12983. }
  12984. break;
  12985. case "deleteContentForward":
  12986. if (selectionStart === selectionEnd) {
  12987. selEnd += 1;
  12988. }
  12989. break;
  12990. }
  12991. event.preventDefault();
  12992. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  12993. source: this,
  12994. detail: {
  12995. id,
  12996. name: "Keystroke",
  12997. value,
  12998. change: data || "",
  12999. willCommit: false,
  13000. selStart,
  13001. selEnd
  13002. }
  13003. });
  13004. });
  13005. }
  13006. this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  13007. }
  13008. if (blurListener) {
  13009. element.addEventListener("blur", blurListener);
  13010. }
  13011. if (this.data.comb) {
  13012. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  13013. const combWidth = fieldWidth / maxLen;
  13014. element.classList.add("comb");
  13015. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  13016. }
  13017. } else {
  13018. element = document.createElement("div");
  13019. element.textContent = this.data.fieldValue;
  13020. element.style.verticalAlign = "middle";
  13021. element.style.display = "table-cell";
  13022. }
  13023. this._setTextStyle(element);
  13024. this._setBackgroundColor(element);
  13025. this._setDefaultPropertiesFromJS(element);
  13026. this.container.append(element);
  13027. return this.container;
  13028. }
  13029. }
  13030. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  13031. constructor(parameters) {
  13032. super(parameters, {
  13033. isRenderable: parameters.renderForms
  13034. });
  13035. }
  13036. render() {
  13037. const storage = this.annotationStorage;
  13038. const data = this.data;
  13039. const id = data.id;
  13040. let value = storage.getValue(id, {
  13041. value: data.exportValue === data.fieldValue
  13042. }).value;
  13043. if (typeof value === "string") {
  13044. value = value !== "Off";
  13045. storage.setValue(id, {
  13046. value
  13047. });
  13048. }
  13049. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  13050. const element = document.createElement("input");
  13051. GetElementsByNameSet.add(element);
  13052. element.setAttribute("data-element-id", id);
  13053. element.disabled = data.readOnly;
  13054. this._setRequired(element, this.data.required);
  13055. element.type = "checkbox";
  13056. element.name = data.fieldName;
  13057. if (value) {
  13058. element.setAttribute("checked", true);
  13059. }
  13060. element.setAttribute("exportValue", data.exportValue);
  13061. element.tabIndex = DEFAULT_TAB_INDEX;
  13062. element.addEventListener("change", event => {
  13063. const {
  13064. name,
  13065. checked
  13066. } = event.target;
  13067. for (const checkbox of this._getElementsByName(name, id)) {
  13068. const curChecked = checked && checkbox.exportValue === data.exportValue;
  13069. if (checkbox.domElement) {
  13070. checkbox.domElement.checked = curChecked;
  13071. }
  13072. storage.setValue(checkbox.id, {
  13073. value: curChecked
  13074. });
  13075. }
  13076. storage.setValue(id, {
  13077. value: checked
  13078. });
  13079. });
  13080. element.addEventListener("resetform", event => {
  13081. const defaultValue = data.defaultFieldValue || "Off";
  13082. event.target.checked = defaultValue === data.exportValue;
  13083. });
  13084. if (this.enableScripting && this.hasJSActions) {
  13085. element.addEventListener("updatefromsandbox", jsEvent => {
  13086. const actions = {
  13087. value(event) {
  13088. event.target.checked = event.detail.value !== "Off";
  13089. storage.setValue(id, {
  13090. value: event.target.checked
  13091. });
  13092. }
  13093. };
  13094. this._dispatchEventFromSandbox(actions, jsEvent);
  13095. });
  13096. 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);
  13097. }
  13098. this._setBackgroundColor(element);
  13099. this._setDefaultPropertiesFromJS(element);
  13100. this.container.append(element);
  13101. return this.container;
  13102. }
  13103. }
  13104. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  13105. constructor(parameters) {
  13106. super(parameters, {
  13107. isRenderable: parameters.renderForms
  13108. });
  13109. }
  13110. render() {
  13111. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  13112. const storage = this.annotationStorage;
  13113. const data = this.data;
  13114. const id = data.id;
  13115. let value = storage.getValue(id, {
  13116. value: data.fieldValue === data.buttonValue
  13117. }).value;
  13118. if (typeof value === "string") {
  13119. value = value !== data.buttonValue;
  13120. storage.setValue(id, {
  13121. value
  13122. });
  13123. }
  13124. const element = document.createElement("input");
  13125. GetElementsByNameSet.add(element);
  13126. element.setAttribute("data-element-id", id);
  13127. element.disabled = data.readOnly;
  13128. this._setRequired(element, this.data.required);
  13129. element.type = "radio";
  13130. element.name = data.fieldName;
  13131. if (value) {
  13132. element.setAttribute("checked", true);
  13133. }
  13134. element.tabIndex = DEFAULT_TAB_INDEX;
  13135. element.addEventListener("change", event => {
  13136. const {
  13137. name,
  13138. checked
  13139. } = event.target;
  13140. for (const radio of this._getElementsByName(name, id)) {
  13141. storage.setValue(radio.id, {
  13142. value: false
  13143. });
  13144. }
  13145. storage.setValue(id, {
  13146. value: checked
  13147. });
  13148. });
  13149. element.addEventListener("resetform", event => {
  13150. const defaultValue = data.defaultFieldValue;
  13151. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  13152. });
  13153. if (this.enableScripting && this.hasJSActions) {
  13154. const pdfButtonValue = data.buttonValue;
  13155. element.addEventListener("updatefromsandbox", jsEvent => {
  13156. const actions = {
  13157. value: event => {
  13158. const checked = pdfButtonValue === event.detail.value;
  13159. for (const radio of this._getElementsByName(event.target.name)) {
  13160. const curChecked = checked && radio.id === id;
  13161. if (radio.domElement) {
  13162. radio.domElement.checked = curChecked;
  13163. }
  13164. storage.setValue(radio.id, {
  13165. value: curChecked
  13166. });
  13167. }
  13168. }
  13169. };
  13170. this._dispatchEventFromSandbox(actions, jsEvent);
  13171. });
  13172. 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);
  13173. }
  13174. this._setBackgroundColor(element);
  13175. this._setDefaultPropertiesFromJS(element);
  13176. this.container.append(element);
  13177. return this.container;
  13178. }
  13179. }
  13180. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  13181. constructor(parameters) {
  13182. super(parameters, {
  13183. ignoreBorder: parameters.data.hasAppearance
  13184. });
  13185. }
  13186. render() {
  13187. const container = super.render();
  13188. container.classList.add("buttonWidgetAnnotation", "pushButton");
  13189. if (this.data.alternativeText) {
  13190. container.title = this.data.alternativeText;
  13191. }
  13192. const linkElement = container.lastChild;
  13193. if (this.enableScripting && this.hasJSActions && linkElement) {
  13194. this._setDefaultPropertiesFromJS(linkElement);
  13195. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  13196. this._dispatchEventFromSandbox({}, jsEvent);
  13197. });
  13198. }
  13199. return container;
  13200. }
  13201. }
  13202. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  13203. constructor(parameters) {
  13204. super(parameters, {
  13205. isRenderable: parameters.renderForms
  13206. });
  13207. }
  13208. render() {
  13209. this.container.classList.add("choiceWidgetAnnotation");
  13210. const storage = this.annotationStorage;
  13211. const id = this.data.id;
  13212. const storedData = storage.getValue(id, {
  13213. value: this.data.fieldValue
  13214. });
  13215. const selectElement = document.createElement("select");
  13216. GetElementsByNameSet.add(selectElement);
  13217. selectElement.setAttribute("data-element-id", id);
  13218. selectElement.disabled = this.data.readOnly;
  13219. this._setRequired(selectElement, this.data.required);
  13220. selectElement.name = this.data.fieldName;
  13221. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  13222. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  13223. if (!this.data.combo) {
  13224. selectElement.size = this.data.options.length;
  13225. if (this.data.multiSelect) {
  13226. selectElement.multiple = true;
  13227. }
  13228. }
  13229. selectElement.addEventListener("resetform", event => {
  13230. const defaultValue = this.data.defaultFieldValue;
  13231. for (const option of selectElement.options) {
  13232. option.selected = option.value === defaultValue;
  13233. }
  13234. });
  13235. for (const option of this.data.options) {
  13236. const optionElement = document.createElement("option");
  13237. optionElement.textContent = option.displayValue;
  13238. optionElement.value = option.exportValue;
  13239. if (storedData.value.includes(option.exportValue)) {
  13240. optionElement.setAttribute("selected", true);
  13241. addAnEmptyEntry = false;
  13242. }
  13243. selectElement.append(optionElement);
  13244. }
  13245. let removeEmptyEntry = null;
  13246. if (addAnEmptyEntry) {
  13247. const noneOptionElement = document.createElement("option");
  13248. noneOptionElement.value = " ";
  13249. noneOptionElement.setAttribute("hidden", true);
  13250. noneOptionElement.setAttribute("selected", true);
  13251. selectElement.prepend(noneOptionElement);
  13252. removeEmptyEntry = () => {
  13253. noneOptionElement.remove();
  13254. selectElement.removeEventListener("input", removeEmptyEntry);
  13255. removeEmptyEntry = null;
  13256. };
  13257. selectElement.addEventListener("input", removeEmptyEntry);
  13258. }
  13259. const getValue = isExport => {
  13260. const name = isExport ? "value" : "textContent";
  13261. const {
  13262. options,
  13263. multiple
  13264. } = selectElement;
  13265. if (!multiple) {
  13266. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  13267. }
  13268. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  13269. };
  13270. let selectedValues = getValue(false);
  13271. const getItems = event => {
  13272. const options = event.target.options;
  13273. return Array.prototype.map.call(options, option => {
  13274. return {
  13275. displayValue: option.textContent,
  13276. exportValue: option.value
  13277. };
  13278. });
  13279. };
  13280. if (this.enableScripting && this.hasJSActions) {
  13281. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  13282. const actions = {
  13283. value(event) {
  13284. removeEmptyEntry?.();
  13285. const value = event.detail.value;
  13286. const values = new Set(Array.isArray(value) ? value : [value]);
  13287. for (const option of selectElement.options) {
  13288. option.selected = values.has(option.value);
  13289. }
  13290. storage.setValue(id, {
  13291. value: getValue(true)
  13292. });
  13293. selectedValues = getValue(false);
  13294. },
  13295. multipleSelection(event) {
  13296. selectElement.multiple = true;
  13297. },
  13298. remove(event) {
  13299. const options = selectElement.options;
  13300. const index = event.detail.remove;
  13301. options[index].selected = false;
  13302. selectElement.remove(index);
  13303. if (options.length > 0) {
  13304. const i = Array.prototype.findIndex.call(options, option => option.selected);
  13305. if (i === -1) {
  13306. options[0].selected = true;
  13307. }
  13308. }
  13309. storage.setValue(id, {
  13310. value: getValue(true),
  13311. items: getItems(event)
  13312. });
  13313. selectedValues = getValue(false);
  13314. },
  13315. clear(event) {
  13316. while (selectElement.length !== 0) {
  13317. selectElement.remove(0);
  13318. }
  13319. storage.setValue(id, {
  13320. value: null,
  13321. items: []
  13322. });
  13323. selectedValues = getValue(false);
  13324. },
  13325. insert(event) {
  13326. const {
  13327. index,
  13328. displayValue,
  13329. exportValue
  13330. } = event.detail.insert;
  13331. const selectChild = selectElement.children[index];
  13332. const optionElement = document.createElement("option");
  13333. optionElement.textContent = displayValue;
  13334. optionElement.value = exportValue;
  13335. if (selectChild) {
  13336. selectChild.before(optionElement);
  13337. } else {
  13338. selectElement.append(optionElement);
  13339. }
  13340. storage.setValue(id, {
  13341. value: getValue(true),
  13342. items: getItems(event)
  13343. });
  13344. selectedValues = getValue(false);
  13345. },
  13346. items(event) {
  13347. const {
  13348. items
  13349. } = event.detail;
  13350. while (selectElement.length !== 0) {
  13351. selectElement.remove(0);
  13352. }
  13353. for (const item of items) {
  13354. const {
  13355. displayValue,
  13356. exportValue
  13357. } = item;
  13358. const optionElement = document.createElement("option");
  13359. optionElement.textContent = displayValue;
  13360. optionElement.value = exportValue;
  13361. selectElement.append(optionElement);
  13362. }
  13363. if (selectElement.options.length > 0) {
  13364. selectElement.options[0].selected = true;
  13365. }
  13366. storage.setValue(id, {
  13367. value: getValue(true),
  13368. items: getItems(event)
  13369. });
  13370. selectedValues = getValue(false);
  13371. },
  13372. indices(event) {
  13373. const indices = new Set(event.detail.indices);
  13374. for (const option of event.target.options) {
  13375. option.selected = indices.has(option.index);
  13376. }
  13377. storage.setValue(id, {
  13378. value: getValue(true)
  13379. });
  13380. selectedValues = getValue(false);
  13381. },
  13382. editable(event) {
  13383. event.target.disabled = !event.detail.editable;
  13384. }
  13385. };
  13386. this._dispatchEventFromSandbox(actions, jsEvent);
  13387. });
  13388. selectElement.addEventListener("input", event => {
  13389. const exportValue = getValue(true);
  13390. storage.setValue(id, {
  13391. value: exportValue
  13392. });
  13393. event.preventDefault();
  13394. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  13395. source: this,
  13396. detail: {
  13397. id,
  13398. name: "Keystroke",
  13399. value: selectedValues,
  13400. changeEx: exportValue,
  13401. willCommit: false,
  13402. commitKey: 1,
  13403. keyDown: false
  13404. }
  13405. });
  13406. });
  13407. this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
  13408. } else {
  13409. selectElement.addEventListener("input", function (event) {
  13410. storage.setValue(id, {
  13411. value: getValue(true)
  13412. });
  13413. });
  13414. }
  13415. if (this.data.combo) {
  13416. this._setTextStyle(selectElement);
  13417. } else {}
  13418. this._setBackgroundColor(selectElement);
  13419. this._setDefaultPropertiesFromJS(selectElement);
  13420. this.container.append(selectElement);
  13421. return this.container;
  13422. }
  13423. }
  13424. class PopupAnnotationElement extends AnnotationElement {
  13425. static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
  13426. constructor(parameters) {
  13427. const {
  13428. data
  13429. } = parameters;
  13430. const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
  13431. super(parameters, {
  13432. isRenderable
  13433. });
  13434. }
  13435. render() {
  13436. this.container.classList.add("popupAnnotation");
  13437. const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
  13438. if (parentElements.length === 0) {
  13439. return this.container;
  13440. }
  13441. const popup = new PopupElement({
  13442. container: this.container,
  13443. trigger: Array.from(parentElements),
  13444. color: this.data.color,
  13445. titleObj: this.data.titleObj,
  13446. modificationDate: this.data.modificationDate,
  13447. contentsObj: this.data.contentsObj,
  13448. richText: this.data.richText
  13449. });
  13450. const page = this.page;
  13451. 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]]);
  13452. const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
  13453. const popupTop = rect[1];
  13454. const {
  13455. pageWidth,
  13456. pageHeight,
  13457. pageX,
  13458. pageY
  13459. } = this.viewport.rawDims;
  13460. this.container.style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
  13461. this.container.style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
  13462. this.container.append(popup.render());
  13463. return this.container;
  13464. }
  13465. }
  13466. class PopupElement {
  13467. constructor(parameters) {
  13468. this.container = parameters.container;
  13469. this.trigger = parameters.trigger;
  13470. this.color = parameters.color;
  13471. this.titleObj = parameters.titleObj;
  13472. this.modificationDate = parameters.modificationDate;
  13473. this.contentsObj = parameters.contentsObj;
  13474. this.richText = parameters.richText;
  13475. this.hideWrapper = parameters.hideWrapper || false;
  13476. this.pinned = false;
  13477. }
  13478. render() {
  13479. const BACKGROUND_ENLIGHT = 0.7;
  13480. const wrapper = document.createElement("div");
  13481. wrapper.classList.add("popupWrapper");
  13482. this.hideElement = this.hideWrapper ? wrapper : this.container;
  13483. this.hideElement.hidden = true;
  13484. const popup = document.createElement("div");
  13485. popup.classList.add("popup");
  13486. const color = this.color;
  13487. if (color) {
  13488. const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  13489. const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  13490. const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  13491. popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
  13492. }
  13493. const title = document.createElement("h1");
  13494. title.dir = this.titleObj.dir;
  13495. title.textContent = this.titleObj.str;
  13496. popup.append(title);
  13497. const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
  13498. if (dateObject) {
  13499. const modificationDate = document.createElement("span");
  13500. modificationDate.classList.add("popupDate");
  13501. modificationDate.textContent = "{{date}}, {{time}}";
  13502. modificationDate.dataset.l10nId = "annotation_date_string";
  13503. modificationDate.dataset.l10nArgs = JSON.stringify({
  13504. date: dateObject.toLocaleDateString(),
  13505. time: dateObject.toLocaleTimeString()
  13506. });
  13507. popup.append(modificationDate);
  13508. }
  13509. if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
  13510. _xfa_layer.XfaLayer.render({
  13511. xfaHtml: this.richText.html,
  13512. intent: "richText",
  13513. div: popup
  13514. });
  13515. popup.lastChild.classList.add("richText", "popupContent");
  13516. } else {
  13517. const contents = this._formatContents(this.contentsObj);
  13518. popup.append(contents);
  13519. }
  13520. if (!Array.isArray(this.trigger)) {
  13521. this.trigger = [this.trigger];
  13522. }
  13523. for (const element of this.trigger) {
  13524. element.addEventListener("click", this._toggle.bind(this));
  13525. element.addEventListener("mouseover", this._show.bind(this, false));
  13526. element.addEventListener("mouseout", this._hide.bind(this, false));
  13527. }
  13528. popup.addEventListener("click", this._hide.bind(this, true));
  13529. wrapper.append(popup);
  13530. return wrapper;
  13531. }
  13532. _formatContents({
  13533. str,
  13534. dir
  13535. }) {
  13536. const p = document.createElement("p");
  13537. p.classList.add("popupContent");
  13538. p.dir = dir;
  13539. const lines = str.split(/(?:\r\n?|\n)/);
  13540. for (let i = 0, ii = lines.length; i < ii; ++i) {
  13541. const line = lines[i];
  13542. p.append(document.createTextNode(line));
  13543. if (i < ii - 1) {
  13544. p.append(document.createElement("br"));
  13545. }
  13546. }
  13547. return p;
  13548. }
  13549. _toggle() {
  13550. if (this.pinned) {
  13551. this._hide(true);
  13552. } else {
  13553. this._show(true);
  13554. }
  13555. }
  13556. _show(pin = false) {
  13557. if (pin) {
  13558. this.pinned = true;
  13559. }
  13560. if (this.hideElement.hidden) {
  13561. this.hideElement.hidden = false;
  13562. this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
  13563. }
  13564. }
  13565. _hide(unpin = true) {
  13566. if (unpin) {
  13567. this.pinned = false;
  13568. }
  13569. if (!this.hideElement.hidden && !this.pinned) {
  13570. this.hideElement.hidden = true;
  13571. this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
  13572. }
  13573. }
  13574. }
  13575. class FreeTextAnnotationElement extends AnnotationElement {
  13576. constructor(parameters) {
  13577. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13578. super(parameters, {
  13579. isRenderable,
  13580. ignoreBorder: true
  13581. });
  13582. this.textContent = parameters.data.textContent;
  13583. }
  13584. render() {
  13585. this.container.classList.add("freeTextAnnotation");
  13586. if (this.textContent) {
  13587. const content = document.createElement("div");
  13588. content.classList.add("annotationTextContent");
  13589. content.setAttribute("role", "comment");
  13590. for (const line of this.textContent) {
  13591. const lineSpan = document.createElement("span");
  13592. lineSpan.textContent = line;
  13593. content.append(lineSpan);
  13594. }
  13595. this.container.append(content);
  13596. }
  13597. if (!this.data.hasPopup) {
  13598. this._createPopup(null, this.data);
  13599. }
  13600. return this.container;
  13601. }
  13602. }
  13603. class LineAnnotationElement extends AnnotationElement {
  13604. constructor(parameters) {
  13605. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13606. super(parameters, {
  13607. isRenderable,
  13608. ignoreBorder: true
  13609. });
  13610. }
  13611. render() {
  13612. this.container.classList.add("lineAnnotation");
  13613. const data = this.data;
  13614. const {
  13615. width,
  13616. height
  13617. } = getRectDims(data.rect);
  13618. const svg = this.svgFactory.create(width, height, true);
  13619. const line = this.svgFactory.createElement("svg:line");
  13620. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  13621. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  13622. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  13623. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  13624. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  13625. line.setAttribute("stroke", "transparent");
  13626. line.setAttribute("fill", "transparent");
  13627. svg.append(line);
  13628. this.container.append(svg);
  13629. this._createPopup(line, data);
  13630. return this.container;
  13631. }
  13632. }
  13633. class SquareAnnotationElement extends AnnotationElement {
  13634. constructor(parameters) {
  13635. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13636. super(parameters, {
  13637. isRenderable,
  13638. ignoreBorder: true
  13639. });
  13640. }
  13641. render() {
  13642. this.container.classList.add("squareAnnotation");
  13643. const data = this.data;
  13644. const {
  13645. width,
  13646. height
  13647. } = getRectDims(data.rect);
  13648. const svg = this.svgFactory.create(width, height, true);
  13649. const borderWidth = data.borderStyle.width;
  13650. const square = this.svgFactory.createElement("svg:rect");
  13651. square.setAttribute("x", borderWidth / 2);
  13652. square.setAttribute("y", borderWidth / 2);
  13653. square.setAttribute("width", width - borderWidth);
  13654. square.setAttribute("height", height - borderWidth);
  13655. square.setAttribute("stroke-width", borderWidth || 1);
  13656. square.setAttribute("stroke", "transparent");
  13657. square.setAttribute("fill", "transparent");
  13658. svg.append(square);
  13659. this.container.append(svg);
  13660. this._createPopup(square, data);
  13661. return this.container;
  13662. }
  13663. }
  13664. class CircleAnnotationElement extends AnnotationElement {
  13665. constructor(parameters) {
  13666. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13667. super(parameters, {
  13668. isRenderable,
  13669. ignoreBorder: true
  13670. });
  13671. }
  13672. render() {
  13673. this.container.classList.add("circleAnnotation");
  13674. const data = this.data;
  13675. const {
  13676. width,
  13677. height
  13678. } = getRectDims(data.rect);
  13679. const svg = this.svgFactory.create(width, height, true);
  13680. const borderWidth = data.borderStyle.width;
  13681. const circle = this.svgFactory.createElement("svg:ellipse");
  13682. circle.setAttribute("cx", width / 2);
  13683. circle.setAttribute("cy", height / 2);
  13684. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  13685. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  13686. circle.setAttribute("stroke-width", borderWidth || 1);
  13687. circle.setAttribute("stroke", "transparent");
  13688. circle.setAttribute("fill", "transparent");
  13689. svg.append(circle);
  13690. this.container.append(svg);
  13691. this._createPopup(circle, data);
  13692. return this.container;
  13693. }
  13694. }
  13695. class PolylineAnnotationElement extends AnnotationElement {
  13696. constructor(parameters) {
  13697. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13698. super(parameters, {
  13699. isRenderable,
  13700. ignoreBorder: true
  13701. });
  13702. this.containerClassName = "polylineAnnotation";
  13703. this.svgElementName = "svg:polyline";
  13704. }
  13705. render() {
  13706. this.container.classList.add(this.containerClassName);
  13707. const data = this.data;
  13708. const {
  13709. width,
  13710. height
  13711. } = getRectDims(data.rect);
  13712. const svg = this.svgFactory.create(width, height, true);
  13713. let points = [];
  13714. for (const coordinate of data.vertices) {
  13715. const x = coordinate.x - data.rect[0];
  13716. const y = data.rect[3] - coordinate.y;
  13717. points.push(x + "," + y);
  13718. }
  13719. points = points.join(" ");
  13720. const polyline = this.svgFactory.createElement(this.svgElementName);
  13721. polyline.setAttribute("points", points);
  13722. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  13723. polyline.setAttribute("stroke", "transparent");
  13724. polyline.setAttribute("fill", "transparent");
  13725. svg.append(polyline);
  13726. this.container.append(svg);
  13727. this._createPopup(polyline, data);
  13728. return this.container;
  13729. }
  13730. }
  13731. class PolygonAnnotationElement extends PolylineAnnotationElement {
  13732. constructor(parameters) {
  13733. super(parameters);
  13734. this.containerClassName = "polygonAnnotation";
  13735. this.svgElementName = "svg:polygon";
  13736. }
  13737. }
  13738. class CaretAnnotationElement extends AnnotationElement {
  13739. constructor(parameters) {
  13740. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13741. super(parameters, {
  13742. isRenderable,
  13743. ignoreBorder: true
  13744. });
  13745. }
  13746. render() {
  13747. this.container.classList.add("caretAnnotation");
  13748. if (!this.data.hasPopup) {
  13749. this._createPopup(null, this.data);
  13750. }
  13751. return this.container;
  13752. }
  13753. }
  13754. class InkAnnotationElement extends AnnotationElement {
  13755. constructor(parameters) {
  13756. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13757. super(parameters, {
  13758. isRenderable,
  13759. ignoreBorder: true
  13760. });
  13761. this.containerClassName = "inkAnnotation";
  13762. this.svgElementName = "svg:polyline";
  13763. }
  13764. render() {
  13765. this.container.classList.add(this.containerClassName);
  13766. const data = this.data;
  13767. const {
  13768. width,
  13769. height
  13770. } = getRectDims(data.rect);
  13771. const svg = this.svgFactory.create(width, height, true);
  13772. for (const inkList of data.inkLists) {
  13773. let points = [];
  13774. for (const coordinate of inkList) {
  13775. const x = coordinate.x - data.rect[0];
  13776. const y = data.rect[3] - coordinate.y;
  13777. points.push(`${x},${y}`);
  13778. }
  13779. points = points.join(" ");
  13780. const polyline = this.svgFactory.createElement(this.svgElementName);
  13781. polyline.setAttribute("points", points);
  13782. polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
  13783. polyline.setAttribute("stroke", "transparent");
  13784. polyline.setAttribute("fill", "transparent");
  13785. this._createPopup(polyline, data);
  13786. svg.append(polyline);
  13787. }
  13788. this.container.append(svg);
  13789. return this.container;
  13790. }
  13791. }
  13792. class HighlightAnnotationElement extends AnnotationElement {
  13793. constructor(parameters) {
  13794. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13795. super(parameters, {
  13796. isRenderable,
  13797. ignoreBorder: true,
  13798. createQuadrilaterals: true
  13799. });
  13800. }
  13801. render() {
  13802. if (!this.data.hasPopup) {
  13803. this._createPopup(null, this.data);
  13804. }
  13805. if (this.quadrilaterals) {
  13806. return this._renderQuadrilaterals("highlightAnnotation");
  13807. }
  13808. this.container.classList.add("highlightAnnotation");
  13809. return this.container;
  13810. }
  13811. }
  13812. class UnderlineAnnotationElement extends AnnotationElement {
  13813. constructor(parameters) {
  13814. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13815. super(parameters, {
  13816. isRenderable,
  13817. ignoreBorder: true,
  13818. createQuadrilaterals: true
  13819. });
  13820. }
  13821. render() {
  13822. if (!this.data.hasPopup) {
  13823. this._createPopup(null, this.data);
  13824. }
  13825. if (this.quadrilaterals) {
  13826. return this._renderQuadrilaterals("underlineAnnotation");
  13827. }
  13828. this.container.classList.add("underlineAnnotation");
  13829. return this.container;
  13830. }
  13831. }
  13832. class SquigglyAnnotationElement extends AnnotationElement {
  13833. constructor(parameters) {
  13834. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13835. super(parameters, {
  13836. isRenderable,
  13837. ignoreBorder: true,
  13838. createQuadrilaterals: true
  13839. });
  13840. }
  13841. render() {
  13842. if (!this.data.hasPopup) {
  13843. this._createPopup(null, this.data);
  13844. }
  13845. if (this.quadrilaterals) {
  13846. return this._renderQuadrilaterals("squigglyAnnotation");
  13847. }
  13848. this.container.classList.add("squigglyAnnotation");
  13849. return this.container;
  13850. }
  13851. }
  13852. class StrikeOutAnnotationElement extends AnnotationElement {
  13853. constructor(parameters) {
  13854. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13855. super(parameters, {
  13856. isRenderable,
  13857. ignoreBorder: true,
  13858. createQuadrilaterals: true
  13859. });
  13860. }
  13861. render() {
  13862. if (!this.data.hasPopup) {
  13863. this._createPopup(null, this.data);
  13864. }
  13865. if (this.quadrilaterals) {
  13866. return this._renderQuadrilaterals("strikeoutAnnotation");
  13867. }
  13868. this.container.classList.add("strikeoutAnnotation");
  13869. return this.container;
  13870. }
  13871. }
  13872. class StampAnnotationElement extends AnnotationElement {
  13873. constructor(parameters) {
  13874. const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
  13875. super(parameters, {
  13876. isRenderable,
  13877. ignoreBorder: true
  13878. });
  13879. }
  13880. render() {
  13881. this.container.classList.add("stampAnnotation");
  13882. if (!this.data.hasPopup) {
  13883. this._createPopup(null, this.data);
  13884. }
  13885. return this.container;
  13886. }
  13887. }
  13888. class FileAttachmentAnnotationElement extends AnnotationElement {
  13889. constructor(parameters) {
  13890. super(parameters, {
  13891. isRenderable: true
  13892. });
  13893. const {
  13894. filename,
  13895. content
  13896. } = this.data.file;
  13897. this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
  13898. this.content = content;
  13899. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  13900. source: this,
  13901. filename,
  13902. content
  13903. });
  13904. }
  13905. render() {
  13906. this.container.classList.add("fileAttachmentAnnotation");
  13907. let trigger;
  13908. if (this.data.hasAppearance) {
  13909. trigger = document.createElement("div");
  13910. } else {
  13911. trigger = document.createElement("img");
  13912. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"}.svg`;
  13913. }
  13914. trigger.classList.add("popupTriggerArea");
  13915. trigger.addEventListener("dblclick", this._download.bind(this));
  13916. if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
  13917. this._createPopup(trigger, this.data);
  13918. }
  13919. this.container.append(trigger);
  13920. return this.container;
  13921. }
  13922. _download() {
  13923. this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  13924. }
  13925. }
  13926. class AnnotationLayer {
  13927. static #appendElement(element, id, div, accessibilityManager) {
  13928. const contentElement = element.firstChild || element;
  13929. contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
  13930. div.append(element);
  13931. accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
  13932. }
  13933. static render(params) {
  13934. const {
  13935. annotations,
  13936. div,
  13937. viewport,
  13938. accessibilityManager
  13939. } = params;
  13940. (0, _display_utils.setLayerDimensions)(div, viewport);
  13941. const elementParams = {
  13942. data: null,
  13943. layer: div,
  13944. page: params.page,
  13945. viewport,
  13946. linkService: params.linkService,
  13947. downloadManager: params.downloadManager,
  13948. imageResourcesPath: params.imageResourcesPath || "",
  13949. renderForms: params.renderForms !== false,
  13950. svgFactory: new _display_utils.DOMSVGFactory(),
  13951. annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
  13952. enableScripting: params.enableScripting === true,
  13953. hasJSActions: params.hasJSActions,
  13954. fieldObjects: params.fieldObjects
  13955. };
  13956. let zIndex = 0;
  13957. for (const data of annotations) {
  13958. if (data.noHTML) {
  13959. continue;
  13960. }
  13961. if (data.annotationType !== _util.AnnotationType.POPUP) {
  13962. const {
  13963. width,
  13964. height
  13965. } = getRectDims(data.rect);
  13966. if (width <= 0 || height <= 0) {
  13967. continue;
  13968. }
  13969. }
  13970. elementParams.data = data;
  13971. const element = AnnotationElementFactory.create(elementParams);
  13972. if (!element.isRenderable) {
  13973. continue;
  13974. }
  13975. const rendered = element.render();
  13976. if (data.hidden) {
  13977. rendered.style.visibility = "hidden";
  13978. }
  13979. if (Array.isArray(rendered)) {
  13980. for (const renderedElement of rendered) {
  13981. renderedElement.style.zIndex = zIndex++;
  13982. AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
  13983. }
  13984. } else {
  13985. rendered.style.zIndex = zIndex++;
  13986. if (element instanceof PopupAnnotationElement) {
  13987. div.prepend(rendered);
  13988. } else {
  13989. AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
  13990. }
  13991. }
  13992. }
  13993. this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
  13994. }
  13995. static update(params) {
  13996. const {
  13997. annotationCanvasMap,
  13998. div,
  13999. viewport
  14000. } = params;
  14001. (0, _display_utils.setLayerDimensions)(div, {
  14002. rotation: viewport.rotation
  14003. });
  14004. this.#setAnnotationCanvasMap(div, annotationCanvasMap);
  14005. div.hidden = false;
  14006. }
  14007. static #setAnnotationCanvasMap(div, annotationCanvasMap) {
  14008. if (!annotationCanvasMap) {
  14009. return;
  14010. }
  14011. for (const [id, canvas] of annotationCanvasMap) {
  14012. const element = div.querySelector(`[data-annotation-id="${id}"]`);
  14013. if (!element) {
  14014. continue;
  14015. }
  14016. const {
  14017. firstChild
  14018. } = element;
  14019. if (!firstChild) {
  14020. element.append(canvas);
  14021. } else if (firstChild.nodeName === "CANVAS") {
  14022. firstChild.replaceWith(canvas);
  14023. } else {
  14024. firstChild.before(canvas);
  14025. }
  14026. }
  14027. annotationCanvasMap.clear();
  14028. }
  14029. }
  14030. exports.AnnotationLayer = AnnotationLayer;
  14031. /***/ }),
  14032. /* 33 */
  14033. /***/ ((__unused_webpack_module, exports) => {
  14034. Object.defineProperty(exports, "__esModule", ({
  14035. value: true
  14036. }));
  14037. exports.ColorConverters = void 0;
  14038. function makeColorComp(n) {
  14039. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  14040. }
  14041. class ColorConverters {
  14042. static CMYK_G([c, y, m, k]) {
  14043. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  14044. }
  14045. static G_CMYK([g]) {
  14046. return ["CMYK", 0, 0, 0, 1 - g];
  14047. }
  14048. static G_RGB([g]) {
  14049. return ["RGB", g, g, g];
  14050. }
  14051. static G_HTML([g]) {
  14052. const G = makeColorComp(g);
  14053. return `#${G}${G}${G}`;
  14054. }
  14055. static RGB_G([r, g, b]) {
  14056. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  14057. }
  14058. static RGB_HTML([r, g, b]) {
  14059. const R = makeColorComp(r);
  14060. const G = makeColorComp(g);
  14061. const B = makeColorComp(b);
  14062. return `#${R}${G}${B}`;
  14063. }
  14064. static T_HTML() {
  14065. return "#00000000";
  14066. }
  14067. static CMYK_RGB([c, y, m, k]) {
  14068. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  14069. }
  14070. static CMYK_HTML(components) {
  14071. const rgb = this.CMYK_RGB(components).slice(1);
  14072. return this.RGB_HTML(rgb);
  14073. }
  14074. static RGB_CMYK([r, g, b]) {
  14075. const c = 1 - r;
  14076. const m = 1 - g;
  14077. const y = 1 - b;
  14078. const k = Math.min(c, m, y);
  14079. return ["CMYK", c, m, y, k];
  14080. }
  14081. }
  14082. exports.ColorConverters = ColorConverters;
  14083. /***/ }),
  14084. /* 34 */
  14085. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14086. Object.defineProperty(exports, "__esModule", ({
  14087. value: true
  14088. }));
  14089. exports.XfaLayer = void 0;
  14090. var _xfa_text = __w_pdfjs_require__(19);
  14091. class XfaLayer {
  14092. static setupStorage(html, id, element, storage, intent) {
  14093. const storedData = storage.getValue(id, {
  14094. value: null
  14095. });
  14096. switch (element.name) {
  14097. case "textarea":
  14098. if (storedData.value !== null) {
  14099. html.textContent = storedData.value;
  14100. }
  14101. if (intent === "print") {
  14102. break;
  14103. }
  14104. html.addEventListener("input", event => {
  14105. storage.setValue(id, {
  14106. value: event.target.value
  14107. });
  14108. });
  14109. break;
  14110. case "input":
  14111. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  14112. if (storedData.value === element.attributes.xfaOn) {
  14113. html.setAttribute("checked", true);
  14114. } else if (storedData.value === element.attributes.xfaOff) {
  14115. html.removeAttribute("checked");
  14116. }
  14117. if (intent === "print") {
  14118. break;
  14119. }
  14120. html.addEventListener("change", event => {
  14121. storage.setValue(id, {
  14122. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  14123. });
  14124. });
  14125. } else {
  14126. if (storedData.value !== null) {
  14127. html.setAttribute("value", storedData.value);
  14128. }
  14129. if (intent === "print") {
  14130. break;
  14131. }
  14132. html.addEventListener("input", event => {
  14133. storage.setValue(id, {
  14134. value: event.target.value
  14135. });
  14136. });
  14137. }
  14138. break;
  14139. case "select":
  14140. if (storedData.value !== null) {
  14141. for (const option of element.children) {
  14142. if (option.attributes.value === storedData.value) {
  14143. option.attributes.selected = true;
  14144. }
  14145. }
  14146. }
  14147. html.addEventListener("input", event => {
  14148. const options = event.target.options;
  14149. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  14150. storage.setValue(id, {
  14151. value
  14152. });
  14153. });
  14154. break;
  14155. }
  14156. }
  14157. static setAttributes({
  14158. html,
  14159. element,
  14160. storage = null,
  14161. intent,
  14162. linkService
  14163. }) {
  14164. const {
  14165. attributes
  14166. } = element;
  14167. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  14168. if (attributes.type === "radio") {
  14169. attributes.name = `${attributes.name}-${intent}`;
  14170. }
  14171. for (const [key, value] of Object.entries(attributes)) {
  14172. if (value === null || value === undefined) {
  14173. continue;
  14174. }
  14175. switch (key) {
  14176. case "class":
  14177. if (value.length) {
  14178. html.setAttribute(key, value.join(" "));
  14179. }
  14180. break;
  14181. case "dataId":
  14182. break;
  14183. case "id":
  14184. html.setAttribute("data-element-id", value);
  14185. break;
  14186. case "style":
  14187. Object.assign(html.style, value);
  14188. break;
  14189. case "textContent":
  14190. html.textContent = value;
  14191. break;
  14192. default:
  14193. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  14194. html.setAttribute(key, value);
  14195. }
  14196. }
  14197. }
  14198. if (isHTMLAnchorElement) {
  14199. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  14200. }
  14201. if (storage && attributes.dataId) {
  14202. this.setupStorage(html, attributes.dataId, element, storage);
  14203. }
  14204. }
  14205. static render(parameters) {
  14206. const storage = parameters.annotationStorage;
  14207. const linkService = parameters.linkService;
  14208. const root = parameters.xfaHtml;
  14209. const intent = parameters.intent || "display";
  14210. const rootHtml = document.createElement(root.name);
  14211. if (root.attributes) {
  14212. this.setAttributes({
  14213. html: rootHtml,
  14214. element: root,
  14215. intent,
  14216. linkService
  14217. });
  14218. }
  14219. const stack = [[root, -1, rootHtml]];
  14220. const rootDiv = parameters.div;
  14221. rootDiv.append(rootHtml);
  14222. if (parameters.viewport) {
  14223. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  14224. rootDiv.style.transform = transform;
  14225. }
  14226. if (intent !== "richText") {
  14227. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  14228. }
  14229. const textDivs = [];
  14230. while (stack.length > 0) {
  14231. const [parent, i, html] = stack.at(-1);
  14232. if (i + 1 === parent.children.length) {
  14233. stack.pop();
  14234. continue;
  14235. }
  14236. const child = parent.children[++stack.at(-1)[1]];
  14237. if (child === null) {
  14238. continue;
  14239. }
  14240. const {
  14241. name
  14242. } = child;
  14243. if (name === "#text") {
  14244. const node = document.createTextNode(child.value);
  14245. textDivs.push(node);
  14246. html.append(node);
  14247. continue;
  14248. }
  14249. let childHtml;
  14250. if (child?.attributes?.xmlns) {
  14251. childHtml = document.createElementNS(child.attributes.xmlns, name);
  14252. } else {
  14253. childHtml = document.createElement(name);
  14254. }
  14255. html.append(childHtml);
  14256. if (child.attributes) {
  14257. this.setAttributes({
  14258. html: childHtml,
  14259. element: child,
  14260. storage,
  14261. intent,
  14262. linkService
  14263. });
  14264. }
  14265. if (child.children && child.children.length > 0) {
  14266. stack.push([child, -1, childHtml]);
  14267. } else if (child.value) {
  14268. const node = document.createTextNode(child.value);
  14269. if (_xfa_text.XfaText.shouldBuildText(name)) {
  14270. textDivs.push(node);
  14271. }
  14272. childHtml.append(node);
  14273. }
  14274. }
  14275. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  14276. el.setAttribute("readOnly", true);
  14277. }
  14278. return {
  14279. textDivs
  14280. };
  14281. }
  14282. static update(parameters) {
  14283. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  14284. parameters.div.style.transform = transform;
  14285. parameters.div.hidden = false;
  14286. }
  14287. }
  14288. exports.XfaLayer = XfaLayer;
  14289. /***/ }),
  14290. /* 35 */
  14291. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  14292. Object.defineProperty(exports, "__esModule", ({
  14293. value: true
  14294. }));
  14295. exports.SVGGraphics = void 0;
  14296. var _display_utils = __w_pdfjs_require__(6);
  14297. var _util = __w_pdfjs_require__(1);
  14298. var _is_node = __w_pdfjs_require__(10);
  14299. let SVGGraphics = class {
  14300. constructor() {
  14301. (0, _util.unreachable)("Not implemented: SVGGraphics");
  14302. }
  14303. };
  14304. exports.SVGGraphics = SVGGraphics;
  14305. {
  14306. const SVG_DEFAULTS = {
  14307. fontStyle: "normal",
  14308. fontWeight: "normal",
  14309. fillColor: "#000000"
  14310. };
  14311. const XML_NS = "http://www.w3.org/XML/1998/namespace";
  14312. const XLINK_NS = "http://www.w3.org/1999/xlink";
  14313. const LINE_CAP_STYLES = ["butt", "round", "square"];
  14314. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  14315. const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
  14316. if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
  14317. return URL.createObjectURL(new Blob([data], {
  14318. type: contentType
  14319. }));
  14320. }
  14321. const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  14322. let buffer = `data:${contentType};base64,`;
  14323. for (let i = 0, ii = data.length; i < ii; i += 3) {
  14324. const b1 = data[i] & 0xff;
  14325. const b2 = data[i + 1] & 0xff;
  14326. const b3 = data[i + 2] & 0xff;
  14327. const d1 = b1 >> 2,
  14328. d2 = (b1 & 3) << 4 | b2 >> 4;
  14329. const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
  14330. const d4 = i + 2 < ii ? b3 & 0x3f : 64;
  14331. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  14332. }
  14333. return buffer;
  14334. };
  14335. const convertImgDataToPng = function () {
  14336. const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  14337. const CHUNK_WRAPPER_SIZE = 12;
  14338. const crcTable = new Int32Array(256);
  14339. for (let i = 0; i < 256; i++) {
  14340. let c = i;
  14341. for (let h = 0; h < 8; h++) {
  14342. if (c & 1) {
  14343. c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
  14344. } else {
  14345. c = c >> 1 & 0x7fffffff;
  14346. }
  14347. }
  14348. crcTable[i] = c;
  14349. }
  14350. function crc32(data, start, end) {
  14351. let crc = -1;
  14352. for (let i = start; i < end; i++) {
  14353. const a = (crc ^ data[i]) & 0xff;
  14354. const b = crcTable[a];
  14355. crc = crc >>> 8 ^ b;
  14356. }
  14357. return crc ^ -1;
  14358. }
  14359. function writePngChunk(type, body, data, offset) {
  14360. let p = offset;
  14361. const len = body.length;
  14362. data[p] = len >> 24 & 0xff;
  14363. data[p + 1] = len >> 16 & 0xff;
  14364. data[p + 2] = len >> 8 & 0xff;
  14365. data[p + 3] = len & 0xff;
  14366. p += 4;
  14367. data[p] = type.charCodeAt(0) & 0xff;
  14368. data[p + 1] = type.charCodeAt(1) & 0xff;
  14369. data[p + 2] = type.charCodeAt(2) & 0xff;
  14370. data[p + 3] = type.charCodeAt(3) & 0xff;
  14371. p += 4;
  14372. data.set(body, p);
  14373. p += body.length;
  14374. const crc = crc32(data, offset + 4, p);
  14375. data[p] = crc >> 24 & 0xff;
  14376. data[p + 1] = crc >> 16 & 0xff;
  14377. data[p + 2] = crc >> 8 & 0xff;
  14378. data[p + 3] = crc & 0xff;
  14379. }
  14380. function adler32(data, start, end) {
  14381. let a = 1;
  14382. let b = 0;
  14383. for (let i = start; i < end; ++i) {
  14384. a = (a + (data[i] & 0xff)) % 65521;
  14385. b = (b + a) % 65521;
  14386. }
  14387. return b << 16 | a;
  14388. }
  14389. function deflateSync(literals) {
  14390. if (!_is_node.isNodeJS) {
  14391. return deflateSyncUncompressed(literals);
  14392. }
  14393. try {
  14394. let input;
  14395. if (parseInt(process.versions.node) >= 8) {
  14396. input = literals;
  14397. } else {
  14398. input = Buffer.from(literals);
  14399. }
  14400. const output = require("zlib").deflateSync(input, {
  14401. level: 9
  14402. });
  14403. return output instanceof Uint8Array ? output : new Uint8Array(output);
  14404. } catch (e) {
  14405. (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
  14406. }
  14407. return deflateSyncUncompressed(literals);
  14408. }
  14409. function deflateSyncUncompressed(literals) {
  14410. let len = literals.length;
  14411. const maxBlockLength = 0xffff;
  14412. const deflateBlocks = Math.ceil(len / maxBlockLength);
  14413. const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  14414. let pi = 0;
  14415. idat[pi++] = 0x78;
  14416. idat[pi++] = 0x9c;
  14417. let pos = 0;
  14418. while (len > maxBlockLength) {
  14419. idat[pi++] = 0x00;
  14420. idat[pi++] = 0xff;
  14421. idat[pi++] = 0xff;
  14422. idat[pi++] = 0x00;
  14423. idat[pi++] = 0x00;
  14424. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  14425. pi += maxBlockLength;
  14426. pos += maxBlockLength;
  14427. len -= maxBlockLength;
  14428. }
  14429. idat[pi++] = 0x01;
  14430. idat[pi++] = len & 0xff;
  14431. idat[pi++] = len >> 8 & 0xff;
  14432. idat[pi++] = ~len & 0xffff & 0xff;
  14433. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  14434. idat.set(literals.subarray(pos), pi);
  14435. pi += literals.length - pos;
  14436. const adler = adler32(literals, 0, literals.length);
  14437. idat[pi++] = adler >> 24 & 0xff;
  14438. idat[pi++] = adler >> 16 & 0xff;
  14439. idat[pi++] = adler >> 8 & 0xff;
  14440. idat[pi++] = adler & 0xff;
  14441. return idat;
  14442. }
  14443. function encode(imgData, kind, forceDataSchema, isMask) {
  14444. const width = imgData.width;
  14445. const height = imgData.height;
  14446. let bitDepth, colorType, lineSize;
  14447. const bytes = imgData.data;
  14448. switch (kind) {
  14449. case _util.ImageKind.GRAYSCALE_1BPP:
  14450. colorType = 0;
  14451. bitDepth = 1;
  14452. lineSize = width + 7 >> 3;
  14453. break;
  14454. case _util.ImageKind.RGB_24BPP:
  14455. colorType = 2;
  14456. bitDepth = 8;
  14457. lineSize = width * 3;
  14458. break;
  14459. case _util.ImageKind.RGBA_32BPP:
  14460. colorType = 6;
  14461. bitDepth = 8;
  14462. lineSize = width * 4;
  14463. break;
  14464. default:
  14465. throw new Error("invalid format");
  14466. }
  14467. const literals = new Uint8Array((1 + lineSize) * height);
  14468. let offsetLiterals = 0,
  14469. offsetBytes = 0;
  14470. for (let y = 0; y < height; ++y) {
  14471. literals[offsetLiterals++] = 0;
  14472. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  14473. offsetBytes += lineSize;
  14474. offsetLiterals += lineSize;
  14475. }
  14476. if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
  14477. offsetLiterals = 0;
  14478. for (let y = 0; y < height; y++) {
  14479. offsetLiterals++;
  14480. for (let i = 0; i < lineSize; i++) {
  14481. literals[offsetLiterals++] ^= 0xff;
  14482. }
  14483. }
  14484. }
  14485. 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]);
  14486. const idat = deflateSync(literals);
  14487. const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  14488. const data = new Uint8Array(pngLength);
  14489. let offset = 0;
  14490. data.set(PNG_HEADER, offset);
  14491. offset += PNG_HEADER.length;
  14492. writePngChunk("IHDR", ihdr, data, offset);
  14493. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  14494. writePngChunk("IDATA", idat, data, offset);
  14495. offset += CHUNK_WRAPPER_SIZE + idat.length;
  14496. writePngChunk("IEND", new Uint8Array(0), data, offset);
  14497. return createObjectURL(data, "image/png", forceDataSchema);
  14498. }
  14499. return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
  14500. const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
  14501. return encode(imgData, kind, forceDataSchema, isMask);
  14502. };
  14503. }();
  14504. class SVGExtraState {
  14505. constructor() {
  14506. this.fontSizeScale = 1;
  14507. this.fontWeight = SVG_DEFAULTS.fontWeight;
  14508. this.fontSize = 0;
  14509. this.textMatrix = _util.IDENTITY_MATRIX;
  14510. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  14511. this.leading = 0;
  14512. this.textRenderingMode = _util.TextRenderingMode.FILL;
  14513. this.textMatrixScale = 1;
  14514. this.x = 0;
  14515. this.y = 0;
  14516. this.lineX = 0;
  14517. this.lineY = 0;
  14518. this.charSpacing = 0;
  14519. this.wordSpacing = 0;
  14520. this.textHScale = 1;
  14521. this.textRise = 0;
  14522. this.fillColor = SVG_DEFAULTS.fillColor;
  14523. this.strokeColor = "#000000";
  14524. this.fillAlpha = 1;
  14525. this.strokeAlpha = 1;
  14526. this.lineWidth = 1;
  14527. this.lineJoin = "";
  14528. this.lineCap = "";
  14529. this.miterLimit = 0;
  14530. this.dashArray = [];
  14531. this.dashPhase = 0;
  14532. this.dependencies = [];
  14533. this.activeClipUrl = null;
  14534. this.clipGroup = null;
  14535. this.maskId = "";
  14536. }
  14537. clone() {
  14538. return Object.create(this);
  14539. }
  14540. setCurrentPoint(x, y) {
  14541. this.x = x;
  14542. this.y = y;
  14543. }
  14544. }
  14545. function opListToTree(opList) {
  14546. let opTree = [];
  14547. const tmp = [];
  14548. for (const opListElement of opList) {
  14549. if (opListElement.fn === "save") {
  14550. opTree.push({
  14551. fnId: 92,
  14552. fn: "group",
  14553. items: []
  14554. });
  14555. tmp.push(opTree);
  14556. opTree = opTree.at(-1).items;
  14557. continue;
  14558. }
  14559. if (opListElement.fn === "restore") {
  14560. opTree = tmp.pop();
  14561. } else {
  14562. opTree.push(opListElement);
  14563. }
  14564. }
  14565. return opTree;
  14566. }
  14567. function pf(value) {
  14568. if (Number.isInteger(value)) {
  14569. return value.toString();
  14570. }
  14571. const s = value.toFixed(10);
  14572. let i = s.length - 1;
  14573. if (s[i] !== "0") {
  14574. return s;
  14575. }
  14576. do {
  14577. i--;
  14578. } while (s[i] === "0");
  14579. return s.substring(0, s[i] === "." ? i : i + 1);
  14580. }
  14581. function pm(m) {
  14582. if (m[4] === 0 && m[5] === 0) {
  14583. if (m[1] === 0 && m[2] === 0) {
  14584. if (m[0] === 1 && m[3] === 1) {
  14585. return "";
  14586. }
  14587. return `scale(${pf(m[0])} ${pf(m[3])})`;
  14588. }
  14589. if (m[0] === m[3] && m[1] === -m[2]) {
  14590. const a = Math.acos(m[0]) * 180 / Math.PI;
  14591. return `rotate(${pf(a)})`;
  14592. }
  14593. } else {
  14594. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  14595. return `translate(${pf(m[4])} ${pf(m[5])})`;
  14596. }
  14597. }
  14598. return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  14599. }
  14600. let clipCount = 0;
  14601. let maskCount = 0;
  14602. let shadingCount = 0;
  14603. exports.SVGGraphics = SVGGraphics = class {
  14604. constructor(commonObjs, objs, forceDataSchema = false) {
  14605. (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
  14606. this.svgFactory = new _display_utils.DOMSVGFactory();
  14607. this.current = new SVGExtraState();
  14608. this.transformMatrix = _util.IDENTITY_MATRIX;
  14609. this.transformStack = [];
  14610. this.extraStack = [];
  14611. this.commonObjs = commonObjs;
  14612. this.objs = objs;
  14613. this.pendingClip = null;
  14614. this.pendingEOFill = false;
  14615. this.embedFonts = false;
  14616. this.embeddedFonts = Object.create(null);
  14617. this.cssStyle = null;
  14618. this.forceDataSchema = !!forceDataSchema;
  14619. this._operatorIdMapping = [];
  14620. for (const op in _util.OPS) {
  14621. this._operatorIdMapping[_util.OPS[op]] = op;
  14622. }
  14623. }
  14624. getObject(data, fallback = null) {
  14625. if (typeof data === "string") {
  14626. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  14627. }
  14628. return fallback;
  14629. }
  14630. save() {
  14631. this.transformStack.push(this.transformMatrix);
  14632. const old = this.current;
  14633. this.extraStack.push(old);
  14634. this.current = old.clone();
  14635. }
  14636. restore() {
  14637. this.transformMatrix = this.transformStack.pop();
  14638. this.current = this.extraStack.pop();
  14639. this.pendingClip = null;
  14640. this.tgrp = null;
  14641. }
  14642. group(items) {
  14643. this.save();
  14644. this.executeOpTree(items);
  14645. this.restore();
  14646. }
  14647. loadDependencies(operatorList) {
  14648. const fnArray = operatorList.fnArray;
  14649. const argsArray = operatorList.argsArray;
  14650. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  14651. if (fnArray[i] !== _util.OPS.dependency) {
  14652. continue;
  14653. }
  14654. for (const obj of argsArray[i]) {
  14655. const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
  14656. const promise = new Promise(resolve => {
  14657. objsPool.get(obj, resolve);
  14658. });
  14659. this.current.dependencies.push(promise);
  14660. }
  14661. }
  14662. return Promise.all(this.current.dependencies);
  14663. }
  14664. transform(a, b, c, d, e, f) {
  14665. const transformMatrix = [a, b, c, d, e, f];
  14666. this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
  14667. this.tgrp = null;
  14668. }
  14669. getSVG(operatorList, viewport) {
  14670. this.viewport = viewport;
  14671. const svgElement = this._initialize(viewport);
  14672. return this.loadDependencies(operatorList).then(() => {
  14673. this.transformMatrix = _util.IDENTITY_MATRIX;
  14674. this.executeOpTree(this.convertOpList(operatorList));
  14675. return svgElement;
  14676. });
  14677. }
  14678. convertOpList(operatorList) {
  14679. const operatorIdMapping = this._operatorIdMapping;
  14680. const argsArray = operatorList.argsArray;
  14681. const fnArray = operatorList.fnArray;
  14682. const opList = [];
  14683. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  14684. const fnId = fnArray[i];
  14685. opList.push({
  14686. fnId,
  14687. fn: operatorIdMapping[fnId],
  14688. args: argsArray[i]
  14689. });
  14690. }
  14691. return opListToTree(opList);
  14692. }
  14693. executeOpTree(opTree) {
  14694. for (const opTreeElement of opTree) {
  14695. const fn = opTreeElement.fn;
  14696. const fnId = opTreeElement.fnId;
  14697. const args = opTreeElement.args;
  14698. switch (fnId | 0) {
  14699. case _util.OPS.beginText:
  14700. this.beginText();
  14701. break;
  14702. case _util.OPS.dependency:
  14703. break;
  14704. case _util.OPS.setLeading:
  14705. this.setLeading(args);
  14706. break;
  14707. case _util.OPS.setLeadingMoveText:
  14708. this.setLeadingMoveText(args[0], args[1]);
  14709. break;
  14710. case _util.OPS.setFont:
  14711. this.setFont(args);
  14712. break;
  14713. case _util.OPS.showText:
  14714. this.showText(args[0]);
  14715. break;
  14716. case _util.OPS.showSpacedText:
  14717. this.showText(args[0]);
  14718. break;
  14719. case _util.OPS.endText:
  14720. this.endText();
  14721. break;
  14722. case _util.OPS.moveText:
  14723. this.moveText(args[0], args[1]);
  14724. break;
  14725. case _util.OPS.setCharSpacing:
  14726. this.setCharSpacing(args[0]);
  14727. break;
  14728. case _util.OPS.setWordSpacing:
  14729. this.setWordSpacing(args[0]);
  14730. break;
  14731. case _util.OPS.setHScale:
  14732. this.setHScale(args[0]);
  14733. break;
  14734. case _util.OPS.setTextMatrix:
  14735. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  14736. break;
  14737. case _util.OPS.setTextRise:
  14738. this.setTextRise(args[0]);
  14739. break;
  14740. case _util.OPS.setTextRenderingMode:
  14741. this.setTextRenderingMode(args[0]);
  14742. break;
  14743. case _util.OPS.setLineWidth:
  14744. this.setLineWidth(args[0]);
  14745. break;
  14746. case _util.OPS.setLineJoin:
  14747. this.setLineJoin(args[0]);
  14748. break;
  14749. case _util.OPS.setLineCap:
  14750. this.setLineCap(args[0]);
  14751. break;
  14752. case _util.OPS.setMiterLimit:
  14753. this.setMiterLimit(args[0]);
  14754. break;
  14755. case _util.OPS.setFillRGBColor:
  14756. this.setFillRGBColor(args[0], args[1], args[2]);
  14757. break;
  14758. case _util.OPS.setStrokeRGBColor:
  14759. this.setStrokeRGBColor(args[0], args[1], args[2]);
  14760. break;
  14761. case _util.OPS.setStrokeColorN:
  14762. this.setStrokeColorN(args);
  14763. break;
  14764. case _util.OPS.setFillColorN:
  14765. this.setFillColorN(args);
  14766. break;
  14767. case _util.OPS.shadingFill:
  14768. this.shadingFill(args[0]);
  14769. break;
  14770. case _util.OPS.setDash:
  14771. this.setDash(args[0], args[1]);
  14772. break;
  14773. case _util.OPS.setRenderingIntent:
  14774. this.setRenderingIntent(args[0]);
  14775. break;
  14776. case _util.OPS.setFlatness:
  14777. this.setFlatness(args[0]);
  14778. break;
  14779. case _util.OPS.setGState:
  14780. this.setGState(args[0]);
  14781. break;
  14782. case _util.OPS.fill:
  14783. this.fill();
  14784. break;
  14785. case _util.OPS.eoFill:
  14786. this.eoFill();
  14787. break;
  14788. case _util.OPS.stroke:
  14789. this.stroke();
  14790. break;
  14791. case _util.OPS.fillStroke:
  14792. this.fillStroke();
  14793. break;
  14794. case _util.OPS.eoFillStroke:
  14795. this.eoFillStroke();
  14796. break;
  14797. case _util.OPS.clip:
  14798. this.clip("nonzero");
  14799. break;
  14800. case _util.OPS.eoClip:
  14801. this.clip("evenodd");
  14802. break;
  14803. case _util.OPS.paintSolidColorImageMask:
  14804. this.paintSolidColorImageMask();
  14805. break;
  14806. case _util.OPS.paintImageXObject:
  14807. this.paintImageXObject(args[0]);
  14808. break;
  14809. case _util.OPS.paintInlineImageXObject:
  14810. this.paintInlineImageXObject(args[0]);
  14811. break;
  14812. case _util.OPS.paintImageMaskXObject:
  14813. this.paintImageMaskXObject(args[0]);
  14814. break;
  14815. case _util.OPS.paintFormXObjectBegin:
  14816. this.paintFormXObjectBegin(args[0], args[1]);
  14817. break;
  14818. case _util.OPS.paintFormXObjectEnd:
  14819. this.paintFormXObjectEnd();
  14820. break;
  14821. case _util.OPS.closePath:
  14822. this.closePath();
  14823. break;
  14824. case _util.OPS.closeStroke:
  14825. this.closeStroke();
  14826. break;
  14827. case _util.OPS.closeFillStroke:
  14828. this.closeFillStroke();
  14829. break;
  14830. case _util.OPS.closeEOFillStroke:
  14831. this.closeEOFillStroke();
  14832. break;
  14833. case _util.OPS.nextLine:
  14834. this.nextLine();
  14835. break;
  14836. case _util.OPS.transform:
  14837. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  14838. break;
  14839. case _util.OPS.constructPath:
  14840. this.constructPath(args[0], args[1]);
  14841. break;
  14842. case _util.OPS.endPath:
  14843. this.endPath();
  14844. break;
  14845. case 92:
  14846. this.group(opTreeElement.items);
  14847. break;
  14848. default:
  14849. (0, _util.warn)(`Unimplemented operator ${fn}`);
  14850. break;
  14851. }
  14852. }
  14853. }
  14854. setWordSpacing(wordSpacing) {
  14855. this.current.wordSpacing = wordSpacing;
  14856. }
  14857. setCharSpacing(charSpacing) {
  14858. this.current.charSpacing = charSpacing;
  14859. }
  14860. nextLine() {
  14861. this.moveText(0, this.current.leading);
  14862. }
  14863. setTextMatrix(a, b, c, d, e, f) {
  14864. const current = this.current;
  14865. current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
  14866. current.textMatrixScale = Math.hypot(a, b);
  14867. current.x = current.lineX = 0;
  14868. current.y = current.lineY = 0;
  14869. current.xcoords = [];
  14870. current.ycoords = [];
  14871. current.tspan = this.svgFactory.createElement("svg:tspan");
  14872. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  14873. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  14874. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  14875. current.txtElement = this.svgFactory.createElement("svg:text");
  14876. current.txtElement.append(current.tspan);
  14877. }
  14878. beginText() {
  14879. const current = this.current;
  14880. current.x = current.lineX = 0;
  14881. current.y = current.lineY = 0;
  14882. current.textMatrix = _util.IDENTITY_MATRIX;
  14883. current.lineMatrix = _util.IDENTITY_MATRIX;
  14884. current.textMatrixScale = 1;
  14885. current.tspan = this.svgFactory.createElement("svg:tspan");
  14886. current.txtElement = this.svgFactory.createElement("svg:text");
  14887. current.txtgrp = this.svgFactory.createElement("svg:g");
  14888. current.xcoords = [];
  14889. current.ycoords = [];
  14890. }
  14891. moveText(x, y) {
  14892. const current = this.current;
  14893. current.x = current.lineX += x;
  14894. current.y = current.lineY += y;
  14895. current.xcoords = [];
  14896. current.ycoords = [];
  14897. current.tspan = this.svgFactory.createElement("svg:tspan");
  14898. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  14899. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  14900. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  14901. }
  14902. showText(glyphs) {
  14903. const current = this.current;
  14904. const font = current.font;
  14905. const fontSize = current.fontSize;
  14906. if (fontSize === 0) {
  14907. return;
  14908. }
  14909. const fontSizeScale = current.fontSizeScale;
  14910. const charSpacing = current.charSpacing;
  14911. const wordSpacing = current.wordSpacing;
  14912. const fontDirection = current.fontDirection;
  14913. const textHScale = current.textHScale * fontDirection;
  14914. const vertical = font.vertical;
  14915. const spacingDir = vertical ? 1 : -1;
  14916. const defaultVMetrics = font.defaultVMetrics;
  14917. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  14918. let x = 0;
  14919. for (const glyph of glyphs) {
  14920. if (glyph === null) {
  14921. x += fontDirection * wordSpacing;
  14922. continue;
  14923. } else if (typeof glyph === "number") {
  14924. x += spacingDir * glyph * fontSize / 1000;
  14925. continue;
  14926. }
  14927. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  14928. const character = glyph.fontChar;
  14929. let scaledX, scaledY;
  14930. let width = glyph.width;
  14931. if (vertical) {
  14932. let vx;
  14933. const vmetric = glyph.vmetric || defaultVMetrics;
  14934. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  14935. vx = -vx * widthAdvanceScale;
  14936. const vy = vmetric[2] * widthAdvanceScale;
  14937. width = vmetric ? -vmetric[0] : width;
  14938. scaledX = vx / fontSizeScale;
  14939. scaledY = (x + vy) / fontSizeScale;
  14940. } else {
  14941. scaledX = x / fontSizeScale;
  14942. scaledY = 0;
  14943. }
  14944. if (glyph.isInFont || font.missingFile) {
  14945. current.xcoords.push(current.x + scaledX);
  14946. if (vertical) {
  14947. current.ycoords.push(-current.y + scaledY);
  14948. }
  14949. current.tspan.textContent += character;
  14950. } else {}
  14951. let charWidth;
  14952. if (vertical) {
  14953. charWidth = width * widthAdvanceScale - spacing * fontDirection;
  14954. } else {
  14955. charWidth = width * widthAdvanceScale + spacing * fontDirection;
  14956. }
  14957. x += charWidth;
  14958. }
  14959. current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
  14960. if (vertical) {
  14961. current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
  14962. } else {
  14963. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  14964. }
  14965. if (vertical) {
  14966. current.y -= x;
  14967. } else {
  14968. current.x += x * textHScale;
  14969. }
  14970. current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
  14971. current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
  14972. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  14973. current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
  14974. }
  14975. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  14976. current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
  14977. }
  14978. const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
  14979. if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  14980. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  14981. current.tspan.setAttributeNS(null, "fill", current.fillColor);
  14982. }
  14983. if (current.fillAlpha < 1) {
  14984. current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  14985. }
  14986. } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
  14987. current.tspan.setAttributeNS(null, "fill", "transparent");
  14988. } else {
  14989. current.tspan.setAttributeNS(null, "fill", "none");
  14990. }
  14991. if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
  14992. const lineWidthScale = 1 / (current.textMatrixScale || 1);
  14993. this._setStrokeAttributes(current.tspan, lineWidthScale);
  14994. }
  14995. let textMatrix = current.textMatrix;
  14996. if (current.textRise !== 0) {
  14997. textMatrix = textMatrix.slice();
  14998. textMatrix[5] += current.textRise;
  14999. }
  15000. current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
  15001. current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
  15002. current.txtElement.append(current.tspan);
  15003. current.txtgrp.append(current.txtElement);
  15004. this._ensureTransformGroup().append(current.txtElement);
  15005. }
  15006. setLeadingMoveText(x, y) {
  15007. this.setLeading(-y);
  15008. this.moveText(x, y);
  15009. }
  15010. addFontStyle(fontObj) {
  15011. if (!fontObj.data) {
  15012. throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
  15013. }
  15014. if (!this.cssStyle) {
  15015. this.cssStyle = this.svgFactory.createElement("svg:style");
  15016. this.cssStyle.setAttributeNS(null, "type", "text/css");
  15017. this.defs.append(this.cssStyle);
  15018. }
  15019. const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  15020. this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
  15021. }
  15022. setFont(details) {
  15023. const current = this.current;
  15024. const fontObj = this.commonObjs.get(details[0]);
  15025. let size = details[1];
  15026. current.font = fontObj;
  15027. if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
  15028. this.addFontStyle(fontObj);
  15029. this.embeddedFonts[fontObj.loadedName] = fontObj;
  15030. }
  15031. current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  15032. let bold = "normal";
  15033. if (fontObj.black) {
  15034. bold = "900";
  15035. } else if (fontObj.bold) {
  15036. bold = "bold";
  15037. }
  15038. const italic = fontObj.italic ? "italic" : "normal";
  15039. if (size < 0) {
  15040. size = -size;
  15041. current.fontDirection = -1;
  15042. } else {
  15043. current.fontDirection = 1;
  15044. }
  15045. current.fontSize = size;
  15046. current.fontFamily = fontObj.loadedName;
  15047. current.fontWeight = bold;
  15048. current.fontStyle = italic;
  15049. current.tspan = this.svgFactory.createElement("svg:tspan");
  15050. current.tspan.setAttributeNS(null, "y", pf(-current.y));
  15051. current.xcoords = [];
  15052. current.ycoords = [];
  15053. }
  15054. endText() {
  15055. const current = this.current;
  15056. if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
  15057. current.element = current.txtElement;
  15058. this.clip("nonzero");
  15059. this.endPath();
  15060. }
  15061. }
  15062. setLineWidth(width) {
  15063. if (width > 0) {
  15064. this.current.lineWidth = width;
  15065. }
  15066. }
  15067. setLineCap(style) {
  15068. this.current.lineCap = LINE_CAP_STYLES[style];
  15069. }
  15070. setLineJoin(style) {
  15071. this.current.lineJoin = LINE_JOIN_STYLES[style];
  15072. }
  15073. setMiterLimit(limit) {
  15074. this.current.miterLimit = limit;
  15075. }
  15076. setStrokeAlpha(strokeAlpha) {
  15077. this.current.strokeAlpha = strokeAlpha;
  15078. }
  15079. setStrokeRGBColor(r, g, b) {
  15080. this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
  15081. }
  15082. setFillAlpha(fillAlpha) {
  15083. this.current.fillAlpha = fillAlpha;
  15084. }
  15085. setFillRGBColor(r, g, b) {
  15086. this.current.fillColor = _util.Util.makeHexColor(r, g, b);
  15087. this.current.tspan = this.svgFactory.createElement("svg:tspan");
  15088. this.current.xcoords = [];
  15089. this.current.ycoords = [];
  15090. }
  15091. setStrokeColorN(args) {
  15092. this.current.strokeColor = this._makeColorN_Pattern(args);
  15093. }
  15094. setFillColorN(args) {
  15095. this.current.fillColor = this._makeColorN_Pattern(args);
  15096. }
  15097. shadingFill(args) {
  15098. const width = this.viewport.width;
  15099. const height = this.viewport.height;
  15100. const inv = _util.Util.inverseTransform(this.transformMatrix);
  15101. const bl = _util.Util.applyTransform([0, 0], inv);
  15102. const br = _util.Util.applyTransform([0, height], inv);
  15103. const ul = _util.Util.applyTransform([width, 0], inv);
  15104. const ur = _util.Util.applyTransform([width, height], inv);
  15105. const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  15106. const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  15107. const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  15108. const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  15109. const rect = this.svgFactory.createElement("svg:rect");
  15110. rect.setAttributeNS(null, "x", x0);
  15111. rect.setAttributeNS(null, "y", y0);
  15112. rect.setAttributeNS(null, "width", x1 - x0);
  15113. rect.setAttributeNS(null, "height", y1 - y0);
  15114. rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
  15115. if (this.current.fillAlpha < 1) {
  15116. rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
  15117. }
  15118. this._ensureTransformGroup().append(rect);
  15119. }
  15120. _makeColorN_Pattern(args) {
  15121. if (args[0] === "TilingPattern") {
  15122. return this._makeTilingPattern(args);
  15123. }
  15124. return this._makeShadingPattern(args);
  15125. }
  15126. _makeTilingPattern(args) {
  15127. const color = args[1];
  15128. const operatorList = args[2];
  15129. const matrix = args[3] || _util.IDENTITY_MATRIX;
  15130. const [x0, y0, x1, y1] = args[4];
  15131. const xstep = args[5];
  15132. const ystep = args[6];
  15133. const paintType = args[7];
  15134. const tilingId = `shading${shadingCount++}`;
  15135. const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
  15136. const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
  15137. const txstep = xstep * xscale;
  15138. const tystep = ystep * yscale;
  15139. const tiling = this.svgFactory.createElement("svg:pattern");
  15140. tiling.setAttributeNS(null, "id", tilingId);
  15141. tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
  15142. tiling.setAttributeNS(null, "width", txstep);
  15143. tiling.setAttributeNS(null, "height", tystep);
  15144. tiling.setAttributeNS(null, "x", `${tx0}`);
  15145. tiling.setAttributeNS(null, "y", `${ty0}`);
  15146. const svg = this.svg;
  15147. const transformMatrix = this.transformMatrix;
  15148. const fillColor = this.current.fillColor;
  15149. const strokeColor = this.current.strokeColor;
  15150. const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
  15151. this.svg = bbox;
  15152. this.transformMatrix = matrix;
  15153. if (paintType === 2) {
  15154. const cssColor = _util.Util.makeHexColor(...color);
  15155. this.current.fillColor = cssColor;
  15156. this.current.strokeColor = cssColor;
  15157. }
  15158. this.executeOpTree(this.convertOpList(operatorList));
  15159. this.svg = svg;
  15160. this.transformMatrix = transformMatrix;
  15161. this.current.fillColor = fillColor;
  15162. this.current.strokeColor = strokeColor;
  15163. tiling.append(bbox.childNodes[0]);
  15164. this.defs.append(tiling);
  15165. return `url(#${tilingId})`;
  15166. }
  15167. _makeShadingPattern(args) {
  15168. if (typeof args === "string") {
  15169. args = this.objs.get(args);
  15170. }
  15171. switch (args[0]) {
  15172. case "RadialAxial":
  15173. const shadingId = `shading${shadingCount++}`;
  15174. const colorStops = args[3];
  15175. let gradient;
  15176. switch (args[1]) {
  15177. case "axial":
  15178. const point0 = args[4];
  15179. const point1 = args[5];
  15180. gradient = this.svgFactory.createElement("svg:linearGradient");
  15181. gradient.setAttributeNS(null, "id", shadingId);
  15182. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  15183. gradient.setAttributeNS(null, "x1", point0[0]);
  15184. gradient.setAttributeNS(null, "y1", point0[1]);
  15185. gradient.setAttributeNS(null, "x2", point1[0]);
  15186. gradient.setAttributeNS(null, "y2", point1[1]);
  15187. break;
  15188. case "radial":
  15189. const focalPoint = args[4];
  15190. const circlePoint = args[5];
  15191. const focalRadius = args[6];
  15192. const circleRadius = args[7];
  15193. gradient = this.svgFactory.createElement("svg:radialGradient");
  15194. gradient.setAttributeNS(null, "id", shadingId);
  15195. gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
  15196. gradient.setAttributeNS(null, "cx", circlePoint[0]);
  15197. gradient.setAttributeNS(null, "cy", circlePoint[1]);
  15198. gradient.setAttributeNS(null, "r", circleRadius);
  15199. gradient.setAttributeNS(null, "fx", focalPoint[0]);
  15200. gradient.setAttributeNS(null, "fy", focalPoint[1]);
  15201. gradient.setAttributeNS(null, "fr", focalRadius);
  15202. break;
  15203. default:
  15204. throw new Error(`Unknown RadialAxial type: ${args[1]}`);
  15205. }
  15206. for (const colorStop of colorStops) {
  15207. const stop = this.svgFactory.createElement("svg:stop");
  15208. stop.setAttributeNS(null, "offset", colorStop[0]);
  15209. stop.setAttributeNS(null, "stop-color", colorStop[1]);
  15210. gradient.append(stop);
  15211. }
  15212. this.defs.append(gradient);
  15213. return `url(#${shadingId})`;
  15214. case "Mesh":
  15215. (0, _util.warn)("Unimplemented pattern Mesh");
  15216. return null;
  15217. case "Dummy":
  15218. return "hotpink";
  15219. default:
  15220. throw new Error(`Unknown IR type: ${args[0]}`);
  15221. }
  15222. }
  15223. setDash(dashArray, dashPhase) {
  15224. this.current.dashArray = dashArray;
  15225. this.current.dashPhase = dashPhase;
  15226. }
  15227. constructPath(ops, args) {
  15228. const current = this.current;
  15229. let x = current.x,
  15230. y = current.y;
  15231. let d = [];
  15232. let j = 0;
  15233. for (const op of ops) {
  15234. switch (op | 0) {
  15235. case _util.OPS.rectangle:
  15236. x = args[j++];
  15237. y = args[j++];
  15238. const width = args[j++];
  15239. const height = args[j++];
  15240. const xw = x + width;
  15241. const yh = y + height;
  15242. d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
  15243. break;
  15244. case _util.OPS.moveTo:
  15245. x = args[j++];
  15246. y = args[j++];
  15247. d.push("M", pf(x), pf(y));
  15248. break;
  15249. case _util.OPS.lineTo:
  15250. x = args[j++];
  15251. y = args[j++];
  15252. d.push("L", pf(x), pf(y));
  15253. break;
  15254. case _util.OPS.curveTo:
  15255. x = args[j + 4];
  15256. y = args[j + 5];
  15257. d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  15258. j += 6;
  15259. break;
  15260. case _util.OPS.curveTo2:
  15261. d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  15262. x = args[j + 2];
  15263. y = args[j + 3];
  15264. j += 4;
  15265. break;
  15266. case _util.OPS.curveTo3:
  15267. x = args[j + 2];
  15268. y = args[j + 3];
  15269. d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  15270. j += 4;
  15271. break;
  15272. case _util.OPS.closePath:
  15273. d.push("Z");
  15274. break;
  15275. }
  15276. }
  15277. d = d.join(" ");
  15278. if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
  15279. d = current.path.getAttributeNS(null, "d") + d;
  15280. } else {
  15281. current.path = this.svgFactory.createElement("svg:path");
  15282. this._ensureTransformGroup().append(current.path);
  15283. }
  15284. current.path.setAttributeNS(null, "d", d);
  15285. current.path.setAttributeNS(null, "fill", "none");
  15286. current.element = current.path;
  15287. current.setCurrentPoint(x, y);
  15288. }
  15289. endPath() {
  15290. const current = this.current;
  15291. current.path = null;
  15292. if (!this.pendingClip) {
  15293. return;
  15294. }
  15295. if (!current.element) {
  15296. this.pendingClip = null;
  15297. return;
  15298. }
  15299. const clipId = `clippath${clipCount++}`;
  15300. const clipPath = this.svgFactory.createElement("svg:clipPath");
  15301. clipPath.setAttributeNS(null, "id", clipId);
  15302. clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
  15303. const clipElement = current.element.cloneNode(true);
  15304. if (this.pendingClip === "evenodd") {
  15305. clipElement.setAttributeNS(null, "clip-rule", "evenodd");
  15306. } else {
  15307. clipElement.setAttributeNS(null, "clip-rule", "nonzero");
  15308. }
  15309. this.pendingClip = null;
  15310. clipPath.append(clipElement);
  15311. this.defs.append(clipPath);
  15312. if (current.activeClipUrl) {
  15313. current.clipGroup = null;
  15314. for (const prev of this.extraStack) {
  15315. prev.clipGroup = null;
  15316. }
  15317. clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
  15318. }
  15319. current.activeClipUrl = `url(#${clipId})`;
  15320. this.tgrp = null;
  15321. }
  15322. clip(type) {
  15323. this.pendingClip = type;
  15324. }
  15325. closePath() {
  15326. const current = this.current;
  15327. if (current.path) {
  15328. const d = `${current.path.getAttributeNS(null, "d")}Z`;
  15329. current.path.setAttributeNS(null, "d", d);
  15330. }
  15331. }
  15332. setLeading(leading) {
  15333. this.current.leading = -leading;
  15334. }
  15335. setTextRise(textRise) {
  15336. this.current.textRise = textRise;
  15337. }
  15338. setTextRenderingMode(textRenderingMode) {
  15339. this.current.textRenderingMode = textRenderingMode;
  15340. }
  15341. setHScale(scale) {
  15342. this.current.textHScale = scale / 100;
  15343. }
  15344. setRenderingIntent(intent) {}
  15345. setFlatness(flatness) {}
  15346. setGState(states) {
  15347. for (const [key, value] of states) {
  15348. switch (key) {
  15349. case "LW":
  15350. this.setLineWidth(value);
  15351. break;
  15352. case "LC":
  15353. this.setLineCap(value);
  15354. break;
  15355. case "LJ":
  15356. this.setLineJoin(value);
  15357. break;
  15358. case "ML":
  15359. this.setMiterLimit(value);
  15360. break;
  15361. case "D":
  15362. this.setDash(value[0], value[1]);
  15363. break;
  15364. case "RI":
  15365. this.setRenderingIntent(value);
  15366. break;
  15367. case "FL":
  15368. this.setFlatness(value);
  15369. break;
  15370. case "Font":
  15371. this.setFont(value);
  15372. break;
  15373. case "CA":
  15374. this.setStrokeAlpha(value);
  15375. break;
  15376. case "ca":
  15377. this.setFillAlpha(value);
  15378. break;
  15379. default:
  15380. (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
  15381. break;
  15382. }
  15383. }
  15384. }
  15385. fill() {
  15386. const current = this.current;
  15387. if (current.element) {
  15388. current.element.setAttributeNS(null, "fill", current.fillColor);
  15389. current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
  15390. this.endPath();
  15391. }
  15392. }
  15393. stroke() {
  15394. const current = this.current;
  15395. if (current.element) {
  15396. this._setStrokeAttributes(current.element);
  15397. current.element.setAttributeNS(null, "fill", "none");
  15398. this.endPath();
  15399. }
  15400. }
  15401. _setStrokeAttributes(element, lineWidthScale = 1) {
  15402. const current = this.current;
  15403. let dashArray = current.dashArray;
  15404. if (lineWidthScale !== 1 && dashArray.length > 0) {
  15405. dashArray = dashArray.map(function (value) {
  15406. return lineWidthScale * value;
  15407. });
  15408. }
  15409. element.setAttributeNS(null, "stroke", current.strokeColor);
  15410. element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
  15411. element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
  15412. element.setAttributeNS(null, "stroke-linecap", current.lineCap);
  15413. element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
  15414. element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
  15415. element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
  15416. element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
  15417. }
  15418. eoFill() {
  15419. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  15420. this.fill();
  15421. }
  15422. fillStroke() {
  15423. this.stroke();
  15424. this.fill();
  15425. }
  15426. eoFillStroke() {
  15427. this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
  15428. this.fillStroke();
  15429. }
  15430. closeStroke() {
  15431. this.closePath();
  15432. this.stroke();
  15433. }
  15434. closeFillStroke() {
  15435. this.closePath();
  15436. this.fillStroke();
  15437. }
  15438. closeEOFillStroke() {
  15439. this.closePath();
  15440. this.eoFillStroke();
  15441. }
  15442. paintSolidColorImageMask() {
  15443. const rect = this.svgFactory.createElement("svg:rect");
  15444. rect.setAttributeNS(null, "x", "0");
  15445. rect.setAttributeNS(null, "y", "0");
  15446. rect.setAttributeNS(null, "width", "1px");
  15447. rect.setAttributeNS(null, "height", "1px");
  15448. rect.setAttributeNS(null, "fill", this.current.fillColor);
  15449. this._ensureTransformGroup().append(rect);
  15450. }
  15451. paintImageXObject(objId) {
  15452. const imgData = this.getObject(objId);
  15453. if (!imgData) {
  15454. (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
  15455. return;
  15456. }
  15457. this.paintInlineImageXObject(imgData);
  15458. }
  15459. paintInlineImageXObject(imgData, mask) {
  15460. const width = imgData.width;
  15461. const height = imgData.height;
  15462. const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
  15463. const cliprect = this.svgFactory.createElement("svg:rect");
  15464. cliprect.setAttributeNS(null, "x", "0");
  15465. cliprect.setAttributeNS(null, "y", "0");
  15466. cliprect.setAttributeNS(null, "width", pf(width));
  15467. cliprect.setAttributeNS(null, "height", pf(height));
  15468. this.current.element = cliprect;
  15469. this.clip("nonzero");
  15470. const imgEl = this.svgFactory.createElement("svg:image");
  15471. imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
  15472. imgEl.setAttributeNS(null, "x", "0");
  15473. imgEl.setAttributeNS(null, "y", pf(-height));
  15474. imgEl.setAttributeNS(null, "width", pf(width) + "px");
  15475. imgEl.setAttributeNS(null, "height", pf(height) + "px");
  15476. imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
  15477. if (mask) {
  15478. mask.append(imgEl);
  15479. } else {
  15480. this._ensureTransformGroup().append(imgEl);
  15481. }
  15482. }
  15483. paintImageMaskXObject(img) {
  15484. const imgData = this.getObject(img.data, img);
  15485. if (imgData.bitmap) {
  15486. (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
  15487. return;
  15488. }
  15489. const current = this.current;
  15490. const width = imgData.width;
  15491. const height = imgData.height;
  15492. const fillColor = current.fillColor;
  15493. current.maskId = `mask${maskCount++}`;
  15494. const mask = this.svgFactory.createElement("svg:mask");
  15495. mask.setAttributeNS(null, "id", current.maskId);
  15496. const rect = this.svgFactory.createElement("svg:rect");
  15497. rect.setAttributeNS(null, "x", "0");
  15498. rect.setAttributeNS(null, "y", "0");
  15499. rect.setAttributeNS(null, "width", pf(width));
  15500. rect.setAttributeNS(null, "height", pf(height));
  15501. rect.setAttributeNS(null, "fill", fillColor);
  15502. rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
  15503. this.defs.append(mask);
  15504. this._ensureTransformGroup().append(rect);
  15505. this.paintInlineImageXObject(imgData, mask);
  15506. }
  15507. paintFormXObjectBegin(matrix, bbox) {
  15508. if (Array.isArray(matrix) && matrix.length === 6) {
  15509. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  15510. }
  15511. if (bbox) {
  15512. const width = bbox[2] - bbox[0];
  15513. const height = bbox[3] - bbox[1];
  15514. const cliprect = this.svgFactory.createElement("svg:rect");
  15515. cliprect.setAttributeNS(null, "x", bbox[0]);
  15516. cliprect.setAttributeNS(null, "y", bbox[1]);
  15517. cliprect.setAttributeNS(null, "width", pf(width));
  15518. cliprect.setAttributeNS(null, "height", pf(height));
  15519. this.current.element = cliprect;
  15520. this.clip("nonzero");
  15521. this.endPath();
  15522. }
  15523. }
  15524. paintFormXObjectEnd() {}
  15525. _initialize(viewport) {
  15526. const svg = this.svgFactory.create(viewport.width, viewport.height);
  15527. const definitions = this.svgFactory.createElement("svg:defs");
  15528. svg.append(definitions);
  15529. this.defs = definitions;
  15530. const rootGroup = this.svgFactory.createElement("svg:g");
  15531. rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
  15532. svg.append(rootGroup);
  15533. this.svg = rootGroup;
  15534. return svg;
  15535. }
  15536. _ensureClipGroup() {
  15537. if (!this.current.clipGroup) {
  15538. const clipGroup = this.svgFactory.createElement("svg:g");
  15539. clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
  15540. this.svg.append(clipGroup);
  15541. this.current.clipGroup = clipGroup;
  15542. }
  15543. return this.current.clipGroup;
  15544. }
  15545. _ensureTransformGroup() {
  15546. if (!this.tgrp) {
  15547. this.tgrp = this.svgFactory.createElement("svg:g");
  15548. this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
  15549. if (this.current.activeClipUrl) {
  15550. this._ensureClipGroup().append(this.tgrp);
  15551. } else {
  15552. this.svg.append(this.tgrp);
  15553. }
  15554. }
  15555. return this.tgrp;
  15556. }
  15557. };
  15558. }
  15559. /***/ })
  15560. /******/ ]);
  15561. /************************************************************************/
  15562. /******/ // The module cache
  15563. /******/ var __webpack_module_cache__ = {};
  15564. /******/
  15565. /******/ // The require function
  15566. /******/ function __w_pdfjs_require__(moduleId) {
  15567. /******/ // Check if module is in cache
  15568. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  15569. /******/ if (cachedModule !== undefined) {
  15570. /******/ return cachedModule.exports;
  15571. /******/ }
  15572. /******/ // Create a new module (and put it into the cache)
  15573. /******/ var module = __webpack_module_cache__[moduleId] = {
  15574. /******/ // no module.id needed
  15575. /******/ // no module.loaded needed
  15576. /******/ exports: {}
  15577. /******/ };
  15578. /******/
  15579. /******/ // Execute the module function
  15580. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  15581. /******/
  15582. /******/ // Return the exports of the module
  15583. /******/ return module.exports;
  15584. /******/ }
  15585. /******/
  15586. /************************************************************************/
  15587. var __webpack_exports__ = {};
  15588. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  15589. (() => {
  15590. var exports = __webpack_exports__;
  15591. Object.defineProperty(exports, "__esModule", ({
  15592. value: true
  15593. }));
  15594. Object.defineProperty(exports, "AbortException", ({
  15595. enumerable: true,
  15596. get: function () {
  15597. return _util.AbortException;
  15598. }
  15599. }));
  15600. Object.defineProperty(exports, "AnnotationEditorLayer", ({
  15601. enumerable: true,
  15602. get: function () {
  15603. return _annotation_editor_layer.AnnotationEditorLayer;
  15604. }
  15605. }));
  15606. Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  15607. enumerable: true,
  15608. get: function () {
  15609. return _util.AnnotationEditorParamsType;
  15610. }
  15611. }));
  15612. Object.defineProperty(exports, "AnnotationEditorType", ({
  15613. enumerable: true,
  15614. get: function () {
  15615. return _util.AnnotationEditorType;
  15616. }
  15617. }));
  15618. Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  15619. enumerable: true,
  15620. get: function () {
  15621. return _tools.AnnotationEditorUIManager;
  15622. }
  15623. }));
  15624. Object.defineProperty(exports, "AnnotationLayer", ({
  15625. enumerable: true,
  15626. get: function () {
  15627. return _annotation_layer.AnnotationLayer;
  15628. }
  15629. }));
  15630. Object.defineProperty(exports, "AnnotationMode", ({
  15631. enumerable: true,
  15632. get: function () {
  15633. return _util.AnnotationMode;
  15634. }
  15635. }));
  15636. Object.defineProperty(exports, "CMapCompressionType", ({
  15637. enumerable: true,
  15638. get: function () {
  15639. return _util.CMapCompressionType;
  15640. }
  15641. }));
  15642. Object.defineProperty(exports, "FeatureTest", ({
  15643. enumerable: true,
  15644. get: function () {
  15645. return _util.FeatureTest;
  15646. }
  15647. }));
  15648. Object.defineProperty(exports, "GlobalWorkerOptions", ({
  15649. enumerable: true,
  15650. get: function () {
  15651. return _worker_options.GlobalWorkerOptions;
  15652. }
  15653. }));
  15654. Object.defineProperty(exports, "InvalidPDFException", ({
  15655. enumerable: true,
  15656. get: function () {
  15657. return _util.InvalidPDFException;
  15658. }
  15659. }));
  15660. Object.defineProperty(exports, "MissingPDFException", ({
  15661. enumerable: true,
  15662. get: function () {
  15663. return _util.MissingPDFException;
  15664. }
  15665. }));
  15666. Object.defineProperty(exports, "OPS", ({
  15667. enumerable: true,
  15668. get: function () {
  15669. return _util.OPS;
  15670. }
  15671. }));
  15672. Object.defineProperty(exports, "PDFDataRangeTransport", ({
  15673. enumerable: true,
  15674. get: function () {
  15675. return _api.PDFDataRangeTransport;
  15676. }
  15677. }));
  15678. Object.defineProperty(exports, "PDFDateString", ({
  15679. enumerable: true,
  15680. get: function () {
  15681. return _display_utils.PDFDateString;
  15682. }
  15683. }));
  15684. Object.defineProperty(exports, "PDFWorker", ({
  15685. enumerable: true,
  15686. get: function () {
  15687. return _api.PDFWorker;
  15688. }
  15689. }));
  15690. Object.defineProperty(exports, "PasswordResponses", ({
  15691. enumerable: true,
  15692. get: function () {
  15693. return _util.PasswordResponses;
  15694. }
  15695. }));
  15696. Object.defineProperty(exports, "PermissionFlag", ({
  15697. enumerable: true,
  15698. get: function () {
  15699. return _util.PermissionFlag;
  15700. }
  15701. }));
  15702. Object.defineProperty(exports, "PixelsPerInch", ({
  15703. enumerable: true,
  15704. get: function () {
  15705. return _display_utils.PixelsPerInch;
  15706. }
  15707. }));
  15708. Object.defineProperty(exports, "RenderingCancelledException", ({
  15709. enumerable: true,
  15710. get: function () {
  15711. return _display_utils.RenderingCancelledException;
  15712. }
  15713. }));
  15714. Object.defineProperty(exports, "SVGGraphics", ({
  15715. enumerable: true,
  15716. get: function () {
  15717. return _svg.SVGGraphics;
  15718. }
  15719. }));
  15720. Object.defineProperty(exports, "UnexpectedResponseException", ({
  15721. enumerable: true,
  15722. get: function () {
  15723. return _util.UnexpectedResponseException;
  15724. }
  15725. }));
  15726. Object.defineProperty(exports, "Util", ({
  15727. enumerable: true,
  15728. get: function () {
  15729. return _util.Util;
  15730. }
  15731. }));
  15732. Object.defineProperty(exports, "VerbosityLevel", ({
  15733. enumerable: true,
  15734. get: function () {
  15735. return _util.VerbosityLevel;
  15736. }
  15737. }));
  15738. Object.defineProperty(exports, "XfaLayer", ({
  15739. enumerable: true,
  15740. get: function () {
  15741. return _xfa_layer.XfaLayer;
  15742. }
  15743. }));
  15744. Object.defineProperty(exports, "build", ({
  15745. enumerable: true,
  15746. get: function () {
  15747. return _api.build;
  15748. }
  15749. }));
  15750. Object.defineProperty(exports, "createPromiseCapability", ({
  15751. enumerable: true,
  15752. get: function () {
  15753. return _util.createPromiseCapability;
  15754. }
  15755. }));
  15756. Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  15757. enumerable: true,
  15758. get: function () {
  15759. return _util.createValidAbsoluteUrl;
  15760. }
  15761. }));
  15762. Object.defineProperty(exports, "getDocument", ({
  15763. enumerable: true,
  15764. get: function () {
  15765. return _api.getDocument;
  15766. }
  15767. }));
  15768. Object.defineProperty(exports, "getFilenameFromUrl", ({
  15769. enumerable: true,
  15770. get: function () {
  15771. return _display_utils.getFilenameFromUrl;
  15772. }
  15773. }));
  15774. Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  15775. enumerable: true,
  15776. get: function () {
  15777. return _display_utils.getPdfFilenameFromUrl;
  15778. }
  15779. }));
  15780. Object.defineProperty(exports, "getXfaPageViewport", ({
  15781. enumerable: true,
  15782. get: function () {
  15783. return _display_utils.getXfaPageViewport;
  15784. }
  15785. }));
  15786. Object.defineProperty(exports, "isDataScheme", ({
  15787. enumerable: true,
  15788. get: function () {
  15789. return _display_utils.isDataScheme;
  15790. }
  15791. }));
  15792. Object.defineProperty(exports, "isPdfFile", ({
  15793. enumerable: true,
  15794. get: function () {
  15795. return _display_utils.isPdfFile;
  15796. }
  15797. }));
  15798. Object.defineProperty(exports, "loadScript", ({
  15799. enumerable: true,
  15800. get: function () {
  15801. return _display_utils.loadScript;
  15802. }
  15803. }));
  15804. Object.defineProperty(exports, "renderTextLayer", ({
  15805. enumerable: true,
  15806. get: function () {
  15807. return _text_layer.renderTextLayer;
  15808. }
  15809. }));
  15810. Object.defineProperty(exports, "setLayerDimensions", ({
  15811. enumerable: true,
  15812. get: function () {
  15813. return _display_utils.setLayerDimensions;
  15814. }
  15815. }));
  15816. Object.defineProperty(exports, "shadow", ({
  15817. enumerable: true,
  15818. get: function () {
  15819. return _util.shadow;
  15820. }
  15821. }));
  15822. Object.defineProperty(exports, "updateTextLayer", ({
  15823. enumerable: true,
  15824. get: function () {
  15825. return _text_layer.updateTextLayer;
  15826. }
  15827. }));
  15828. Object.defineProperty(exports, "version", ({
  15829. enumerable: true,
  15830. get: function () {
  15831. return _api.version;
  15832. }
  15833. }));
  15834. var _util = __w_pdfjs_require__(1);
  15835. var _api = __w_pdfjs_require__(2);
  15836. var _display_utils = __w_pdfjs_require__(6);
  15837. var _text_layer = __w_pdfjs_require__(26);
  15838. var _annotation_editor_layer = __w_pdfjs_require__(27);
  15839. var _tools = __w_pdfjs_require__(5);
  15840. var _annotation_layer = __w_pdfjs_require__(32);
  15841. var _worker_options = __w_pdfjs_require__(14);
  15842. var _svg = __w_pdfjs_require__(35);
  15843. var _xfa_layer = __w_pdfjs_require__(34);
  15844. const pdfjsVersion = '3.5.141';
  15845. const pdfjsBuild = 'be0f6ee08';
  15846. })();
  15847. /******/ return __webpack_exports__;
  15848. /******/ })()
  15849. ;
  15850. });
  15851. //# sourceMappingURL=pdf.js.map